C PROGRAMMING

FIRST PROGRAM IN C

Let us start with a simple program

Program:

#include<stdio.h>
int main()
{
printf("Hello World");
return 0;
}

Output:

This image has an empty alt attribute; its file name is output.png

Explanation

In the first line we have used ‘#include<stdio.h>‘ which means that we are instructing compiler to include ‘stdio.h‘ file which is a header file. ‘std‘ means  standard, ‘i‘ stands for input and ‘o‘ stands for  output, ‘.h‘ is extension for header files.

In the next line we wrote “int main()”. “int” is the returning type of the function “main”. empty parenthesis indicates that function takes no arguments. This line represents the calling of main function which will return an integer.(Don’t worry if you are not able to understand this explanation , we are going to explain each and every important aspect of it in upcoming posts)

Now we have a set of { } immediately after the main function, which indicates the all the statements that are included in between these braces belongs to main function.

Inside main function we wrote “printf(“Hello World”);” which is for displaying the text “Hello World”.

The syntax of printf statement is
printf(“…….. text……… ”) ; 

A semicolon ‘;’ is compulsory at the end of each statement. If we didn’t type semi-colon at the end of statement then compiler will give an error.

After that we are returning the integer value zero. The purpose of main’s return value is to return an exit status to the operating system.Even if we don’t return anything i.e return type is void.

Basic C programmes

Program to print “Hello World!!”.

#include<stdio.h>
int main(){
printf(“Hello World!!”);
}

Program to assign values of two numbers and print their addition.

#include<stdio.h>
void main()
{
int a,b,ans;
a=10;
b=20;
ans=a+b;
printf(“Addition is : %d”,ans);
}

Program to read values of two numbers from the user and print their addition.

#include<stdio.h>
void main()
{
int a,b,ans;
printf(“Enter 1st number:”);
scanf(“%d”,&a);
printf(“Enter 2nd number:”);
scanf(“%d”,&b);
ans=a+b;
printf(“Addition is : %d”,ans);
}

Program to check whether a number is even or odd

#include<stdio.h>
void main()
{
int no;
printf("\n enter the number");
scanf("%d",&no);
if(no%2==0)
{
printf("\n the number is even");
}
else 
{
printf("\n the number is odd");
}
}

Program to check whether a number is positive or negative

#include<stdio.h>
void main()
{
int a;
printf("\n enter the number");
scanf("%d",&a);
if(a>0)
{
printf("\n the number is positive");
}
else
{
if(a==0)
{
printf("\n the number is zero");
}
else
{
printf("\n the number is negative");
}
}
}

Program to accept value of radius and print area of a circle.

#include<stdio.h>
void main()
{
float area,radius;
printf(“Enter Radius:”);
scanf(“%f”,&radius);
area=3.14*radius*radius;
printf(“Area of the given radius is : %6.2f”,area);
}

Program to accept a number from user and print it’s square & cube.

#include<stdio.h>
void main()
{
int n,square,cube;
printf(“Enter Number: “);
scanf(“%d”,&n);
square=n*n;
cube=n*n*n;
printf(“\nSquare: %d\nCube: %d”,square,cube);
}

Program to accept two values of a & b and swap their values.

#include<stdio.h>
void main()
{
int a,b,temp;
printf(“Enter 1st number: “);
scanf(“%d”,&a);
printf(“Enter 2nd number: “);
scanf(“%d”,&b);
printf(“\nBefore Swapping..\n A=%d, B=%d”,a,b);
temp=a;
a=b;
b=temp;
printf(“\nAfter Swapping..\n A=%d, B=%d”,a,b);
}

Program to accept two number and print largest among them

#include<stdio.h>
void main()
{
int a,b;
printf(“Enter 1st number: “);
scanf(“%d”,&a);
printf(“Enter 2nd number: “);
scanf(“%d”,&b);
if(a>b)
printf(“Largest value is: %d”,a);
else
printf(“Largest value is: %d”,b);
}

