C program without main

C program without main function :

usually it is not possible and not even make sense to write a code without main function because program start executing from main. but for the sake of argument this can be done through MACROS. 
i have not experienced it personally but people say that it is very much asked in Interviews.

In following program printf statement is also working without semicolons ' ; '

#include<stdio.h>
#define any main

void any()
{
   if(! printf("this program is without main function\n") )
   {

   }
}

C Program for this Pattern

54321
4321 
321  
21   

1    
CODE :

#include <stdio.h>

int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=i;j>=1;j--)
        {
            printf("%d",j);
        }
        printf("\n");
    }

    return 0;
}

C Program for this Pattern

12345
2345 
345  
45   

5    
CODE

#include <stdio.h>

int main()
{
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=i;j<=5;j++)
        {
            printf("%d",j);
        }
        printf("\n");
    }

    return 0;
}

C Program for this Patters

12345
1234 
123  
12   
1    
CODE :

#include <stdio.h>

int main()
{
    int i, j;
    for(i=5;i>=1;i--)
    {
        for(j=1;j<=i;j++)
        {
            printf("%d",j);
        }
        printf("\n");
    }

    return 0;
}

C Program for this Number Pattern

    5
   54
  543
 5432
54321

CODE:

int main()
{
  int i,j;
  for(i=5;i>=1;i--)
  {
    for(j=1;j<i;j++)
      printf(" ");
    for(j=5;j>=i;j--)
      printf("%d",j);
    printf("\n");
  }
  return 0;
}

strcpy - String Copy


Code :

#include <stdio.h>
#include <stdlib.h>
void xstrcpy(char str[100],char str1[100]);
void main()
{
    char arr[100],arr1[100];
    printf("Enter string ");
    gets(arr);
    xstrcpy(arr,arr1);
}
void xstrcpy(char str[100],char str1[100])
{
    int i;
    for(i=0;arr[i]!='\0';i++)
    {
     str1[i]=str[i];
    }
    printf("copied string is: ");
    puts(str1);
}

String to Lower Case

CODE :


#include<stdio.h>

void main()
{
    int i=0,j=0, length;
    char str[100];

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

    for(i=0; str[i]!='\0';i++)
    {}
    length = i ;

    for(j=0; j<length; j++)
    {
        if(str[j]==32)//ascii of space
        {
            continue;//skip iteration to skip space character
        }
        else if(str[j]>=65 || str[j]<=90 )
        {
            str[j]=str[j]+32;
        }
    }
    printf("String in lower case is : ");
    puts(str);

}

String to Upper Case Letters

code:

#include<stdio.h>

void main()
{
    int i=0,j=0, length;
    char str[100];

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

    for(i=0; str[i]!='\0';i++)
    {}
    length = i ;

    for(j=0; j<length; j++)
    {
        if(str[j]==32)//ascii of space
        {
            continue;//skip iteration to skip space character
        }
        else if(str[j]>=97 || str[j]<=122 )
        {
            str[j]=str[j]-32;
        }
    }
    printf("String in upper case is : ");
    puts(str);

}

Strcmp - String Compare

Program to compare two strings are equal or not.

Code :

#include <stdio.h>
#include <stdlib.h>
void stringcompare(char arr[100], char arr2[100]);

int main()
{
    char arr[100], arr2[100];
    stringcompare(arr,arr2);
}

void stringcompare(char arr[100], char arr2[100])
{
    int ans,length,result;
    printf("\nEnter string : ");
    gets(arr);
    printf("\nEnter 2nd String: ");
    gets(arr2);
    int i,counter=0,j,lenght,lenght2;
    for(i=0;arr[i]!='\0';i++)
    {
    }
    lenght=i;
    for(j=0;arr[j]!='\0';j++)
    {
        if(arr[j]==arr2[j])
        {
            counter++;
        }
    }
    if(counter==lenght)
    {
        printf("\n\tEqual");
    }
    else{
        printf("\n\tNot Equal\n");
    }
}

