C Programming Examples

X




Resources > C Program Examples > {{currentSubTopic}}

Program to Display "Hello, World!"


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
   // printf() displays the string inside quotation
   printf("Hello, World!");
   return 0;
}									

Output

Program to Print an Integer


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int num;

    // printf() dislpays the string 
    printf("Enter an integer: ");  
    
    // scanf() here is written to read an integer value where
    // %d is the format specifier denoting an integer
    scanf("%d", &num);  
    
    // printf() displays the formatted output
    printf("You entered: %d", num);
    return 0;
}									

Output

Program to Add two Integers


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int num1, num2, sumOfNumbers;
    
    printf("Enter two integers: ");

    // Two integers entered by user is stored using scanf() function
    scanf("%d %d", &num1, &num2);

    // We perform the addition and the result is stored in the variable sumOfNumbers
    sumOfNumbers = num1 + num2;

    // Displays sum      
    printf("%d + %d = %d", num1, num2, sumOfNumbers);

    return 0;
}									

Output

Program to Multiply two Floating Point Numbers


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    double num1, num2, product;
    printf("Enter two numbers: ");

    // Stores two floating point numbers in variable num1 and num2 respectively
    scanf("%lf%lf", &num1, &num2);  
 
    // Performs multiplication and stores the result in variable product
    product = num1 * num2;  

    
    printf("Product = %lf", product);
    
    return 0;
}									

Output

Program to Find ASCII Value of a Character


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    char ch;
    printf("Enter a character: ");

    // Reads character input from the user
    scanf("%c", &ch);  
    
    // %d displays the integer value of a character
    // %c displays the actual character
    printf("ASCII value of %c = %d", ch, ch);
    return 0;
}									

Output

Program to Compute Quotient and Remainder


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{

    int dividend, divisor, quotient, remainder;

    printf("Enter dividend: ");
    scanf("%d", &dividend);

    printf("Enter divisor: ");
    scanf("%d", &divisor);

    // Computes quotient
    quotient = dividend / divisor;

    // Computes remainder
    remainder = dividend % divisor;

    printf("Quotient = %d\n", quotient);
    printf("Remainder = %d", remainder);

    return 0;
}									

Output

Program to Find the Size of different data types


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int intVar;
    float floatVar;
    double doubleVar;
    char charVar;

    // Sizeof operator is used to evaluate the size of a variable
    // The size of operators prints a long int hence the format specifier is %ld
    printf("Size of int: %ld bytes\n",sizeof(intVar));
    printf("Size of float: %ld bytes\n",sizeof(floatVar));
    printf("Size of double: %ld bytes\n",sizeof(doubleVar));
    printf("Size of char: %ld byte\n",sizeof(charVar));

    return 0;
}									

Output

Program to Demonstrate the Working of Keyword long


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int a;
    long b;
    long long c;

    double e;
    long double f;


    printf("Size of int = %ld bytes \n", sizeof(a));
    printf("Size of long = %ld bytes\n", sizeof(b));
    printf("Size of long long = %ld bytes\n", sizeof(c));

    printf("Size of double = %ld bytes\n", sizeof(e));
    printf("Size of long double = %ld bytes\n", sizeof(f));

    return 0;
}									

Output

Program to Swap Two Numbers


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
      int num1, num2, tempVar;

      printf("Enter first number: ");
      scanf("%d", &num1);

      printf("Enter second number: ");
      scanf("%d",&num2);

      // Value of num1 is assigned to tempVar
      tempVar = num1;

      // Value of num2 is assigned to num1
      num1 = num2;

      // Value of tempVar (which contains the initial value of num1) is assigned to num2
      num2 = tempVar;

      printf("\nAfter swapping, num1 = %d\n", num1);
      printf("After swapping, num2 = %d", num2);

      return 0;
}									

Output

Program to Check Whether a Number is Even or Odd


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int num;

    printf("Enter an integer: ");
    scanf("%d", &num);

    // An even number is divisible by 2 i.e. its remainder when divided by 2 is 0
    if(num % 2 == 0)
        printf("%d is even.", num);
    else
        printf("%d is odd.", num);

    return 0;
}									

Output

