Our website is made possible by displaying online advertisements to our visitors.Please consider supporting us by disabling your ad blocker.
Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu
Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Translate it in your own Language

Print this Job Post

Print Friendly and PDF

Saturday, May 3, 2014

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>
#include<conio.h> 
void 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);
    getch();
}

Output of program:



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>
 void 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);
   getch();
}

Output of program:


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: 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>
#include<conio.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);
   getch();
}
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:


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>
#include<conio.h> 
void 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 */
    if ( string[c] >= 'a' && string[c] <= 'z' ) 
    count[string[c]-'a']++;
    c++;
   }
    for ( c = 0 ; c < 26 ; c++ )
   {
     if( count[c] != 0 )
     printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }
   getch();
}

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:


C program to find nCr and nPr: This code calculate nCr which is n!/(r!*(n-r)!) and nPr = n!/(n-r)!

C program to find nCr using function


#include<stdio.h>
#include<conio.h> 
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
void main()
{
   int n, r;
   long ncr, npr;
   clrscr();
   printf("Enter the value of n and r\n");
   scanf("%d%d",&n,&r);
   ncr = find_ncr(n, r);
   npr = find_npr(n, r);
   printf("%dC%d = %ld\n", n, r, ncr);
   printf("%dP%d = %ld\n", n, r, npr);
   getch();
}
long find_ncr(int n, int r)
{
   long result;
   result = factorial(n)/(factorial(r)*factorial(n-r));
   return result;
}
long find_npr(int n, int r)
{
   long result;
   result = factorial(n)/factorial(n-r);
   return result;
long factorial(int n)
{
   int c;
   long result = 1;
   for( c = 1 ; c <= n ; c++ )
      result = result*c;
   return ( result );
}
C program to convert decimal to binary: c language code to convert an integer from decimal number system(base-10) to binary number system(base-2). Size of integer is assumed to be 32 bits. We use bitwise operators to perform the desired task. We right shift the original number by 31, 30, 29, ..., 1, 0 bits using a loop and bitwise AND the number obtained with 1(one), if the result is 1 then that bit is 1 otherwise it is 0(zero).

C programming code

#include <stdio.h>
#include<conio.h> 
void main()
{
  int n, c, k;
  printf("Enter an integer in decimal number system\n");
  scanf("%d", &n);
  printf("%d in binary number system is:\n", n);
  for (c = 31; c >= 0; c--)
  {
    k = n >> c;
    if (k & 1)
      printf("1");
    else
      printf("0");
  }
  printf("\n");
  getch();
}

Above code only prints binary of integer, but we may wish to perform operations on binary so in the code below we are storing the binary in a string. We create a function which returns a pointer to string which is the binary of the number passed as argument to the function.

C code to store decimal to binary conversion in a string

#include <stdio.h>
#include <stdlib.h>
#include<conio.h> 
char *decimal_to_binary(int);
void main()
{
   int n, c, k;
   char *pointer;
   printf("Enter an integer in decimal number system\n");
   scanf("%d",&n);
   pointer = decimal_to_binary(n);
   printf("Binary string of %d is: %s\n", n, t);
   free(pointer);
   getch();
}
 char *decimal_to_binary(int n)
{
   int c, d, count;
   char *pointer;
   count = 0;
   pointer = (char*)malloc(32+1);
   if ( pointer == NULL )
   exit(EXIT_FAILURE);
   for ( c = 31 ; c >= 0 ; c-- )
   {
      d = n >> c;
      if ( d & 1 )
         *(pointer+count) = 1 + '0';
      else
         *(pointer+count) = 0 + '0';
      count++;
   }
   *(pointer+count) = '\0';
    return  pointer;
}



C program to find hcf and lcm: The code below finds highest common factor and least common multiple of two integers. HCF is also known as greatest common divisor(GCD) or greatest common factor(gcf).

C programming code

#include <stdio.h>
#include<conio.h> 
void main() 
{
  int a, b, x, y, t, gcd, lcm;
  printf("Enter two integers\n");
  scanf("%d%d", &x, &y);
  a = x;
  b = y;
  while (b != 0) 
  {
    t = b;
    b = a % b;
    a = t;
  }
  gcd = a;
  lcm = (x*y)/gcd;
  printf("Greatest common divisor of %d and %d = %d\n", x, y, gcd);
  printf("Least common multiple of %d and %d = %d\n", x, y, lcm);
  getch();
}

C program to find hcf and lcm using recursion


#include <stdio.h>
#include<conio.h> 
long gcd(long, long);
void main() 
{
  long x, y, hcf, lcm;
  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
  getch();
}
 long gcd(long a, long b) 
{
  if (b == 0) 
{
    return a;
 }
  else 
{
  return gcd(b, a % b);
 }
}

C program to find hcf and lcm using function

#include <stdio.h>
#include<conio.h> 
long gcd(long, long);
void main() 
{
  long x, y, hcf, lcm;
  printf("Enter two integers\n");
  scanf("%ld%ld", &x, &y);
  hcf = gcd(x, y);
  lcm = (x*y)/hcf;
  printf("Greatest common divisor of %ld and %ld = %ld\n", x, y, hcf);
  printf("Least common multiple of %ld and %ld = %ld\n", x, y, lcm);
  getch();
}
 long gcd(long x, long y) 
{
  if (x == 0) 
{
    return y;
 }
   while (y != 0) 
{
   if (x > y) 
{
   x = x - y;
 }
  else 
{
  y = y - x;
}
}
  return x;
}

Friday, May 2, 2014

Factorial program in c: c code to find and print factorial of a number, three methods are given, first one uses for loop, second uses a function to find factorial and third using recursion. Factorial is represented using '!', so five factorial will be written as (5!), n factorial as (n!). Also
n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1.

Factorial program in c using for loop

#include <stdio.h>
#includde<conio.h>
void main()
{
  int c, n, fact = 1;
  printf("Enter a number to calculate it's factorial\n");
  scanf("%d", &n);
  for (c = 1; c <= n; c++)
  fact = fact * c;
  printf("Factorial of %d = %d\n", n, fact);
  getch();
}
---------------------------------------------------------------------------------------------

Factorial program in c using function


#include <stdio.h>
#include<conio.h>
long factorial(int);
void main()
{
  int number;
  long fact = 1;
  printf("Enter a number to calculate it's factorial\n");
  scanf("%d", &number);
  printf("%d! = %ld\n", number, factorial(number));
  getch();
}
 long factorial(int n)
{
  int c;
  long result = 1;
  for (c = 1; c <= n; c++)
  result = result * c;
  return result;
}
---------------------------------------------------------------------------------------------------------------------------------

Factorial program in c using recursion

#include<stdio.h>
#include<conio.h>
long factorial(int);
void main()
{
  int n;
  long f;
  printf("Enter an integer to find factorial\n");
  scanf("%d", &n);
  if (n < 0)
    printf("Negative integers are not allowed.\n");
  else
  {
    f = factorial(n);
    printf("%d! = %ld\n", n, f);
  }
    getch();
}
 long factorial(int n)
{
  if (n == 0)
  return 1;
  else
   return(n * factorial(n-1));
}
------------------------------------------------------------------------------------------------------------
Recursion is a technique in which a function calls itself, for example in above code factorial function is calling itself. To solve a problem using recursion you must first express its solution in recursive form.

                                                                                                    


C keeps a small set of keywords for its own use. These keywords cannot be used as identifiers in the program — a common restriction with modern languages. Where users of Old C may be surprised is in the introduction of some new keywords; if those names were used as identifiers in previous programs, then the programs will have to be changed. It will be easy to spot, because it will provoke your compiler into telling you about invalid names for things. Here is the list of keywords used in Standard C; you will notice that none of them use upper-case letters.



autodouble  int  struct
breakelse  long  switch
caseenum      register  typedef
charextern  return  union
constfloat  short  unsigned
continuefor  signed  void
defaultgoto  sizeof  volatile
doif  static  while

The new keywords that are likely to surprise old programmers are: constsignedvoid and volatile (although void has been around for a while). Eagle eyed readers may have noticed that some implementations of C used to use the keywords entryasm, and fortran. These are not part of the Standard, and few will mourn them.
  • C Pointer is used to allocate memory dynamically i.e. at run time.
  • C Pointer is a variable that stores the address of another variable.
  • The variable might be any of the data type such as int, float, char, double, short etc.
Syntax : data_type *var_name;Example : int *p;  char *p;
  • Where, * is used to denote that “p” is pointer variable and not a normal variable.
Key points to remember about pointers in C:
  • Normal variable stores the value whereas pointer variable stores the address of the variable.
  • The content of the C pointer always be a whole number i.e. address.
  • Always C pointer is initialized to null, i.e. int *p = null.
  • The value of null pointer is 0.
  • & symbol is used to get the address of the variable.
  • * symbol is used to get the value of the variable that a pointer is pointing to.
  • If pointer is assigned to NULL, it means it is pointing to nothing.
  • Two pointers can be subtracted to know how many elements are available between these two pointers.
  • But, Pointer addition, multiplication, division are not allowed.
  • The size of any pointer is 2 byte (for 16 bit compiler).
Example program for pointer in C:

#include <stdio.h>
#include<conio.h> 
void main()
{
   int *ptr, q;
    q = 50;  
    /* address of q is assigned to ptr  */
    ptr = &q;    
    /* display q's value using ptr variable */      
    printf("%d", *ptr);
    getch();
}
Output:
50
A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure, etc.

Defining a Function:

The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
   body of the function
}
A function definition in C programming language consists of a function header and a function body. Here are all the parts of a function:
  • Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.
  • Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature.
  • Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
  • Function Body: The function body contains a collection of statements that define what the function does.

