IT WORLD

Welcome To The World Of IT

Free Training Programs

Free Training For Everyone, Everywhere And Every Time

Free Source Code

A Lot Of Source Code Is Waiting For You

Free IT Document For You !

A Lot Of IT Document Is Waiting For You !!

Source Code Game

Source Code Of Some Simple Game

Showing posts with label Source Code C. Show all posts
Showing posts with label Source Code C. Show all posts

Monday, April 4, 2016

C program to shutdown or turn off computer

C Program to shutdown your computer: This program turn off i.e shutdown your computer system. Firstly it will asks you to shutdown your computer if you press 'y' then your computer will shutdown in 30 seconds, system function of "stdlib.h" is used to run an executable file shutdown.exe which is present in C:\WINDOWS\system32 in Windows XP. You can use various options while executing shutdown.exe, you can use -t option to specify number of seconds after which shutdown occurs.
Syntax: shutdown -s -t x; here x is the number of seconds after which shutdown will occur.
By default shutdown occur after 30 seconds. To shutdown immediately you can write "shutdown -s -t 0". If you wish to restart your computer then you can write "shutdown -r".
If you are using Turbo C Compiler then execute your program from command prompt or by opening the executable file from the folder. Press F9 to build your executable file from source program. When you run program from within the compiler by pressing Ctrl+F9 it may not work.

C programming code for Windows XP

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   char ch;
 
   printf("Do you want to shutdown your computer now (y/n)\n");
   scanf("%c", &ch);
 
   if (ch == 'y' || ch == 'Y')
      system("C:\\WINDOWS\\System32\\shutdown -s");
 
   return 0;
}

C programming code for Windows 7

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   system("C:\\WINDOWS\\System32\\shutdown /s");
 
   return 0;
}
To shutdown immediately use "C:\\WINDOWS\\System32\\ shutdown /s /t 0". To restart use /r instead of /s.

C programming code for Ubuntu Linux

#include <stdio.h>
 
int main() {
  system("shutdown -P now");
  return 0;
} 
You need to be logged in as root user for above program to execute otherwise you will get the message shutdown: Need to be rootnowspecifies that you want to shutdown immediately. '-P' option specifies you want to power off your machine. You can specify minutes as:
shutdown -P "number of minutes"
For more help or options type at terminal: man shutdown.

c program to get ip address

This c program prints ip (internet protocol) address of your computer, system function is used to execute the command ipconfig which prints ip address, subnet mask and default gateway. The code given below works for Windows xp and Windows 7. If you are using turbo c compiler then execute program from folder, it may not work when you are working in compiler and press Ctrl+F9 to run your program.

C programming code

#include<stdlib.h>
 
int main()
{
   system("C:\\Windows\\System32\\ipconfig");
 
   return 0;
}
Output of program: ( In Windows 7)
ip address
Only part of output is shown in image.

C program to print date

This c program prints current system date. To print date we will use getdate function.

C programming code (Works in Turbo C only)

#include <stdio.h>
#include <conio.h>
#include <dos.h>
 
int main()
{
   struct date d;
 
   getdate(&d);
 
   printf("Current system date is %d/%d/%d",d.da_day,d.da_mon,d.da_year);
   getch();
   return 0;
}
This code works in Turbo C only because it supports dos.h header file.

C program to add two complex numbers

C program to add two complex numbers: this program calculate the sum of two complex numbers which will be entered by the user and then prints it. User will have to enter the real and imaginary parts of two complex numbers. In our program we will add real parts and imaginary parts of complex numbers and prints the complex number, i is the symbol used for iota. For example if user entered two complex numbers as (1 + 2i) and (4 + 6 i) then output of program will be (5+8i). A structure is used to store complex number.

C programming code

#include <stdio.h>
 
struct complex
{
   int real, img;
};
 
int main()
{
   struct complex a, b, c;
 
   printf("Enter a and b where a + ib is the first complex number.\n");
   printf("a = ");
   scanf("%d", &a.real);
   printf("b = ");
   scanf("%d", &a.img);
   printf("Enter c and d where c + id is the second complex number.\n");
   printf("c = ");
   scanf("%d", &b.real);
   printf("d = ");
   scanf("%d", &b.img);
 
   c.real = a.real + b.real;
   c.img = a.img + b.img;
 
   if ( c.img >= 0 )
      printf("Sum of two complex numbers = %d + %di\n", c.real, c.img);
   else
      printf("Sum of two complex numbers = %d %di\n", c.real, c.img);
 
   return 0;
}
Output of c program to add two complex numbers is shown in image below:
output of c program to add two complex numbers

C program to generate random numbers