Program to Check Whether a Character is Vowel or Consonant


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    char c;

    printf("Enter an alphabet: ");
    scanf("%c",&c);

    // evaluates to 1 if the character is either a lower case one or an upper case one
    if ((c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') || (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'))
        printf("%c is a vowel.", c);
    else
        printf("%c is not a vowel.", c);
    return 0;
}									

Output

Program to Find the Largest Number Among Three Numbers


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int n1, n2, largeAmong2, n3;

    printf("Enter three different numbers: ");
    scanf("%d%d%d", &n1, &n2, &n3);

    // First find the largest among 2 numbers and store the result in a variable
    if( n1>=n2)
    	largeAmong2 = n1;
    else
    	largeAmong2 = n2;

    //Now compare this variable with the 3rd variable to print the highest
    if( largeAmong2>=n3 )
        printf("The largest is %d", largeAmong2);
    else
        printf("The largest is %d", n3);

    return 0;
}									

Output

Program to Find all Roots of a Quadratic Equation


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
//including a header file math.h for using math functions
#include <math.h>
int main()
{
    double a, b, c, determinant, root1,root2;
    // In this program we are assuming that the roots assumed 
    printf("Enter coefficients a, b and c: ");
    scanf("%lf%lf%lf",&a, &b, &c);

    determinant = b*b-4*a*c;

    // sqrt() function returns square root is present in math.h
    root1 = (-b+sqrt(determinant))/(2*a);
    root2 = (-b-sqrt(determinant))/(2*a);

    printf("root1 = %.2lf and root2 = %.2lf",root1 , root2);
   
    return 0;
}									

Output

Program to Check Leap Year


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int year;

    printf("Enter a year: ");
    scanf("%d",&year);

    if(year%4 == 0)
    {
        if( year%100 == 0)
        {
            // year is divisible by 400, hence the year is a leap year
            if ( year%400 == 0)
                printf("%d is a leap year.", year);
            else
                printf("%d is not a leap year.", year);
        }
        else
            printf("%d is a leap year.", year );
    }
    else
        printf("%d is not a leap year.", year);
    
    return 0;
}									

Output 1

Output 2

Program to Check Whether a Number is Positive or Negative


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    double number;

    printf("Enter a number: ");
    scanf("%lf", &number);

    if (number <= 0.0)
    {
        if (number == 0.0)
            printf("You entered 0.");
        else
            printf("You entered a negative number.");
    }
    else
        printf("You entered a positive number.");
    return 0;
}									

Output

Program to Check Whether a Character is an Alphabet or not


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    char c;
    printf("Enter a character: ");
    scanf("%c",&c);

    if( (c>='a' && c<='z') || (c>='A' && c<='Z'))
        printf("%c is an alphabet.",c);
    else
        printf("%c is not an alphabet.",c);

    return 0;
}									

Output

Program to Calculate the Sum of Natural Numbers


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int n, i, sum = 0;
    
    printf("Enter a positive integer: ");
    scanf("%d",&n);

    // Initially the sum is 0 
    // When we encounter 1 the sum will be 0+1 = 1
    // When we encounter 2 the sum will be 1+2 = 3 (The previous sum is added to the current value 
    // of i)
    for(i=1; i <= n; i++)
    {
         sum = sum+i;
    }

    printf("Sum = %d",sum);

    return 0;
}									

Output

Program to Find Factorial of a Number


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int n, i;
    int factorial = 1;

    printf("Enter an integer: ");
    scanf("%d",&n);

    // factorial is the product of the 1st n numbers
    for(i=1; i<=n; ++i)
    {
        factorial *= i;              // factorial = factorial*i;
    }
        
    printf("Factorial of %d = %d", n, factorial);
    
    return 0;
}									

Output

Program to Generate Multiplication Table


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int n, i;

    printf("Enter an integer: ");
    scanf("%d",&n);

    for(i=1; i<=10; ++i)
    {
        printf("%d * %d = %d \n", n, i, n*i);
    }
    
    return 0;
}									

Output

