If else Ladder Statement in C Programming

The if else ladder statement in C programming language is used to test set of conditions in sequence. An if condition is tested only when all previous if conditions in if-else ladder is false. If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.

Syntax of if else ladder statement

if(condition_expression_One) {
    statement1;
} else if (condition_expression_Two) {
    statement2;
} else if (condition_expression_Three) {
    statement3;
} else {
    statement4;
}
  • First of all condition_expression_One is tested and if it is true then statement1 will be executed and control comes out out of whole if else ladder.
  • If condition_expression_One is false then only condition_expression_Two is tested. Control will keep on flowing downward, If none of the conditional expression is true.
  • The last else is the default block of code which will gets executed if none of the conditional expression is true.

C-If-Else-Ladder-Statement

C Program to print grade of a student using If Else Ladder Statement

If else Ladder Statement in C Programming

#include<stdio.h>
#include<conio.h>
 
int main(){
    int marks;
     
    printf("Enter your marks between 0-100\n");
    scanf("%d", &marks);
    /* Using if else ladder statement to print
       Grade of a Student */
    if(marks >= 90){
        /* Marks between 90-100 */
        printf("YOUR GRADE : A\n");
    } else if (marks >= 70 && marks < 90){
        /* Marks between 70-89 */
        printf("YOUR GRADE : B\n");
    } else if (marks >= 50 && marks < 70){
        /* Marks between 50-69 */
        printf("YOUR GRADE : C\n");
    } else {
        /* Marks less than 50 */
        printf("YOUR GRADE : Failed\n");
    }
       
    getch();
    return(0);
}

Above program check whether a student passed or failed in examination using if statement.

Output

Enter your marks
96
YOUR GRADE : A
Enter your marks
75
YOUR GRADE : B
Enter your marks
60
YOUR GRADE : C
Enter your marks
35
YOUR GRADE : Failed

Points to Remember about If else ladder statement

  • The condition_expression is a boolean expression. It must evaluate to true or false value(In C, all non-zero and non-null values are considered as true and zero and null value is considered as false).
  • We may use more than one condition inside if else ladder statement
    For Example:
    if(condition_one && condition_two) {
    /* if code block */
    } else if(condition_three) {
    /* else code block */
    }
  • Default else block is optional in if-else ladder statement.
  • Opening and Closing Braces are optional, If the block of code of if else statement contains only one statement.
    For Example:
    if(condition_expression)
    statement1;
    else if(condition_expression)
    statement2;
    In above example only statement1 will gets executed if condition_expression is true.

C Program to Print Even Numbers Between 1 to 100 using For and While Loop | How to Write a C Program that Prints List of Even Numbers up to 100?

C Program to Print Even Numbers Between 1 to 100 using For and While Loop

Wondering How to Print Even Numbers between 1 to 100 using for Loop as well as While Loop? If so, don’t bother as ou tutorial completely describes how to write C Program that Prints Even Numbers between 1 to 100 using both for and while loops. You can simply check the sample programs over here and understand the logic to create one on your own. To learn the program effectively you need to be aware of the following

Even Numbers – Definition

Even Numbers are the numbers that are exactly divisible by 2. Even Numbers always end with digits 0, 2, 4, 6, 8. Smallest Positive Even Natural Number is 2.
Examples of Even Numbers are 2, 14, 16, 20, etc.

Write a C Program to Print Even Numbers Between 1 to 100 using For Loop?

This program will print the even numbers between 1 to 100 by using the for loop.

C Program to Print Even Numbers Between 1 to 100 using For and While Loop

#include <stdio.h>  
   
int main() {  
    int counter; 
    printf("Even numbers between 1 to 100\n");  
    /* 
     * Initialize counter with 1, and increment it in every iteration.
     * For every value of counter check whether it is even number or
     * not and print it accordingly 
     */ 
    for(counter = 1; counter <= 100; counter++) {  
        /* Even numbers are divisible by 2 */ 
        if(counter%2 == 0) { 
            /* counter is even, print it */
            printf("%d ", counter);  
        }  
    }  
   
    return 0;  
}

Logic:

  • Here we have declared the variable counter in the initial step
  • Later on, we have initialized the counter value by 1.
  • Using for loop we will check the condition counter <=100 and if it is met loop will execute by further checking the condition counter%2==0 or not to determine if the number is divisible by 2 or not. If it is true counter value is incremented and the loop iterates as such to get all the even numbers between 1 to 100.