This c program generates pseudo random numbers using rand and random function(Turbo C compiler only). As the random numbers are generated by an algorithm used in a function they are pseudo random, this is the reason why pseudo word is used. Function rand() returns a pseudo random number between 0 and RAND_MAX. RAND_MAX is a constant which is platform dependent and equals the maximum value returned by rand function.

C programming code using rand

We use modulus operator in our program. If you evaluate a % b where a and b are integers then result will always be less than b for any set of values of a and b. For example
For a = 1243 and b = 100
a % b = 1243 % 100 = 43
For a = 99 and b = 100
a % b = 99 % 100 = 99
For a = 1000 and b = 100
a % b = 1000 % 100 = 0
In our program we print pseudo random numbers in range [0, 100]. So we calculate rand() % 100 which will return a number in [0, 99] so we add 1 to get the desired range.
#include <stdio.h>
#include <stdlib.h>
 
int main() {
  int c, n;
 
  printf("Ten random numbers in [1,100]\n");
 
  for (c = 1; c <= 10; c++) {
    n = rand() % 100 + 1;
    printf("%d\n", n);
  }
 
  return 0;
}
If you rerun this program you will get same set of numbers. To get different numbers every time you can use: srand(unisgned int seed) function, here seed is an unsigned integer. So you will need a different value of seed every time you run the program for that you can use current time which will always be different so you will get a different set of numbers. By default seed = 1 if you do not use srand function.

C programming code using random function(Turbo C compiler only)

randomize function is used to initialize random number generator. If you don't use it then you will get same random numbers each time you run the program.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
 
int main()
{
   int n, max, num, c;
 
   printf("Enter the number of random numbers you want\n");
   scanf("%d", &n);
 
   printf("Enter the maximum value of random number\n");
   scanf("%d", &max);
 
   printf("%d random numbers from 0 to %d are :-\n", n, max);
 
   randomize();
 
   for (c = 1; c <= n; c++)
   {
      num = random(max);
      printf("%d\n",num);         
   }
 
   getch();
   return 0;
}

C program to delete a file

This c program deletes a file which is entered by the user, the file to be deleted should be present in the directory in which the executable file of this program is present. Extension of the file should also be entered, remove macro is used to delete the file. If there is an error in deleting the file then an error will be displayed using perror function.

C programming code

#include<stdio.h>
 
main()
{
   int status;
   char file_name[25];
 
   printf("Enter the name of file you wish to delete\n");
   gets(file_name);
 
   status = remove(file_name);
 
   if( status == 0 )
      printf("%s file deleted successfully.\n",file_name);
   else
   {
      printf("Unable to delete the file\n");
      perror("Error");
   }
 
   return 0;
}
Output of program:
output of c program to delete file
Deleted file doesn't go to trash or recycle bin so you may not be able to recover it. Deleted files can be recovered using special recovery software if the files are not overwritten on the storage medium.

C program to list files in directory

This program list all files present in a directory/folder in which this executable file is present. For example if this executable file is present in C:\\TC\\BIN then it will lists all the files present in C:\\TC\\BIN.

C programming code(Turbo C compiler only)

#include <stdio.h>
#include <conio.h>
#include <dir.h>
 
int main()
{
   int done;
   struct ffblk a;
 
   printf("Press any key to view the files in the current directory\n");
 
   getch();
 
   done = findfirst("*.*",&a,0);
 
   while(!done)
   {
      printf("%s\n",a.ff_name);
      done = findnext(&a);
   }
 
   getch();
   return 0;
}
Obviously you will get a different output when you will execute this file on your computer.

C program to merge two files

This c program merges two files and stores their contents in another file. The files which are to be merged are opened in read mode and the file which contains content of both the files is opened in write mode. To merge two files first we open a file and read it character by character and store the read contents in another file then we read the contents of another file and store it in file, we read two files until EOF (end of file) is reached.

C programming code

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   FILE *fs1, *fs2, *ft;
 
   char ch, file1[20], file2[20], file3[20];
 
   printf("Enter name of first file\n");
   gets(file1);
 
   printf("Enter name of second file\n");
   gets(file2);
 
   printf("Enter name of file which will store contents of two files\n");
   gets(file3);
 
   fs1 = fopen(file1,"r");
   fs2 = fopen(file2,"r");
 
   if( fs1 == NULL || fs2 == NULL )
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      getch();
      exit(EXIT_FAILURE);
   }
 
   ft = fopen(file3,"w");
 
   if( ft == NULL )
   {
      perror("Error ");
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
 
   while( ( ch = fgetc(fs1) ) != EOF )
      fputc(ch,ft);
 
   while( ( ch = fgetc(fs2) ) != EOF )
      fputc(ch,ft);
 
   printf("Two files were merged into %s file successfully.\n",file3);
 
   fclose(fs1);
   fclose(fs2);
   fclose(ft);
 
   return 0;
}
Output of program:
merge files program