Example:

Following is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum between the two:
/* function returning the max between two numbers */
int max(int num1, int num2) 
{
   /* local variable declaration */
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result; 
}

Function Declarations:

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For the above defined function max(), following is the function declaration:
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so following is also valid declaration:
int max(int, int);
Function declaration is required when you define a function in one source file and you call that function in another file. In such case you should declare the function at the top of the file calling the function.

Calling a Function:

While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value. For example:
#include <stdio.h>
#include<conio.h> 
/* function declaration */
int max(int num1, int num2);
void main ()
{
 /* local variable definition */
   int a = 100;
   int b = 200;
   int ret;
 /* calling a function to get max value */
   ret = max(a, b);
   printf( "Max value is : %d\n", ret );
   getch();
}
 
/* function returning the max between two numbers */
int max(int num1, int num2) 
{
   /* local variable declaration */
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result; 
}
I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result:
Max value is : 200

Function Arguments:

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call TypeDescription
Call by valueThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Call by referenceThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
By default, C uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.
Pointer
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C language is rich in built-in operators and provides the following types of operators:
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators
This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

Arithmetic Operators

Following table shows all the arithmetic operators supported by C language. Assume variable A holds 10 and variable B holds 20 then:
OperatorDescriptionExample
+Adds two operandsA + B will give 30
-Subtracts second operand from the firstA - B will give -10
*Multiplies both operandsA * B will give 200
/Divides numerator by de-numeratorB / A will give 2
%Modulus Operator and remainder of after an integer divisionB % A will give 0
++Increments operator increases integer value by oneA++ will give 11
--Decrements operator decreases integer value by oneA-- will give 9