Output

Even numbers between 1 to 100
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

Write a C Program to Print Even Numbers from 1 to 100 using While Loop?

The intent of the program is the same as above it is just that we have replaced the for loop with while loop to print the even numbers between 1 to 100. You can use the below program to find out all even numbers between 1 to n using while loop by simply declaring one more variable and enter the limit.

C program to print even numbers from 1 to N using while loop

#include <stdio.h>  
   
int main() {  
    int counter; 
    printf("Even numbers between 1 to 100\n");  
    /* 
     * Initialize counter with first even number 2, and increment 
     * it by 2 in every iteration.
     */
    counter = 2;
    while (counter <= 100) {  
        printf("%d ", counter);
        /* Add 2 to current even number 
           to get next even number */
        counter = counter + 2;  
    }  
   
    return 0;  
}

Logic:

  • Here a counter variable is declared in the above program i.e. is the loop counter
  • Initialize the loop counter by 2 as it is the first even number value
  • Use the while loop to check the counter number <=100 and execute the loop till the value of a number is less than or equal to 100.
  • If the condition is met then the loop executes and the counter value is incremented. the same is done till we get the even numbers between 1 to 100.

Output:

Even numbers between 1 to 100
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

C Program to Read an Amount and Find Number of Notes

C Program to Read an Amount and Find Number of Notes
  • Write a C program to accept an amount and find number of notes.

Required Knowledge

Starting from the highest denomination note, we will try to accommodate as many notes possible.
For example, let amount is A and current note is N, then number of notes is A/N and remaining amount is A%N.Let’s say A = 450 and N = 100, then number of 100 notes is 450/100 = 4 and remaining amount is 450%100 = 50.

We will repeat this process for all notes in decreasing order.

C program to accept an amount and find number of notes

C Program to Read an Amount and Find Number of Notes

/** 
 * C program to accept an amount and count number of notes 
 */ 
   
#include <stdio.h>  
   
int main() {  
    int number, i;
    int notes[7] = {1000, 500, 100, 50, 10, 5, 1};
    int noteCounter[7] = {0};  
    /* 
     * Take a number as input from user 
     */ 
    printf("Enter a Number\n");  
    scanf("%d", &number);  
       
    for(i = 0; i < 7; i++) {
        if(number >= notes[i]){
            noteCounter[i] = number/notes[i];
            number = number - noteCounter[i]*notes[i];
        }
    }
  
    /* Print notes */
    printf("Currency   Count\n");
    for(i = 0; i < 7; i++){
        if(noteCounter[i] != 0){
            printf("%d   %d\n", notes[i], noteCounter[i]);
        }
    }
     
    return 0;  
}

Output

Enter a Number
868
Currency   Count
500   1
100   3
50   1
10   1
1    3

C Program to Find Total, Average and Percentage Marks of Subjects

C program to find total, average and percentage marks of subjects
  • Write a C program to read marks of N subjects and find Total, Average and Percentage marks.
  • Wap in C to find average and percentage marks of all subjects.

Required Knowledge

We will first read the number of subjects and then marks of all subjects using for loop and scanf function. To get the total marks, we add the marks of all subject and to calculate average marks and percentage we will use below mentioned formulae.

  • Average Marks = Marks_Obtained/Number_Of_Subjects
  • Percentage of Marks = (Marks_Obtained/Total_Marks) X 100

C program to find total, average and percentage marks of subjects

C program to find total, average and percentage marks of subjects

/** 
 * C program to calculate total, average and percentage of all subjects 
 */ 
   
#include <stdio.h>  
   
int main(){
    int subjects, i;  
    float marks, total=0.0f, averageMarks, percentage;
   
    /* 
     * Take number of subjects as imput from user 
     */ 
    printf("Enter number of subjects\n");  
    scanf("%d", &subjects);  
   
    /* 
     * Take marks of subjects as input 
     */
    printf("Enter marks of subjects\n");  
    for(i = 0; i < subjects; i++){
     scanf("%f", &marks);
     total += marks; 
    }  
    averageMarks = total / subjects;
    /* Each subject is of 100 Marks*/ 
    percentage = (total/(subjects * 100)) * 100;  
   
    printf("Total Marks of %d Subjects = %0.4f\n",subjects,total);  
    printf("Average Marks = %.4f\n", averageMarks);  
    printf("Percentage = %.4f", percentage);  
   
    return 0;  
}