Program to Display Fibonacci Sequence


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int i, n, first = 0, second = 1, third;

    printf("Enter the number of terms: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");
    // The third term is the summation of the first two terms
    for (i = 1; i <= n; ++i)
    {
        printf("%d, ", first);
        third = first + second;
        //first becomes the previous second and the second becomes the previous third
        first = second;
        second = third;
    }
    return 0;
}									

Output

Program to Find number of digits in a number


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int n;
    int count = 0;

    printf("Enter an integer: ");
    scanf("%d", &n);
    // Keep dividing the number by 10, the number of times it can divide 10 that many digits exist
    //in the number
    while(n != 0)
    {
        // n = n/10
        n /= 10;
        ++count;
    }

    printf("Number of digits: %d", count);
}									

Output

Program to Reverse a number


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int n, rev = 0, digit;

    printf("Enter an integer: ");
    scanf("%d", &n);

    while(n != 0)
    {
        digit = n%10;
        // The reverse calculated so far is multiplied by 10 and then added to the reverse
        rev = rev*10 + digit;
        n /= 10;
    }

    printf("Reversed Number = %d", rev);

    return 0;
}									

Output

Program to Check whether a number is armstrong or not


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
	// In this definition of the armstrong number 
	// We are checking whether the number is same as the sum of the cubes of the digits
    int number, originalNumber, digit, sum = 0;

    printf("Enter a three digit integer: ");
    scanf("%d", &number);

    originalNumber = number;

    while (originalNumber != 0)
    {
        digit = originalNumber%10;
        sum += digit*digit*digit;
        originalNumber /= 10;
    }

    if(sum == number)
        printf("%d is an Armstrong number.",number);
    else
        printf("%d is not an Armstrong number.",number);

    return 0;
}									

Output

Program to Find Largest Element in an array


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int i, n;
    float arr[100],max;

    printf("Enter total number of elements(1 to 100): ");
    scanf("%d", &n);
    printf("\n");

    // Stores number entered by the user
    for(i = 0; i < n; ++i)
    {
       printf("Enter Number %d: ", i+1);
       scanf("%f", &arr[i]);
    }
    //Assume the first value to be the maximum 
    max = arr[0];
    // Loop to store largest number to arr[0]
    for(i = 1; i < n; ++i)
    {
       // Change < to > if you want to find the smallest element
       if(max < arr[i])
           max = arr[i];
    }
    printf("Largest element = %.2f", max);

    return 0;
}									

Output

Program to Concatenate 2 strings without using strcat


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    char s1[100], s2[100], i, j;

    printf("Enter first string: ");
    scanf("%s", s1);

    printf("Enter second string: ");
    scanf("%s", s2);

    // calculate the length of string s1
    // and store it in i
    for(i = 0; s1[i] != '\0'; ++i);

   	// from the end of the 1st string keep concatenating the 2nd string
    for(j = 0; s2[j] != '\0'; ++j, ++i)
    {
        s1[i] = s2[j];
    }
    //you need to manually include the null character because the original one will be over written
    s1[i] = '\0';
    printf("After concatenation: %s", s1);

    return 0;
}									

Output

Program to Create pattern


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int i, j, rows;

    printf("Enter number of rows: ");
    scanf("%d",&rows);

    for(i=rows; i>=1; --i) //Responsible for the rows
    {
        for(j=1; j<=i; ++j) //Responsible for the columns
        {
            printf("* ");
        }
        printf("\n");
    }
    
    return 0;
}									

Output

Program to Find transpose of a matrix


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main()
{
    int a[10][10], trpose[10][10], r, c, i, j;
    printf("Enter rows and columns of matrix: ");
    scanf("%d %d", &r, &c);

    // Storing elements of the matrix
    printf("\nEnter elements of matrix:\n");
    for(i=0; i<r; ++i)
        for(j=0; j<c; ++j)
        {
            printf("Enter element a%d%d: ",i+1, j+1);
            scanf("%d", &a[i][j]);
        }

    // Displaying the matrix a[][] */
    printf("\nEntered Matrix: \n");
    for(i=0; i<r; ++i)
    {
        for(j=0; j<c; ++j)
        {
            printf("%d  ", a[i][j]);       
        }
         printf("\n");
    }

    // Finding the transpose of matrix a
    // Interchanging the contents of the rows and the columns
    for(i=0; i<r; ++i)
        for(j=0; j<c; ++j)
        {
            trpose[j][i] = a[i][j];
        }

    // Displaying the transpose of matrix a
    printf("\nTranspose of Matrix:\n");
    for(i=0; i<c; ++i)
    {
    	for(j=0; j<r; ++j)
        {
            printf("%d  ",trpose[i][j]);
            
        }
		printf("\n");
	}

    return 0;
}									