C program to copy files

C program to copy files: This program copies a file, firstly you will specify the file to copy and then you will enter the name of target file, You will have to mention the extension of file also. We will open the file that we wish to copy in read mode and target file in write mode.

C programming code

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   char ch, source_file[20], target_file[20];
   FILE *source, *target;
 
   printf("Enter name of file to copy\n");
   gets(source_file);
 
   source = fopen(source_file, "r");
 
   if( source == NULL )
   {
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
 
   printf("Enter name of target file\n");
   gets(target_file);
 
   target = fopen(target_file, "w");
 
   if( target == NULL )
   {
      fclose(source);
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
 
   while( ( ch = fgetc(source) ) != EOF )
      fputc(ch, target);
 
   printf("File copied successfully.\n");
 
   fclose(source);
   fclose(target);
 
   return 0;
}
Output of program:
copy file program

C program to read a file

C program to read a file: This program reads a file entered by the user and displays its contents on the screen, fopen function is used to open a file it returns a pointer to structure FILE. FILE is a predefined structure in stdio.h . If the file is successfully opened then fopen returns a pointer to file and if it is unable to open a file then it returns NULL. fgetc function returns a character which is read from the file and fclose function closes the file. Opening a file means we bring file from disk to ram to perform operations on it. The file must be present in the directory in which the executable file of this code sis present.

C program to open a file

C programming code to open a file and to print it contents on screen.
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
   char ch, file_name[25];
   FILE *fp;
 
   printf("Enter the name of file you wish to see\n");
   gets(file_name);
 
   fp = fopen(file_name,"r"); // read mode
 
   if( fp == NULL )
   {
      perror("Error while opening the file.\n");
      exit(EXIT_FAILURE);
   }
 
   printf("The contents of %s file are :\n", file_name);
 
   while( ( ch = fgetc(fp) ) != EOF )
      printf("%c",ch);
 
   fclose(fp);
   return 0;
}
Output of program:
read file
There are blank lines present at end of file. In our program we have opened only one file but you can open multiple files in a single program and in different modes as desired. File handling is very important when we wish to store data permanently on a storage device. All variables and data of program is lost when program exits so if that data is required later we need to use files.

Anagram in c

Anagram in c: c program to check whether two strings are anagrams or not, string is assumed to consist of alphabets only. Two words are said to be anagrams of each other if the letters from one word can be rearranged to form the other word. From the above definition it is clear that two strings are anagrams if all characters in both strings occur same number of times. For example "abc" and "cab" are anagram strings, here every character 'a', 'b' and 'c' occur only one time in both strings. Our algorithm tries to find how many times characters appear in the strings and then comparing their corresponding counts.

C anagram programming code

#include <stdio.h>
 
int check_anagram(char [], char []);
 
int main()
{
   char a[100], b[100];
   int flag;
 
   printf("Enter first string\n");
   gets(a);
 
   printf("Enter second string\n");
   gets(b);
 
   flag = check_anagram(a, b);
 
   if (flag == 1)
      printf("\"%s\" and \"%s\" are anagrams.\n", a, b);
   else
      printf("\"%s\" and \"%s\" are not anagrams.\n", a, b);
 
   return 0;
}
 
int check_anagram(char a[], char b[])
{
   int first[26] = {0}, second[26] = {0}, c = 0;
 
   while (a[c] != '\0')
   {
      first[a[c]-'a']++;
      c++;
   }
 
   c = 0;
 
   while (b[c] != '\0')
   {
      second[b[c]-'a']++;
      c++;
   }
 
   for (c = 0; c < 26; c++)
   {
      if (first[c] != second[c])
         return 0;
   }
 
   return 1;
}
Output of program:
Anagram program

C program to find frequency of characters in a string

This program computes frequency of characters in a string i.e. which character is present how many times in a string. For example in the string "code" each of the character 'c', 'o', 'd', and 'e' has occurred one time. Only lower case alphabets are considered, other characters (uppercase and special characters) are ignored. You can easily modify this program to handle uppercase and special symbols.

C programming code

#include <stdio.h>
#include <string.h>
 
int main()
{
   char string[100];
   int c = 0, count[26] = {0};
 
   printf("Enter a string\n");
   gets(string);
 
   while (string[c] != '\0')
   {
      /** Considering characters from 'a' to 'z' only
          and ignoring others */
 
      if (string[c] >= 'a' && string[c] <= 'z') 
         count[string[c]-'a']++;
 
      c++;
   }
 
   for (c = 0; c < 26; c++)
   {
      /** Printing only those characters 
          whose count is at least 1 */
 
      if (count[c] != 0)
         printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }
 
   return 0;
}
Explanation of "count[string[c]-'a']++", suppose input string begins with 'a' so c is 0 initially and string[0] = 'a' and string[0]-'a' = 0 and we increment count[0] i.e. a has occurred one time and repeat this till complete string is scanned.
Output of program:
characters frequency in string
Did you notice that string in the output of program contains every alphabet at least once.