strchr - Character Occurrence

Code :

#include <stdio.h>
#include <stdlib.h>
char xstrchr(char arr[100]);
int main()
{
    char arr[100];
    xstrchr(arr);
}
char xstrchr(char arr[100])
{
    char search_key;
    printf("Enter string: ");
    gets(arr);
    int i;
    printf("Enter word u want to search: ");
    scanf("%c",&search_key);
    for(i=0;arr[i]!='\0';i++)
    {
        if(arr[i]==search_key)
        {
            printf("\ncharacter is found in %d index",i+1);
            //break ;  // remove this comment if you want to search character only once
        }
    }
}

string concatenation

#include <stdio.h>
#include <stdlib.h>
char stringcat(char arr[100],char arr2[100]);
int main()
{
    char arr[100],arr2[100];
    stringcat(arr,arr2);
}
char stringcat(char arr[100],char arr2[100])
{
    int i,ans,ans2,result,counter=0;
    printf("Enter arr\n");
    gets(arr);
    for(i=0;arr[i]!='\0';i++)
    {
    }
    ans=i;
    printf("The length of arr 1 is=%d\n",ans);
    printf("Enter 2nd arr\n");
    gets(arr2);
        for(i=0;arr2[i]!='\0';i++)
    {
    }
    ans2=i;
    printf("The length of arr 2 is=%d\n",ans2);
    result=ans+ans2;
    char arr3[result];
    arr3[result];
    for(i=0;i<=result;i++)
    {
        arr3[i]=arr[i];

        if(i==ans||i>ans)
        {
            arr3[i]=arr2[counter];
            counter++;
        }
    }
    puts(arr3);

}

Strings Programs

In this page you will find programs of <string.h> library but without using built in functions.

Guessing game

The below code will generate a guessing game.

Logic 

Store a number in an variable.This will be the hidden number.If the user enters number which is greater or smaller then the hidden number then display an appropriate message.Limit the user to fixed number of tries so that the game can end if the user is unable to guess the hidden number.


Code : 

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

void main()

{
    int x,i,j,num,count;
    printf("Welcome...\nMax number of tries is 4");
    count=0;
    x=37;    //this is the value which is to be guessed

    for(i=1;i!=x;i)

    {
        printf("\nEnter number:");
        scanf("%d",&i);
        if(i>x)
            printf("Too Large");
        if(i<x)
            printf("To Small");
        count++;
        if(count==4)
            break;
    }

    if(count==4)

        printf("\n\nYou lose\nnumber of tries:%d",count);
    else
        printf("\n\nYou win\nnumber of tries:%d",count);

    getch();

}

Teaase your Friends with this code

The following program will keep on printing the statement which is written in printf if the user is pressign any key you can send the .exe file of this code to your friends to fool them .

#include<stdio.h>
#include<conio.h>
void main()
{
char ch[]="I AM AN IDIOT.";
char c='A';
int i=0;

  while(c)
   {
     c=getch();
     printf("%c\a",ch[i]);
     i++;
    if(i==14)//if you change the printf statement then replace this 14 with the size of you string.
        {
            printf(" ");
            i=0;
        }
  }
}

Enjoy.

Write a C Program to print Hello world without using Semicolon

Semicolon is the statement terminator in compiler of C language. Our task is to write a piece of code to print Hello World! or any other line without using semicolons.
this can be done in the part of syntax which is free from bound of semicolons and these are IF-ELSE statements and LOOPS. It means that you can write your printf statement in these parts.

EXAMPLE:

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

void main()
 {
     if(!printf("Without Semicolons ? Piece of Cake %c\n",2))

 getch();
 }


Same thing can be done with WHILE LOOP

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

void main()
 {
     while(!printf("Without Semicolons ? Piece of Cake %c\n",2))

 getch();
 }


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

Newer Posts Older Posts
© Copyright Encyclopedia of C | Designed By Code Nirvana
Back To Top