C Program for Linear Search

The below code will perform linear search on an array.Linear search has a time complexity of O(n).

Logic: In linear search each element of the array is checked for target element one by one.

Code:

#include <stdio.h> 
#include <conio.h>

void main()
{
     int i,j,size,target,found;
     size=10;    //size of the array
     int array[size];
     
 //take input from user to fill the array

    printf("Welcome\nEnter ten numbers:\n);

     for(i=0;i<size;i++)
        { 
             scanf("%d,"&array[i]);
         }

 //get the target element from user

 printf("Enter number to search");
 scanf("%d",&target);

//start searching

for(i=0;i<size;i++)   //go through each element of the array
  {
      if(array[i]==target)   //check whether the element at index i matches the target element
        {
           found=1;              //if so then put found to 1 and stop the iteration process
            break;
         }
  }

//if found is equal to one the print number found else not found
 
if(found==1)
   printf("\nNumber found");
else
   printf("\nNumber not found");

printf("\npress any key to continue");
getch();

 

C Program for Second Maximum and Second Minimun in an One-Dimensional Array

There are two approaches to calculate maximum,minimum,second-maximum and second-minimum.
The first one is through sorting.You can sort the array in ascending or descending order and can get the required degree of number i.e max,min,etc.
The second approach is without sorting.
The below code will generate 2nd max and 2nd min from a list of numbers in an array without sorting.

Logic: Find the required number using linear search

Code:

#include <stdio.h>
#include <conio.h>

void main()
{
  int i,size,min,max,second_max,second_min;
  
  //get size of the array

 printf("Enter total number of elements:");
 scanf("%d",&size);

//declare an array

int numbers[size];
 
//fill the array 

 printf("Enter numbers:\n");
 for(i=0;i<size;i++)
 {
       scanf("%d",&numbers[i]);
 }

 //initialize max,min,second_max,second_min with first element of the array

 max=min=second_min=second_max=numbers[0];

 /*find the max and min numbers from the array.
    start searching from index 1 because max,min already contain the numbers at
    index 0 
  */
 


 for(i=1;i<size;i++)
 {
     /*if the number at index i is greater then the number in max 
        then put the number at i in max
     */
     
      if(max<numbers[i])
             max=numbers[i];
   
     /*if the number at index i is less then the number in min 
        then put the number at i in min
     */
 
     if(min>numbers[i])
            min=numbers[i];
 }  

 /*find the second max and second min numbers from the array
    go through the array,if the number at index i is equal to the number in max
    or min,then skip the checking process and proceed to the next number in the
    array
  */

 for(i=1;i<size;i++)
 {
     if(numbers[i]==max || numbers[i]==min)
          continue;
     
    if(second_max<numbers[i])
         second_max=numbers[i];

    if(second_min>numbers[i])
         second_min=numbers[i];
}

 //print the second max and second min numbers

 printf("\nThe second maximum number is %d\nThe second minimum number is  %d",second_max,second_min);

  printf("\npress any key to continue");
  getch();

}    

C Program for Maximum and Minimun number in an One-Dimensional Array

The below code will find the maximum and minimum numbers in an array.

Logic: Use linear search to search for the max and min numbers.

Code:

#include <stdio.h>
#include <conio.h>  

void main()
{
   int i,size,max,min;

  //get the size of the array  

   printf("Welcome\nEnter the total number of elements(numbers):");
   scanf("%d",&size);
   
  //declare an array

  int numbers[size];
  
  //take input , to fill the array.
  
  printf("Enter numbers");
  for(i=0;i<size;i++)
  {
     scanf("%d",&numbers[i];
   }

 /*to calculate maximum and minimum,these variables need to be initialized with some data,therefore we initialize it with the first elements of the array*/

  max=numbers[0];
  min=numbers[0];

 //use linear search to find the max and min number of the array

//star from index 1 as min and max are already initialized with the element at index o
 for(i=1;i<size;i++) 
 {
    //if the number at index i is greater then the number in max then put the number at i in max
 
    if(max<numbers[i])
           max=numbers[i];
    
    //if the number at index i is less then the number in min then put the number at i in min
    if(min>numbers[i])
           min=numbers[i];
 }

 //print the max and min numbers

 printf("\nMax is %d\nMin is %d",max,min);

 printf("\npress any key to continue");
 getch();

 
 

C Program for Sum of Numbers in an One-Dimensional Array

The below code will generate the sum of all the numbers stored in an 1D-Array.

Logic: Add all the numbers from index zero to the last index

Code:

#include <stdio.h>
#include <conio.h>

void main()
{
   int i,sum;
   sum =0;
   int numbers[]={1,5,2,3,4,7};

  for(i=0;i<6;i++)
  {
     sum=sum+numbers[i];
  }
   
  printf("Sum is %d",sum);

 printf("\npress any key to continue");
 getch();
}

C program for swapping of two Variables without using temporary variable

Logic:
         To swap two variable we will add the both variables and store in first variable, then we will subtract second from first and store in second so we will get value of first variable in Second Variable. Then from value of first variable which is still the sum of 2 value we will subtract the value of second variable. so we will get the value of second variable in first variable.

Code:

#include <stdio.h>

int 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);
   return 0;
}

C Program to tokenize a string using Strtok

Strtok is the built-in function of <String.h> header file.

Code:

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main ()
{
char input[100], *tokenptr;
int lenth,i=0,j,temp,count=0;
printf("Enter string to Tokenize : ");
gets(input);

lenth=strlen(input);                      //calculating length of string by built in function
tokenptr=strtok(input, " ");           // tokenizing string on bases of space
while(tokenptr!=NULL)               // while loop until null character is found
{
printf("%s \n",tokenptr);    //printing token
tokenptr=strtok(NULL, " "); //passing NULL as the first parameter to tell function to resume from the last spot left in the string.

   }

C Program to tokenize a string Without using Strtok

Logic :
         To tokenize a string without using strtok we will simply use assignment operator '='. The logic is that where the character is found (on basis of which you want to tokenize) place there a '\n' this will print that string in tokens.

Code :

#include<stdio.h>
#include<stdlib.h>
void main()
{
    char arr[100];
    char reverse[100][100];
    int i=0,len=0,j=0;

    printf("Enter string: ");
    gets(arr);

     len = strlen(arr);


     for(i=0; i<len; i++)
        {
            if(arr[i]==' ')  // here in ' ' is the character upon basis of which you want to tokenize in this code there is space
            {
               arr[i]='\n' ;
            }
        }
     puts(arr);
}

C program for swapping of two Variables

Logic:
           we have two variables of type int say a and b. we want to shift the value of a into b and vice versa.
For this purpose we need another temporary variable say temp. we will shift value of a into temp. Then value of b into a and at last value of temp into b.

Code:

#include<stdio.h>
#include<conio.h>

void main()
{
   int a=20, b=30, temp;
 
  printf("value of a is %d and b is %d\n",a,b);

  printf("After Swapping \n");

  temp=a;   //swapping
  a=b;        //swapping
  b=temp;  //swapping

  printf("value of a is %d and b is %d\n",a,b);

getch(); //halts screen

}

C program to Print Triangle

The below code prints a triangle of height 'h' taken from the user.

   *
   * *
   * * *
   * * * *
   * * * * *

Code:
#include <stdio.h>
#include <conio.h>

void main()
{
    int i,j,k,x;
    printf("Enter height of triangle:");
    scanf("%d",&x);

    for(i=x;i>=1;i--)
    {
        for(j=1;j<i;j++)
        {
            printf(" ");
        }

        for(k=x;k>=i;k--)
        {
            printf(" *");
        }
        printf("\n");
    }
    printf("\npress any key to continue...");
    getch();
}
 

Right Angle Triangle Checker C program

The below code checks whether a triangle is right angled or not by taking input the lengths of all three sides.

Logic: By Pythagoras theorem, 
(hypotenuse)^2 = (base)^2+(perpendicular)^2
If the input data satisfies the above equation then the triangle will be a right angle triangle.

Code: 
#include <stdio.h>
#include <conio.h>

void main()
{
    char x,check;

    float first,second,third;

    printf("This program checks wheater the trianle is a right angle triangle or not\n\nEnter the lenght of first side:");
    scanf("%f",&first);
    printf("Enter the length of second side:");
    scanf("%f",&second);
    printf("Enter the length of third side:");
    scanf("%f",&third);

    if(first==0&&second==0&&third==0)
        printf("invalid input");
    else
        {
      if((first*first)==(second*second)+(third*third))
        printf("The triangle is an right angle triangle");
      else if((second*second)==(first*first)+(third*third))
        printf("The triangle is an right angle triangle");
      else if((third*third)==(second*second)+(first*first))
        printf("The triangle is an right angle triangle");
      else
        printf("The triangle is not an right angle triangle");
        }
     printf("\n\n(*_*) Would you like to run again...(Y/N)");
     scanf(" %c", &check);
     if(check=='Y'||check=='y')
            {
                system("cls");
                main();
            }
      printf("\npress any key to continue");
      getch();

}
 

Even-Odd Checker C program

The below code checks whether a number is even or odd using switch structure.

Logic: 
If a number is divided by 2 and the remainder is zero then that number is an even number.

Code:
#include <stdio.h>
#include <conio.h>

void main()
{
    int x;
    char ch;

        printf("Even-Odd checker\nEnter a number:");
        scanf("%d",&x);

        switch(x%2)
        {
        case 0:
            printf("The number is even");
            break;
        case 1:
            printf("The number is odd");

        }
        printf("\n\n(*_*) Would you like to run again...(Y/N)");
        scanf(" %c",&ch);
        if(ch=='Y'||ch=='y')
            {
                system("cls");
                main();
            }
        printf("\npress any key to continue");
        getch();

C program for Simple Calculator using Switch Case Statement

The below code will create a simple calculator with the Switch structure;

Logic: 
Each case is designed to work with a specific switch, in this case  switches are the   mathematical operators i.e " +, - , * , / , % (for remainder-modulus) ". 

Code: 
#include <stdio.h>
#include <stdlib.h>

void main()
{
    int a,b,mod;
    float sum,sub,mul,div,x,y;
    char ch,op;

        printf("This is a calculator...\nThe following operations can be performed\n\naddition +\nsubtration -\nmultiplication *\ndivision /\nremainder %%\n\nEnter you equation e.g \"3+5\" :");
        scanf("%f %c %f",&x, &op, &y);

        switch(op)
        {
        case '+':
            sum=x+y;
            printf("answer is %.1f",sum);
            break;
         case '-':
            sub=x-y;
            printf("answer is %.1f",sub);
            break;
         case '*':
            mul=x*y;
            printf("answer is %.1f",mul);
            break;
         case '/':
            if(x==0||y==0)
                {
                    printf("The entered value must not be zero");
                    break;
                }

            div=x/y;
            printf("answer is %.2f",div);
            break;
         case '%':
            a=x;
            b=y;
            mod=a%b;
            printf("answer is %d",mod);
            break;
         default:
            printf("incorrect input");

        }
        printf("\n\n(*_*) Would you like to run again...(Y/N)");
        scanf(" %c", &ch);
        if(ch=='Y'||ch=='y')
            {
                system("cls");
                main();
            }
        printf("\npress any key to continue:");
        getch();
    }
 

C program for Sum of digits of a Number

The below code will calculate the sum of digits of an integer number.

Logic: An integer number like 54321 can be separated into digits by dividing it by 10.If 54321 is divided by 10 then we get remainder 1,and number becomes 5432,if we repeat this process we will get the digits 1 2 3 4 5.

Code:

#include <stdio.h>

#include <conio.h>

void main()

{
    int x,sum;
    sum=0;

    printf("Welcome\nEnter a number:");

    scanf("%d",&x);  //input number

    while(x!=0)

    {
       sum=sum+(x%10);  //get the last digit and add it to sum
       x=x/10;                    //drop the last digit from the number
    }

    printf("\nThe sum is %d",sum);


    printf("\npress any key to continue");

    getch();                       //to halt the execution of the program
}

Prime Number - Checker C Program

The below code checks whether the entered number is prime or not.

Logic: Prime numbers are defined as the numbers which are only divisible by one or itself.
This can be checked by dividing the number from 2 to that number.If the number is divisible on any other number other then itself then that number will not be a primer number.Also as 1 is not a prime number,if the user enters 1 print not prime.

Code
#include <stdio.h>
#include <conio.h>

void main()
{
    int x,y,count=0;
    printf("Enter a number:");
    scanf("%d",&x);
    y=2;
    if(x==1)
        printf("The number %d is not prime",x);
    while(y<=x)
    {
        if(x%y==0)
          count++;
        y++;
    }
    if(count==1)
      printf("The number %d is prime",x);
    else
        printf("The number %d is not prime",x);

    getch();
}

C program for simple Calculator

The below code will create a simple calculator with the use of if-else-if control structure. 

Code:
#include<stdio.h>
#include<conio.h>

void main()
{
    int a,b,mod;
    float x,y,sum,sub,mul,div;
    char ch,op;

        printf("This is a calculator\nThe following operations can be perfoemed by it\n\naddition +\nsubtraction -\nmultiplication *\ndivision /\nremainder %%\n\nEnter your equation e.g \"3+4\" :");
        scanf("%f %c %f",&x, &op,&y);
        if(op=='+')
        {
            sum=x+y;
            printf("anwser is %.2f",sum);
        }
        else if(op=='-')
        {
            sub=x-y;
            printf("answer is %.2f",sub);
        }
        else if(op=='*')
        {
            mul=x*y;
            printf("answer is %.2f",mul);
        }
        else if(op=='/')
        {
            if(x==0||y==0)
            {
                printf("The entered number should not be zero");
            }
            else
            {
                div=x/y;
                printf("answer is %.2f",div);
            }
        }
        else if(op=='%')
        {
            a=x;
            b=y;
            mod=a%b;
            printf("mod is %d",mod);
        }
        else
            printf("invalid input");
        printf("\n\n\n(*_*) Would you like to run again...(Y/N)");
        scanf(" %c",&ch);
        if(ch=='Y'||ch=='y')
            {
                system("cls");
                main();
            }
        printf("\npress any key to continue");
        getch();


}

C program to Print Right Angle Triangle

The below code prints a right angle triangle of height h taken from the user,


        *
       **
       *** 
     ****
    *****

Logic: The outer loop controls the number of rows whereas the inner loops control the number of columns.The first inner loop is used to print spaces in  columns and the second one is used to print stars in columns. 

Code:
#include <stdio.h>
#include <conio.h>

void main()
{
    int i,j,k,x;
    printf("Enter height:");
    scanf("%d",&x);

    for(i=x;i>=1;i--)
    {
        for(j=1;j<i;j++)
        {
            printf(" ");
        }
        for(k=x;k>=i;k--)
        {
            printf("*");
        }
        printf("\n");
    }
    getch();
}

TEST

this is our test post.....huge load of source codes is on the way :)
Newer Posts
© Copyright Encyclopedia of C | Designed By Code Nirvana
Back To Top