Output

Program to Store information of student in a structure


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
struct student
{
    char name[50];
    int roll;
    float marks;
} ;

int main()
{
    
	struct student s;

    printf("Enter information:\n");

    printf("Enter name: ");
    scanf("%s", s.name);

    printf("Enter roll number: ");
    scanf("%d", &s.roll);

    printf("Enter marks: ");
    scanf("%f", &s.marks);


    printf("Displaying Information:\n");

    printf("Name: ");
    puts(s.name);

    printf("Roll number: %d\n",s.roll);

    printf("Marks: %.1f\n", s.marks);

    return 0;
}									

Output

Program to Pass two complex numbers in a function


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
typedef struct complex
{
    float real;
    float imag;
}complex;
complex add(complex num1, complex num2)
{
      complex sum;

      sum.real = num1.real + num2.real;
      sum.imag = num1.imag + num2.imag;

      return sum;
}

int main()
{
    complex num1, num2, sum;

    printf("For 1st complex number \n");
    printf("Enter real and imaginary part respectively:\n");
    scanf("%f%f", &num1.real, &num1.imag);

    printf("\nFor 2nd complex number \n");
    printf("Enter real and imaginary part respectively:\n");
    scanf("%f%f", &num2.real, &num2.imag);

    sum = add(num1, num2);
    printf("Sum = %.1f + %.1fi", sum.real, sum.imag);

    return 0;
}									

Output

Program on Array of structures example


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
struct student
{
    char name[50];
    int roll;
    float marks;
};

int main()
{
    struct student s[10];

    int i;

    printf("Enter information of students:\n");

    // storing information
    for(i=0; i<10; ++i)
    {
        s[i].roll = i+1;

        printf("\nFor roll number%d,\n",s[i].roll);

        printf("Enter name: ");
        scanf("%s",s[i].name);

        printf("Enter marks: ");
        scanf("%f",&s[i].marks);

        printf("\n");
    }

    printf("Displaying Information:\n\n");
    // displaying information
    for(i=0; i<10; ++i)
    {
        printf("\nRoll number: %d\n",i+1);
        printf("Name: ");
        puts(s[i].name);
        printf("Marks: %.1f",s[i].marks);
        printf("\n");
    }
    return 0;
}									

Output

Program for GCD using Recursion


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int hcf(int num1, int num2);
int main()
{
   int num1, num2;
   printf("Enter two positive integers: ");
   scanf("%d%d", &num1, &num2);

   printf("G.C.D of %d and %d is %d.", num1, num2, hcf(num1,num2));
   return 0;
}

int hcf(int num1, int num2)
{
    if (num2 != 0)
       return hcf(num2, num1%num2);
    else 
       return num1;
}									

Output

Program for Calculator using switch case


 
// Note the program is written using GCC Compiler 
#include <stdio.h>
int main() 
{

    char op;
    double num1,num2;

    printf("Enter an op (+, -, *,): ");
    scanf("%c", &op);

    printf("Enter two operands: ");
    scanf("%lf %lf",&num1, &num2);

    switch(op)
    {
        case '+':
            printf("%.1lf + %.1lf = %.1lf",num1, num2, num1 + num2);
            break;

        case '-':
            printf("%.1lf - %.1lf = %.1lf",num1, num2, num1 - num2);
            break;

        case '*':
            printf("%.1lf * %.1lf = %.1lf",num1, num2, num1 * num2);
            break;

        case '/':
            printf("%.1lf / %.1lf = %.1lf",num1, num2, num1 / num2);
            break;

        // op doesn't match any case constant (+, -, *, /)
        default:
            printf("Error! op is not correct");
    }
    
    return 0;
}									

Output