Output

Enter number of subjects
4
Enter marks of subjects
50
60
70
80
Total Marks of 4 Subjects = 260.0000
Average Marks = 65.0000
Percentage = 65.0000

C Program to Find Sum of Digits of a Number using Recursion

To find the sum of digits of a number, we have to add the each digit of a number. Here, to find the sum of digits of a number we will remove one digit at a time from a number and add it to a variable.

For Example
Sum of digits of 4265 = 4 + 2 + 6 + 5 = 17

To extract digits of a number we can use ‘/'(division) and ‘%'(modulus) operator. Number%10 will give the least significant digit of the Number, we will use it to get one digit of number at a time. To remove last least significant digit from number we will divide number by 10. We can use recursion to implement above mentioned algorithms because it can be expressed as recursive equation.

Let getSum(N) returns the sum of digits of N. We can express sum of digits of N recursively as :
getSum(N) = N%10 + getSum(N/10)

For Example
getSum(1234) = 1234%10 + getSum(1234/10) = 4 + getSum(123).

Algorithm to find the sum of digits of number using recursion
Let N be the input number.

  • N%10 gives the least significant digit of N(rightmost digit of N). For Example: 2345%10 = 5.
  • N/10 return the number after removing least significant digit of N(rightmost digit of N). For Example: 2345/10 = 234.

C program to calculate sum of digits of a number recursively

Below program user a user defined function getSumOfDigit, that takes an integer as input parameter(num) and return the it’s sum of digits. This function implements the above mentioned recursive algorithm using division and modulus operator. Recursion will terminate when num becomes zero.

C Program to Find Sum of Digits of a Number using Recursion

/*
* C Program to print sum of digits of a number using number
*/
#include <stdio.h>
#include <conio.h>
 
int main(){
    int num;
    printf("Enter a number \n");
    scanf("%d", &num);
    printf("Sum of digits of %d is %d\n", num, getSumOfDigit(num));
    getch();
    return 0;
}
 
/*
 * Function to calculate sum of digits of a number
 */
int getSumOfDigit(int num){
    /* Recursion termination condition*/
    if(num == 0)
        return 0;
                
    return num%10 + getSumOfDigit(num/10);    
}

Program Output

Enter a number 
3426
Sum of digits of 3426 is 15

C program to calculate sum of digits of a number using loop

Below program calculates the sum of digits of a number using while loop. It first takes a number as input from user using using scanf function and stores it in an integer variable. In line number 14, it extract the least significant digit of number and adds it to the variable digitSum. In line number 17, it removes the least significant digit from number. Inside the while loop, above process continues until number become zero.

C program to calculate sum of digits of a number using loop

/*
* C Program to find sum of digits of a number
*/
#include <stdio.h>
#include <conio.h>
  
int main(){
    int number, digitSum = 0;
    printf("Enter a number : ");
    scanf("%d", &number);
    while(number != 0){
        /* get the least significant digit(last digit)
         of number and add it to digitSum */
        digitSum += number % 10;
        /* remove least significant digit(last digit)
         form number */
        number = number/10;
    }    
    printf("Sum of digits : %d\n", digitSum);
    getch();
    return 0;
}

Program Output

Enter a number : 12345
Sum of digits : 15

C Program to Print a Matrix Diagonally

  • Write a C program to print a matrix diagonally from top to bottom

Given a matrix of size m x n, we have to print the matrix diagonally from right to left and top to bottom. We have to print one diagonal in a separate line.

The minor diagonal divides a matrix into two parts, elements above minor diagonal(upper half) and elements below minor diagonal(lower half). In below mentioned C program, we first print upper half of matrix then lower half of matrix diagonally.

For example, If input matrix is 
1 2 3 4
5 6 7 8
9 0 1 2
3 4 5 6
Then we should print output like this
1
2 5
3 6 9
4 7 0 3
8 1 4
2 5
6

Algorithm to print a matrix diagonally
Let A be a matrix of dimension M x N.

  • Minor diagonal of a matrix, divides it into two sections. All the elements above diagonals are upper diagonal elements and all the elements below diagonals are lower diagonal elements. We will print the matrix diagonally in two sections, first we will print upper diagonal elements then lower diagonal.
  • To print the upper diagonal elements we will use two for loops(check line 24 and 26 of below program). Outer loop will iterate over cols whereas inner loop will move the control left-down direction(by increasing row and decreasing column)
  • To print the lower diagonal elements we will use two for loops(check line 33 and 35 of below program). Outer loop will iterate over rows whereas inner loop will move the control left-down direction(by increasing row and decreasing column)