Program to accept three number and print smallest among them

#include<stdio.h>
void main()
{
int a,b,c;
printf("\n enter the three integers");
scanf("%d %d %d",&a,&b,&c);
if((a<b)&&(a<c))
{
printf("\n the smallest no is %d",a);
}
else if((b<a)&&(b<c))
{
printf("\n the smallest no is %d",b);
}
else
{
printf("\n the smallest no is %d",c);
}
}

Program to roots of a quadratic equation

#include<stdio.h>
#include<math.h>
void main()
{
float a,b,c,dis,x1,x2;
printf("\n input values for a,b,c");
scanf("%f %f %f",&a,&b,&c);
dis=b*b-4*a*c;
if(dis<0)
{
printf("\n roots are imaginary");
}
else
{
x1=(-b+sqrt(dis))/(2.0*a);
x2=(-b-sqrt(dis))/(2.0*a);
printf("\n the roots are %0.2f,%0.2f",x1,x2);
}
}

Program to find the area of the triangle with respect to the cases using switch case

#include<stdio.h>
#include<math.h>
void main()
{
int base,h,a,b,c,x1,y1,x2,y2,x3,y3,n;
float s,a1,a2,a3;
printf("\n enter your choice");
scanf("%d",&n);
switch(n)
{
case 1:printf("\n enter the base and height");
        scanf("%d %d",&base,&h);
        a1=(1/2.0*((float)base*h));
        printf("\n area of triangle with base %d and height %d is %0.2f",base,h,a1);
        break;
case 2:printf("\n enter the values of a,b,c");
       scanf("%d %d %d",&a,&b,&c);
       s=((float)(a+b+c)/2.0);
       a2=sqrt(s*(s-a)*(s-b)*(s-c));
       printf("\n area of triangle with sides %d,%d,%d is %0.2f",a,b,c,a2);
       break;
case 3:printf("\n enter the values for x1,y1,x2,y2,x3,y3");
       scanf("%d %d %d %d %d %d",&x1,&y1,&x2,&y2,&x3,&y3);
       a3=0.5*((float)abs(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2)));
       printf("\n area of the triangle is %0.2f",a3);
       break;
}
}     

Program to find the no of bytes used by different data types

#include<stdio.h>
void main()
{
printf("\n no of bytes occupied by different data types:\n");
printf("\n char=%ld \n",sizeof(char));
printf("\n int=%ld \n",sizeof(int));
printf("\n unsigned char=%ld \n",sizeof(unsigned char));
printf("\n short int=%ld",sizeof(short int));
printf("\n long int=%ld",sizeof(long int));
printf("\n float=%ld",sizeof(float));
printf("\n double=%ld",sizeof(double));
printf("\n long double=%ld",sizeof(long double));
}

Relational operators

#include<stdio.h>
void main()
{
int a,b,c,d,p,q,r,s;
printf("\n enter two integers");
scanf("%d %d",&a,&b);
c=a<b;
d=a<=b;
p=a>b;
q=a>=b;
r=a==b;
s=a!=b;
printf("\n less than (%d<%d)=%d \n",a,b,c);
printf("\n less than or equal to (%d<=%d)=%d \n",a,b,d);
printf("\n greater than (%d>%d)=%d \n",a,b,p);
printf("\n greater than or equal to (%d>=%d)=%d \n",a,b,q);
printf("\n equal to (%d==%d)=%d \n",a,b,r);
printf("\n not equal to (%d!=%d)=%d \n",a,b,s);
}

Program to print numbers from 1 to n using while loop.

#include<stdio.h>
void main()
{
int i=1, n;
printf(“Enter n : “);
scanf(“%d”, &n);
while(i<=n)
{
printf(“%d\t”,i);
i++;
}
}

Program to print numbers from n to 1 using Do While loop.

#include<stdio.h>
void main()
{
int i=1, n;
printf(“Enter n : “);
scanf(“%d”, &n);
i=n;
do
{
printf(“%d\t”,i);
i–;
}while(i>=1);
}