Relational Operators

Following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20, then:
OperatorDescriptionExample
==Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.(A < B) is true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

Logical Operators

Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then:
OperatorDescriptionExample
&&Called Logical AND operator. If both the operands are non-zero, then condition becomes true.(A && B) is false.
||Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.(A || B) is true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A && B) is true.

Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as follows:
pqp & qp | qp ^ q
00000
01011
11110
10011
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A  = 1100 0011
The Bitwise operators supported by C language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then:
OperatorDescriptionExample
&Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12, which is 0000 1100
|Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61, which is 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49, which is 0011 0001
~Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.(~A ) will give -61, which is 1100 0011 in 2's complement form.
<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 0000 1111

Assignment Operators

There are following assignment operators supported by C language:
OperatorDescriptionExample
=Simple assignment operator, Assigns values from right side operands to left side operandC = A + B will assign value of A + B into C
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operandC += A is equivalent to C = C + A
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operandC -= A is equivalent to C = C - A
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operandC *= A is equivalent to C = C * A
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operandC /= A is equivalent to C = C / A
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operandC %= A is equivalent to C = C % A
<<=Left shift AND assignment operatorC <<= 2 is same as C = C << 2
>>=Right shift AND assignment operatorC >>= 2 is same as C = C >> 2
&=Bitwise AND assignment operatorC &= 2 is same as C = C & 2
^=bitwise exclusive OR and assignment operatorC ^= 2 is same as C = C ^ 2
|=bitwise inclusive OR and assignment operatorC |= 2 is same as C = C | 2

Misc Operators ↦ sizeof & ternary

There are few other important operators including sizeof and ? : supported by C Language.
OperatorDescriptionExample
sizeof()Returns the size of an variable.sizeof(a), where a is integer, will return 4.
&Returns the address of an variable.&a; will give actual address of the variable.
*Pointer to a variable.*a; will pointer to a variable.
? :Conditional ExpressionIf Condition is true ? Then value X : Otherwise value Y

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity 
Postfix () [] -> . ++ - -  Left to right 
Unary + - ! ~ ++ - - (type)* & sizeof Right to left 
Multiplicative  * / % Left to right 
Additive  + - Left to right 
Shift  << >> Left to right 
Relational  < <= > >= Left to right 
Equality  == != Left to right 
Bitwise AND Left to right 
Bitwise XOR Left to right 
Bitwise OR Left to right 
Logical AND && Left to right 
Logical OR || Left to right 
Conditional ?: Right to left 
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left 
Comma Left to right
Copyright @ CrackMNC 2014-2024
Divas Nikhra Theme by Crack MNC