C program to print a matrix diagonally

C Program to Print a Matrix Diagonally

/*
* C Program to print a matrix diagonally from top to bottom
*/
 
#include <stdio.h>
#include <conio.h>
 
int main(){
    int rows, cols, rowCounter, colCounter, currentRow, currentCol;
    int inputMatrix[50][50];
     
    /*  Input matrix*/
    printf("Enter size of matrix\n");
    scanf("%d %d", &rows, &cols);
     
    printf("Enter the matrix of size %dX%d\n", rows, cols);
    for(rowCounter = 0; rowCounter < rows; rowCounter++){
        for(colCounter = 0; colCounter < cols; colCounter++){
            scanf("%d", &inputMatrix[rowCounter][colCounter]);
        }
    }
    printf("Printing matrix diagonally\n");
    // Print Upper half of matrix
    for(colCounter = 0; colCounter < cols; colCounter++){
        currentCol = colCounter; currentRow = 0;
        for(;currentCol >= 0 && currentRow < rows; currentCol--, currentRow++){
            printf("%d ", inputMatrix[currentRow][currentCol]); 
        }
        printf("\n");
    }
     
    // Print Lower half of matrix
    for(rowCounter = 1; rowCounter < rows; rowCounter++){
        currentCol = cols -1; currentRow = rowCounter;
        for(;currentCol >= 0 && currentRow < rows; currentCol--, currentRow++){
            printf("%d ", inputMatrix[currentRow][currentCol]); 
        }
        printf("\n");
    }
     
    getch();
    return 0;
}

Program Output

Enter the size of matrix
3 3
Enter matrix of size 3X3
1 2 3
4 5 6
7 8 9
Printing matrix diagonally
1
2 4
3 5 7
6 8
9

Enter the size of matrix
2 4
Enter matrix of size 2X4
1 2 3 4
5 6 7 8
Printing matrix diagonally
1
2 5
3 6
4 7
8

C Program to Find the Perimeter and Area of a Rectangle

C Program to Find the Perimeter and Area of a Rectangle
  • Write a C program to find perimeter and area of rectangle.
  • WAP in C to find perimeter of a rectangle.

Required Knowledge

To find the perimeter and area of rectangle, we will first take length and breadth of rectangle as input from user using scanf function and then calculate area and perimeter of rectangle using following formulae.

  • Perimeter of Rectangle = 2 x (length + width)
  • Area of Rectangle = length x width

C program to find the perimeter and area of rectangle

C Program to Find the Perimeter and Area of a Rectangle

/* 
 *  C program to find perimeter and area of Rectangle, 
 *  Given its length and Breadth
 */ 
   
#include <stdio.h>  
 
int main() {  
    float length, width, area, perimeter; 
   
    /* 
     * Take length and breadth as input from user using scanf 
     */ 
    printf("Enter length of Rectangle\n");  
    scanf("%f", &length);  
    printf("Enter width of Rectangle\n");  
    scanf("%f", &width);  
   
    /* Perimeter of Rectangle = 2 x (length + width) */ 
    perimeter = 2 * (length + width);  
    printf("Perimeter of Rectangle : %f\n", perimeter); 
     
    /* Area of Rectangle = length x width */ 
    area = length * width;
    printf("Area of Rectangle : %f\n", area);
   
    return 0;  
}

Output

Enter length of Rectangle
3.5
Enter width of Rectangle
5
Perimeter of Rectangle : 17.000000
Area of Rectangle : 17.500000

C Program to Convert Octal Number to Decimal Number System

  • Write a C program to convert octal number to decimal number system.
  • How to convert octal number to binary number.

Required Knowledge

Octal number system is a base 8 number system using digits 0 and 7 whereas Decimal number system is base 10 number system and using digits from 0 to 9. Given an octal number as input from user convert it to decimal number.

For Example

2015 in Octal is equivalent to 1037 in Decimal number system.

Algorithm to convert Octal to Decimal number

  • We multiply each octal digit with 8i and add them, where i is the position of the octal digit(starting from 0) from right side. Least significant digit is at position 0.