Program to add first n numbers

#include<stdio.h>
void main()
{
int n,i,sum=0;
printf("\n enter the value of n");
scanf("%d",&n);
for(i=1;i<=n;i++)
         {
           sum=sum+i;
         }
    printf("\n sum of natural nos till %d is %d",n,sum);
}

Program to add even and odd numbers

#include<stdio.h>
void main()
{
int i,n,sum1=0,sum2=0;
printf("\n enter the value of n");
scanf("%d",&n);
for(i=1;i<=n;i++)
      {
        if(i%2==0)
              {
                sum1=sum1+i;
               }        
         else
              {
                sum2=sum2+i;
              }
      }
printf("\n sum of even nos is %d",sum1);
printf("\n sum of odd nos is %d",sum2);
}  

Program to find armstrong numbers in the range

#include<stdio.h>
void main()
{
int m,n,i,t,r,v,sum=0;
printf("\n enter the value of m and n");
scanf("%d%d",&m,&n);
for(i=m;i<=n;i++)
{
 v=i;
 sum=0;
 t=i;	
         while(t!=0)
       {
         r=t%10;
         sum=sum+(r*r*r);
         t=t/10;
       }
	 if(sum==v)
	{
		printf("\n %d is an armstrong no",v);
	}  
}
}
       

Program to check whether a number is prime or not

#include<stdio.h>
void main()
{
      int i=1,p,count=0;
      printf("\n enter the value of p");
      scanf("%d",&p);   
      for(i=1;i<p/2;i++)
             {
                 if(p%i==0)
                           {
                            count=count+1;
                           }
             }
      if(count==1)
             {
                printf("\n %d is a prime no",p);
             }
      else
             {
                printf("\n entered no is not prime");
             }
}

Program to find the prime numbers in a range of numbers

#include<stdio.h>
void main()
{
 int i,m,n,t,count=0;
 printf("\n enter the values of m and n");
 scanf("%d%d",&m,&n);
 for(i=m;i<=n;i++)
      {
        t=i;         
        count=0;
        if(t%i==0)
               {
                 count=count+1;
               }
      } 
  if(count==1)
     {
          printf("\n %d is a prime no",t);
     }
}


Program to take number from user and print table of that number.

#include<stdio.h>
void main()
{
int i, n;
printf(“Enter number : “);
scanf(“%d”, &n);
for(i=1; i<=10; i++)
printf(“%d × %d = %d\n”, n, i, n*i);
}

Program to print the pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

#include<stdio.h>
void main()
{
int n, i, j;
printf(“Enter number : “);
scanf(“%d”, &n);
for (i = 1; i <= n; i++)
{
for (j = 1; j <= i; j++)
{
printf(“%d “, j);
}
printf(“\n”);
}
}

Program to print Pascal triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

#include<stdio.h>
long fact(int);

void main()
{
int line, i, j;
printf(“Enter the number : “);
scanf(“%d”, &line);

for (i = 0; i < line; i++)
{
for (j = 0; j < line – i – 1; j++)
{
printf(” “);
}

for (j = 0; j <= i; j++)
{
printf(“%ld “, fact(i) / (fact(j) * fact(i – j)));
}

printf(“\n”);
}
}

long fact(int num)
{
long f = 1;
int i = 1;
while (i <= num)
{
f = f * i;
i++;
}
return f;
}

Program to accept a number and print Fibonacci sequence.

#include<stdio.h>
void main()
{
int pre=1, cur=1, temp, i, n;
printf(“Enter number : “);
scanf(“%d”, &n);
printf(“%d\t%d”, pre, cur);
for(i=3; i<=n; i++)
{
temp = cur;
cur = pre + cur;
pre = temp;
printf(“\t%d”, cur);
}
}

Add ‘n’ numbers using array.