Calculating frequency using function

We will make a function which computes frequency of characters in input string and print in a table (see output image below).
#include <stdio.h>
#include <string.h>
 
void find_frequency(char [], int []);
 
int main()
{
   char string[100];
   int c, count[26] = {0};
 
   printf("Input a string\n");
   gets(string);
 
   find_frequency(string, count);
 
   printf("Character Count\n");
 
   for (c = 0 ; c < 26 ; c++)
      printf("%c \t  %d\n", c + 'a', count[c]);
 
   return 0;
}
 
void find_frequency(char s[], int count[]) {
   int c = 0;
 
   while (s[c] != '\0') {
      if (s[c] >= 'a' && s[c] <= 'z' ) 
         count[s[c]-'a']++;
      c++;
   }
}
Output of progran:
C characters frequency program output in table
We do not pass no of elements of array count[] to function find_frequency as they will always be 26. But you can pass if you wish to do so.

C program to swap two strings

C program to swap strings i.e. contents of two strings are interchanged.

C programming code

#include <stdio.h>
#include <string.h>
#include <malloc.h>
 
int main()
{
   char first[100], second[100], *temp;
 
   printf("Enter the first string\n");
   gets(first);
 
   printf("Enter the second string\n");
   gets(second);
 
   printf("\nBefore Swapping\n");
   printf("First string: %s\n",first);
   printf("Second string: %s\n\n",second);
 
   temp = (char*)malloc(100);
 
   strcpy(temp,first);
   strcpy(first,second);
   strcpy(second,temp);
 
   printf("After Swapping\n");
   printf("First string: %s\n",first);
   printf("Second string: %s\n",second);
 
   return 0;
}
Output of program:

C program to change case of a string

Strlwr function convert a string to lower case and strupr function convert a string to upper case.Here we will change string case with and without strlwr, strupr functions. These functions convert case of alphabets and ignore other characters which may be present in a string.

strlwr in c

#include <stdio.h>
#include <string.h>
 
int main()
{
   char string[1000];
 
   printf("Input a string to convert to lower case\n");
   gets(string);
 
   printf("Input string in lower case: \"%s\"\n",strlwr(string));
 
   return  0;
}

strupr in c

#include <stdio.h>
#include <string.h>
 
int main()
{
   char string[1000];
 
   printf("Input a string to convert to upper case\n");
   gets(string);
 
   printf("Input string in upper case: \"%s\"\n",strupr(string));
 
   return  0;
}

Change string to upper case without strupr

#include <stdio.h>
 
void upper_string(char []);
 
int main()
{
   char string[100];
 
   printf("Enter a string to convert it into upper case\n");
   gets(string);
 
   upper_string(string);
 
   printf("Entered string in upper case is \"%s\"\n", string);
 
   return 0;
}
 
void upper_string(char s[]) {
   int c = 0;
 
   while (s[c] != '\0') {
      if (s[c] >= 'a' && s[c] <= 'z') {
         s[c] = s[c] - 32;
      }
      c++;
   }
}

Change string to lower case without strlwr

#include <stdio.h>
 
void lower_string(char []);
 
int main()
{
   char string[100];
 
   printf("Enter a string to convert it into lower case\n");
   gets(string);
 
   lower_string(string);
 
   printf("Entered string in lower case is \"%s\"\n", string);
 
   return 0;
}
 
void lower_string(char s[]) {
   int c = 0;
 
   while (s[c] != '\0') {
      if (s[c] >= 'A' && s[c] <= 'Z') {
         s[c] = s[c] + 32;
      }
      c++;
   }
}
You can also implement functions using pointers.

C program to change case from upper to lower and lower to upper

Below program change case of alphabets if a lower case alphabet is found it is converted to upper and if an upper case is found it is converted to lower case.
#include <stdio.h>
 
int main () 
{
   int c = 0;
   char ch, s[1000];
 
   printf("Input a string\n");
   gets(s);
 
   while (s[c] != '\0') {
      ch = s[c];
      if (ch >= 'A' && ch <= 'Z')
         s[c] = s[c] + 32;
      else if (ch >= 'a' && ch <= 'z')
         s[c] = s[c] - 32;   
      c++;   
   }
 
   printf("%s\n", s);
 
   return 0;
}
Output of program:
Input a string
abcdefghijklmnopqrstuvwxyz{0123456789}ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ{0123456789}abcdefghijklmnopqrstuvwxyz
If a digit or special character is present in string it is left as it is.