Let’s convert 2015(octal number) to decimal number
Decimal number = 2*83 + 0*82 + 1*81 + 5*80 = 1024 + 0 + 8 + 5 = 1037

C program to convert a octal number to decimal number

C Program to Convert Octal Number to Decimal Number System

#include <stdio.h>  
#include <math.h>    
   
int main() {  
    long octalNumber, decimalNumber=0;  
    int position=0, digit;  
   
    printf("Enter an Octal Number\n");  
    scanf("%ld", &octalNumber);  
     
    /* Converting octal number to decimal number */
    while(octalNumber!=0) {   
        /* get the least significant digit of octal number */
 
        digit = octalNumber%10;
        decimalNumber += digit*pow(8, position);    
   
        position++;  
        octalNumber /= 10;  
    }  
  
    printf("Decimal Number : %ld", decimalNumber);  
   
    return 0;  
}

Output

Enter an Octal Number
2015
Decimal Number : 1037
Enter an Octal Number
1234
Decimal Number : 668

C Program to Convert Octal Number to Binary Number System

  • Write a C program to convert octal number to binary number system.
  • How to convert Octal number to Binary number in C.

Required Knowledge

Binary number system is a base 2 number system using digits 0 and 1 whereas Octal number system is base 8 and using digits from 0 to 7. Given an octal number as input from user convert it to binary number.

For Example

1203 in Octal is equivalent to 1010000011 in Binary number system.

Algorithm to convert Octal to Binary number

  • Create a mapping between octal digits and binary sequence {(0 => 000), (1 => 001), (2 => 010), (3 => 011), (4 => 100), (5 => 101), (6 => 110), (7 => 111)}
  • Now, replace each octal digit with it’s corresponding binary sequence as mentioned above.

For Example:
Octal number : 1203
replace 1 by (001), 2 by (010), 0 by (000) and 3 by (011)
Decimal number = 001010000011 = 1010000011

C program to convert a octal number to binary number

C Program to Convert Octal Number to Binary Number System

#include <stdio.h>  
   
int main() {  
    int octalDigitToBinary[8] = {0, 1, 10, 11, 100, 101, 110, 111};  
    long long octalNumber, binaryNumber = 0, position;  
    int digit;  
       
    /* Take an Octal Number as input from user */ 
    printf("Enter an Octal Number\n");  
    scanf("%ld", &octalNumber); 
   
    position = 1;  
    /* Convert Octal Number to Binary Number */ 
    while(octalNumber != 0) {
        digit = octalNumber % 10;
        binaryNumber = (octalDigitToBinary[digit] * position) + binaryNumber;  
        octalNumber /= 10;  
        position *= 1000;  
    }
 
    printf("Binary Number = %ld", binaryNumber);
     
    return 0;
}

Output

Enter an Octal Number
1203
Binary Number = 1010000011
Enter an Octal Number
1111
Binary Number = 1001001001

C Program to Print All Negative Numbers of an Array

C Program to Print All Negative Numbers of an Array
  • Write a C program to print all negative numbers of an array.
  • How to print all negative elements of an integer array in C.

Required Knowledge

Algorithm to print negative numbers of an array
Let inputArray is an integer array having N elements.

  • Using a for loop, traverse inputArray from index 0 to N-1.
  • For every element inputArray[i], check whether it is negative number or not(inputArray[i] < 0) and print it accordingly.

C program to print all negative elements of an array

C Program to Print All Negative Numbers of an Array

#include <stdio.h>
#include <conio.h>
  
int main(){
    int inputArray[100], elementCount, counter;
      
    printf("Enter Number of Elements in Array\n");
    scanf("%d", &elementCount);
    printf("Enter %d numbers \n", elementCount);
     
    /* Read array elements */
    for(counter = 0; counter < elementCount; counter++){
        scanf("%d", &inputArray[counter]);
    }
        
    /* Iterate form index 0 to elementCount-1 and 
       check for negative numbers */
    printf("Negative Elements in Array\n");
    for(counter = 0; counter < elementCount; counter++){
        if(inputArray[counter] < 0) {
            printf("%d ", inputArray[counter]);
        }
    }
          
    getch();
    return 0;
}

Output

Enter Number of Elements in Array
8
Enter 8 numbers
2 -4 9 10 0 -5 -1 1
Negative Elements in Array
-4 -5 -1