#include<stdio.h>
void main()
{
int n, sum = 0, i, array[100];
printf(“Enter total numbers “);
scanf(“%d”, &n);
for (i = 1; i <= n; i++)
{
printf(“Enter number %d : “, i);
scanf(“%d”, &array[i]);
sum = sum + array[i];
}
printf(“Sum : %d\n”, sum);
}

Program to accept a number and display the sum of digits

#include<stdio.h>
void main()
{
int n, sum = 0, remainder;
printf(“Enter the number : “);
scanf(“%d”, &n);

while (n != 0)
{
remainder = n % 10;
sum = sum + remainder;
n = n / 10;
printf(“Sum of digits of entered number : %d”, sum);
}

Average of numbers.

#include<stdio.h>
void main()
{
int n, i;
float sum=0, x, avg;
printf(“Enter total Numbers : “);
scanf(“%d”, &n);
for (i = 1; i <= n; i++)
{
printf(“\nNumber %d : “, i );
scanf(“%f”, &x);
sum += x;
}
avg = sum / n;
printf(“\nThe Average is : %0.2f”, avg);
}

Program to take an alphabet from user and check whether it is a vowel or not.

#include<stdio.h>
void main()
{
char ch;
printf(“Enter an alphabet : “);
scanf(“%c”, &ch);

if (ch==’a’ || ch==’A’ || ch==’e’ || ch==’E’ || ch==’i’ || ch==’I’ || ch==’o’ || ch==’O’ || ch==’u’ || ch==’U’)
printf(“%c is a vowel.”, ch);
else
printf(“%c is not a vowel.”, ch);
}

Program to find the factorial of a number

#include<stdio.h>
int recursivefactorial(int);
void main()
{
int n,factorialresult;
printf("\n enter no:\t");
scanf("%d",&n);
factorialresult=recursivefactorial(n);
printf("\n the factorial is %d",factorialresult);
}
int recursivefactorial(int num)
{
if(num<0)
      {
            printf("\n input error:negative values not allowed");
            exit(0);
      }
else if(num==0)
      {
            return 1;
       }
else
      {
            return num*recursivefactorial(num-1);
       }
}              

Program to find the GCD of two numbers

#include<stdio.h>
void main()
{
int a,b,result,factor,min;
printf("\n enter two integers :\t");
scanf("%d %d",&a,&b);
result=gcd(a,b);
printf("\n GCD is %d",result);
}
int gcd(int a,int b)
{
if(a==0)
      {
       return b;
       }
else if(b==0)
      {
       return a;
       }
else
      {
       if(a>b)
            return gcd(b,a%b);
        else
            return gcd(a,b%a);
       }
}

Program to check whether the number is palindrome or not.

#include<stdio.h>
void main()
{
int n, rev = 0, temp;
printf(“Enter a number : “);
scanf(“%d”, &n);

temp = n;
while (temp != 0)
{
rev = rev * 10;
rev = rev + temp % 10;
temp = temp / 10;
}

if (n == rev)
printf(“\n%d is palindrome number.”, n);
else
printf(“\n%d is not palindrome number.”, n);
}

Program to implement 2D array

#include<stdio.h>
void main()
{
int a[10][10],i,j,row,col;
printf("\n enter the no of rows:\t");
scanf("%d",&row);
printf("\n enter the no of columns:\t");
scanf("%d",&col);
for(i=0;i<row;i++)
      {
       for(j=0;j<col;j++)
           {
            scanf("%d",&a[i][j]);
           }
      }
for(i=0;i<row;i++)
      {
       for(j=0;j<col;j++)
       	printf("%d\t",a[i][j]);
       printf("\n");
      }
}

Program to sort an array of numbers(Bubble Sort)

#include<stdio.h>
void main()
{
int a[20],n,i,j,temp;
printf("\n enter the value of usersize");
scanf("%d",&n);
for(i=0;i<n;i++)
      {
       printf("\nEnter the value of a[%d]:\t",i);
       scanf("%d",&a[i]);
      }
printf("\nBefore sorting: The array elements are:\n");
for(i=0;i<n;i++)
      {
       printf("a[%d]=%d",i,a[i]);
      }
for(i=0;i<n;i++)
      {
       for(j=i+1;j<n;j++)
          { 
            printf("\nComparing a[%d]=%d with a[%d]=%d",i,a[i],j,a[j]);
            if(a[i]>a[j])
              {
		printf("\n\tswapping a[%d]=%d with a[%d]=%d",i,a[i],j,a[j]);
               temp=a[i];
               a[i]=a[j];
               a[j]=temp;
               printf("\n a[%d]=%d a[%d]=%d",i,a[i],j,a[j]);
              }
           }
      }
printf("\nAfter sorting: The array elements are:\n");
for(i=0;i<n;i++)
      {
       printf("a[%d]=%d",i,a[i]);
      }
} 

Program to convert binary to decimal

#include<stdio.h>
#include<math.h>
void main()
{
long int bin;
int i=0,bit;
int dec=0;
printf("\n enter the binary value");
scanf("%ld",&bin);
while(bin!=0)
{
bit=bin%10;
dec=dec+bit*pow(2,i);
bin=bin/10;
i++;
}
printf("\n binary is %ld",bin);
printf("\n decimal equivalent is %d",dec);
}

Program to convert Decimal numbers to Binary.

#include<stdio.h>
void main()
{
int n, c, k;
printf(“Enter a decimal number : “);
scanf(“%d”, &n);

printf(“\n%d in binary number system is : “, n);

for (c = 31; c >= 0; c–)
{
k = n >> c;
if (k & 1)
{
printf(“1”);
}
else
{
printf(“0”);
}
}
printf(“\n”);
}

Program to add two strings without using concat() function.

#include<stdio.h>
void concat(char[], char[]);

void main()
{
char s1[50], s2[30];
clrscr();
printf(“\nEnter String 1 : “);
gets(s1);
printf(“\nEnter String 2 : “);
gets(s2);

concat(s1, s2);

printf(“\nConcatenated string is : %s”, s1);
}

void concat(char s1[], char s2[])
{
int i, j;

i = strlen(s1);

for (j = 0; s2[j] != ‘\0’; i++, j++)
{
s1[i] = s2[j];
}

s1[i] = ‘\0’;
}

Program to compare two strings.

#include<stdio.h>
void main()
{
char a[100], b[100];
printf(“\nEnter the first string : “);
gets(a);
printf(“\nEnter the second string : “);
gets(b);

if (strcmp(a, b) == 0)
printf(“\nEntered strings are equal.”);
else
printf(“\nEntered strings are not equal.”);
}

Program to convert upper case to lower case and lower case to upper case

#include<stdio.h>
void main()
{
char ch;
printf("\n enter the character");
scanf("%c",&ch);
if(ch>=97&&ch<=122)
{
printf("\n the entered character in lower case is %c and ASCII value is %d",ch,ch);
ch=ch-32;
printf("\n the character in upper case is %c and ASCII value is %d",ch,ch);
}
else if(ch>=65&&ch<=90)
{
printf("\n the entered character in upper case is %c and ASCII value is %d",ch,ch);
ch=ch+32;
printf("\n the character in lower case is %c and ASCII value is %d",ch,ch);
}
else
{
printf("\n invalid character");
}
} 

Program to count frequency of characters in a string.

#include<stdio.h>
#include<string.h>

void main()
{
char str[1500];
int c = 0, count[26] = {0};

printf(“Enter a string : “);
gets(str);

while (str[c] != ‘\0’)
{

if (str[c] >= ‘a’ && str[c] <= ‘z’)
count[str[c] – ‘a’]++;
c++;
}

for (c = 0; c < 26; c++)
{
if (count[c] != 0)
printf(“%c occurs %d times in the string.\n”, c + ‘a’, count[c]);
}
}

Program to calculate the length of string without using strlen() function.

#include<stdio.h>
void main()
{
char s[1000], i;

printf(“Enter a string : “);
scanf(“%s”, s);

for (i = 0; s[i] != ‘\0’; ++i);

printf(“Length of string : %d”, i);
}

Program to add two matrices.

#include<stdio.h>
void main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];

