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

Wednesday, May 7, 2014

Palindrome number algorithm

1. Get the number from user.
2. Reverse it.
3. Compare it with the number entered by the user.
4. If both are same then print palindrome number
5. Else print not a palindrome number
.

Palindrome number program c

#include <stdio.h>
#include<conio.h> 
void main()
{
   int n, reverse = 0, temp;
   clrscr();
   printf("Enter a number to check if it is a palindrome or not\n");
   scanf("%d",&n);
   temp = n;
   while( temp != 0 )
   {
      reverse = reverse * 10;
      reverse = reverse + temp%10;
      temp = temp/10;
   }
   if ( n == reverse )
      printf("%d is a palindrome number.\n", n);
   else
      printf("%d is not a palindrome number.\n", n);
   getch();
}

Tuesday, May 6, 2014

C Program to reverse a number :- This program reverse the number entered by the user and then prints the reversed number on the screen. For example if user enter 123 as input then 321 is printed as output. In our program we use modulus(%) operator to obtain the digits of a number. To invert number look at it and write it from opposite direction or the output of code is a number obtained by writing original number from right to left. To reverse or invert large numbers use long data type or long long data type if your compiler supports it, if you still have large numbers then use strings or other data structure.


C programming code

#include <stdio.h>
#include<conio.h> 
void main()
{
   int n, reverse = 0;
   printf("Enter a number to reverse\n");
   scanf("%d",&n);
   while (n != 0)
   {
      reverse = reverse * 10;
      reverse = reverse + n%10;
      n = n/10;
   }
   printf("Reverse of entered number is = %d\n", reverse);
   getch();
}

Swapping of two numbers in c

#include <stdio.h>
#include<conio.h> 
void main()
{
   int x, y, temp;
   printf("Enter the value of x and y\n");
   scanf("%d%d", &x, &y);
   printf("Before Swapping\nx = %d\ny = %d\n",x,y);
   temp = x;
   x    = y;
   y    = temp;
   printf("After Swapping\nx = %d\ny = %d\n",x,y);
   getch();
}

Swapping of two numbers without third variable

/*You can also swap two numbers without using temp or temporary or third variable. In that case c program will be as shown :-   */

#include <stdio.h>
#include<conio.h> 
void main()
{
   int a, b;
   printf("Enter two integers to swap\n");
   scanf("%d%d", &a, &b);
   a = a + b;
   b = a - b;
   a = a - b;
   printf("a = %d\nb = %d\n",a,b);
   getch();
}
To understand above logic simply choose a as 7 and b as 9 and then do what is written in program. You can choose any other combination of numbers as well. Sometimes it's a good way to understand a program.

Swap two numbers using pointers

#include <stdio.h>
#include<conio.h> 
void main()
{
   int x, y, *a, *b, temp;
   printf("Enter the value of x and y\n");
   scanf("%d%d", &x, &y);
   printf("Before Swapping\nx = %d\ny = %d\n", x, y);
   a = &x;
   b = &y;
   temp = *b;
   *b   = *a;
   *a   = temp;
   printf("After Swapping\nx = %d\ny = %d\n", x, y);
   getch();
}

Swapping numbers using call by reference

/*In this method we will make a function to swap numbers.*/
#include <stdio.h>
#include<conio.h> 
void swap(int*, int*);
int main()
{
   int x, y;
   printf("Enter the value of x and y\n");
   scanf("%d%d",&x,&y);
   printf("Before Swapping\nx = %d\ny = %d\n", x, y);
   swap(&x, &y); 
   printf("After Swapping\nx = %d\ny = %d\n", x, y);
   getch();
}
void swap(int *a, int *b)
{
   int temp;
   temp = *b;
   *b   = *a;
   *a   = temp;   
}

C programming code to swap using bitwise XOR

#include <stdio.h>
#include<conio.h> 
void main()
{
  int x, y;
  scanf("%d%d", &x, &y);
  printf("x = %d\ny = %d\n", x, y);
  x = x ^ y;
  y = x ^ y;
  x = x ^ y;
  printf("x = %d\ny = %d\n", x, y);
  getch();
}

Swapping is used in sorting algorithms that is when we wish to arrange numbers in a particular order either in ascending order or in descending.

Monday, May 5, 2014

C programming code


#include <stdio.h>
#include<conio.h> 
void main()
{
   int n, sum = 0, c, value;
   printf("Enter the number of integers you want to add\n");
   scanf("%d", &n);
   printf("Enter %d integers\n",n);
   for (c = 1; c <= n; c++)
   {
      scanf("%d",&value);
      sum = sum + value;
   }
   printf("Sum of entered integers = %d\n",sum);
   getch();
}

Sunday, May 4, 2014

C programming code


#include <stdio.h>
#include<conio.h> 
void main()
{
   int first, second, add, subtract, multiply;
   float divide;
   printf("Enter two integers\n");
   scanf("%d%d", &first, &second);
   add = first + second;
   subtract = first - second;
   multiply = first * second;
   divide = first /second;
   printf("Sum = %d\n",add);
   printf("Difference = %d\n",subtract);
   printf("Multiplication = %d\n",multiply);
   printf("Division = %.2f\n",divide);
   getch();
}
This program concatenates strings, for example if the first string is "c " and second string is "program" then on concatenating these two strings we get the string "c program". To concatenate two strings we use strcat function of string.h, to concatenate without using library function see another code below which uses pointers.

C programming code

#include <stdio.h>
#include <string.h>
#include<conio.h> 
void  main()
{
   char a[100], b[100];
   printf("Enter the first string\n");
   gets(a);
   printf("Enter the second string\n");
   gets(b);
   strcat(a,b);
   printf("String obtained on concatenation is %s\n",a);
   getch();
}

Output of program:


String concatenation without strcat
#include <stdio.h>
#include<conio.h> 
void concatenate_string(char*, char*);
void main()
{
    char original[100], add[100];
    printf("Enter source string\n");
    gets(original);
    printf("Enter string to concatenate\n");
    gets(add);
    concatenate_string(original, add);
    printf("String after concatenation is \"%s\"\n", original);
    getch();
}
void concatenate_string(char *original, char *add)
{
   while(*original)
   original++;
   while(*add)
   {
      *original = *add;
       add++;
       original++;
   }
   *original = '\0';
}

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
Copyright @ CrackMNC 2014-2024
Divas Nikhra Theme by Crack MNC