printf(“Enter the number of rows and columns of matrix :”);
scanf(“%d%d”, &m, &n);
printf(“\nEnter the elements of first matrix : \n”);

for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
scanf(“%d”, &first[c][d]);
}
}

printf(“\nEnter the elements of second matrix : \n”);

for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
scanf(“%d”, &second[c][d]);
}
}

printf(“\nSum of entered matrices : \n”);

for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
{
sum[c][d] = first[c][d] + second[c][d];
printf(“%d\t”, sum[c][d]);
}
printf(“\n”);
}
}

Program to calculate the determinant of 2×2 matrix.

#include<stdio.h>
void main()
{
int a[2][2], i, j;
long determinant;
clrscr();

printf(“Enter the 4 elements of matrix :\n”);
for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
scanf(“%d”, &a[i][j]);
}
}

printf(“\nThe matrix is : \n”);
for (i = 0; i < 2; i++)
{
printf(“\n”);
for (j = 0; j < 2; j++)
{
printf(“%d\t”, a[i][j]);
}
}

determinant = a[0][0] * a[1][1] – a[1][0] * a[0][1];

printf(“\nDeterminant of 2X2 matrix: %ld”, determinant);
}

Program to calculate the determinant of 3×3 matrix.

#include<stdio.h>
void main()
{
int a[3][3], i, j;
long determinant;

printf(“Enter the 9 elements of matrix :\n”);
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
scanf(“%d”, &a[i][j]);
}
}

printf(“\nThe matrix is :\n”);
for (i = 0; i < 3; i++)
{
printf(“\n”);
for (j = 0; j < 3; j++)
{
printf(“%d\t”, a[i][j]);
}
}

determinant = a[0][0] * ((a[1][1] * a[2][2]) – (a[2][1] * a[1][2]))
– a[0][1] * (a[1][0] * a[2][2] – a[2][0] * a[1][2])
+ a[0][2] * (a[1][0] * a[2][1] – a[2][0] * a[1][1]);

printf(“\nDeterminant of 3X3 matrix : %ld”, determinant);
}

Program to implement the concept of pointers

#include<stdio.h>
void main()
{
int a,*ap;
char ch,*chp;
float f,*fp;
a=24;
ch='a';
f=4.5;
ap=&a;
chp=&ch;
fp=&f;
printf("\n a=%d",a);
printf("\n ch=%c",ch);
printf("\n f=%f",f);
printf("\n address of a:ap=%p",ap);
printf("\n value of a:*ap=%d",*ap);
printf("\n address of ch:chp=%p",chp);
printf("\n value of ch:*chp=%c",*chp);
printf("\n address of f:fp=%p",fp);
printf("\n value of f:*fp=%f",*fp);
}

Program to implement swapping using pointers

#include<stdio.h>
void swap(int *,int *);
void main()
{
int a,b;
printf("\n enter the values for a and b");
scanf("%d %d",&a,&b);
printf("\n in main():before swap():a=%d b=%d &a=%p &b=%p",a,b,&a,&b);
swap(&a,&b); 
printf("\n in main():after swap():a=%d b=%d &a=%p &b=%p",a,b,&a,&b);
}
void swap(int *x,int *y)
{
int temp;
printf("\n in swap():before swap *x=%d *y=%d x=%p y=%p",*x,*y,x,y);
temp=*x;
*x=*y;
*y=temp;
printf("\n in swap():after swap *x=%d *y=%d x=%p y=%p",*x,*y,x,y);
}

To practice problems on C
https://www.hackerrank.com/domains/c

We recommend you to join the Telegram Channel for more updates.

Programming Monks Telegram Channel : https://t.me/Programming_Monk

Do subscribe our blog.