C Program To Find Absolute Value of a Number

Write a C program to find absolute value of a number entered through the keyboard.

Absolute Value
In mathematics, the absolute value or modulus |x| of a real number x is the non-negative value of x without regard to its sign. The absolute value of a number may be thought of as its distance from zero.

Note: abs() is a builtin method/function present in library/header file stdlib.h

Example For Absolute Value of a Number

1. If user enters/inputs a value of 5. Then the distance from 0 to 5 is 5 units. So the absolute value of 5 is 5. Mathematically its written as |5| = 5. Its read as Modulus 5 is 5.

2. If user enters/inputs a value of -5. Then the distance from 0 to -5 is 5 units. So the absolute value of -5 is 5. Mathematically its written as |-5| = 5. Its read as Modulus -5 is 5.

scale

Expected Output for the Input

User Input:
Enter a positive or negative number
-14

Output:
Absolute Value of -14 is 14

Video Tutorial: C Program To Find Absolute Value of a Number


[youtube https://www.youtube.com/watch?v=O8Q7YEgq7_c]

YouTube Link: https://www.youtube.com/watch?v=O8Q7YEgq7_c [Watch the Video In Full Screen.]

Source Code: C Program To Find Absolute Value of a Number

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

int main()
{
    int num;

    printf("Enter a positive or negative number\n");
    scanf("%d", &num);

    printf("Absolute Value of |%d| is %d\n", num, abs(num));

    return 0;
}

Output 1:
Enter a positive or negative number
14
Absolute Value of |14| is 14

Output 2:
Enter a positive or negative number
41
Absolute Value of |41| is 41

Output 3:
Enter a positive or negative number
-2
Absolute Value of |-2| is 2

Output 4:
Enter a positive or negative number
2
Absolute Value of |2| is 2

Output 5:
Enter a positive or negative number
-100
Absolute Value of |-100| is 100

Note: abs() works only for integer values and not for floating or double type data.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Find The Day on 01 January using Gregorian Calendar

According to the Gregorian Calendar, it was Monday on the date 01/01/01. If any year is input through the keyboard write a program to find out what is the day on 1st January of this year.

Note: From 01/01 we understand that it’s 1st of January. We shall take the year as 1900. We also know that 01 January 1900 was Monday.

Related Read
while loop in C programming
C Program To Check Leap Year
Simple Calculator Program using Switch Case: C

Gregorian Calendar: the calendar introduced in 1582 by Pope Gregory XIII, as a modification of the Julian Calendar.

Expected Output for the Input

User Input:
Enter a year between 1900 and 2099
2020

Output:
The day on 01 January 2020 was Wednesday.

Video Tutorial: C Program To Find The Day on 01 January in Gregorian Calendar


[youtube https://www.youtube.com/watch?v=mG2gfYAX14Q]

YouTube Link: https://www.youtube.com/watch?v=mG2gfYAX14Q [Watch the Video In Full Screen.]

Logic To Find The Day on 01 January using Gregorian Calendar

We take reference year as 1900. We ask the user to enter a year between 1900 and 2099 and store it inside the address of variable year. Now we find the difference (1900 – year) and store it inside variable diff.

Using while loop, we loop through until reference year(1900) is less than the user entered year. Inside the while loop we check for all the leap years present from 1900 to user entered year.

Next we calculate exact number of days between 1900 and user entered year using formula:

diff = ref_year – year;
Total no of leap years is calculated and stored in variable leap.

Total_days = (diff – leap) x 365 + leap x 366;

Now every year has 12 months, but each month has different number of days. But every week has exactly 7 days. So we divide Total_days by 7 and store the reminder inside variable day.

Note: Since our reference year 1900 has Monday on 1st of January. So we take Monday as first day:

0 Monday
1 Tuesday
2 Wednesday
3 Thursday
4 Friday
5 Saturday
6 Sunday

We make use of Switch case to match the number in variable day to the day of the week.

Source Code: C Program To Find The Day on 01 January using Gregorian Calendar

#include < stdio.h >

int main()
{
    int ref_year = 1900, year, leap = 0, diff, total_days = 0, day = 0;

    printf("Enter a year between 1900 and 2099\n");
    scanf("%d", &year);

    diff = year - ref_year;

    while(ref_year < year)
    {
        if(ref_year % 100 == 0)
        {
            if(ref_year % 400 == 0)
            {
                leap++;
            }
        }
        else
        {
            if(ref_year % 4 == 0)
            {
                leap++;
            }
        }
        ref_year++;
    }

    total_days = (diff - leap) * 365 + leap * 366;
    day        = total_days % 7;

    printf("\nThe day on 01 January %d was ", year);

    switch(day)
    {
        case 0: printf("Monday.\n");
                break;
        case 1: printf("Tuesday.\n");
                break;
        case 2: printf("Wednesday.\n");
                break;
        case 3: printf("Thursday.\n");
                break;
        case 4: printf("Friday.\n");
                break;
        case 5: printf("Saturday.\n");
                break;
        case 6: printf("Sunday.\n");
                break;
    }

    return 0;
}

Output 1:
Enter a year between 1900 and 2099
1900

The day on 01 January 1900 was Monday.

Output 2:
Enter a year between 1900 and 2099
2015

The day on 01 January 2015 was Thursday.

Output 3:
Enter a year between 1900 and 2099
2016

The day on 01 January 2016 was Friday.

Output 4:
Enter a year between 1900 and 2099
2017

The day on 01 January 2017 was Sunday.

Output 5:
Enter a year between 1900 and 2099
2018

The day on 01 January 2018 was Monday.

Lets Use Ternary / Conditional Operator To Find Leap Year

We modify above program and use Ternary Operator or Conditional Operator to find leap year. You can find detailed explanation of finding leap year using Conditional Operator here: C Program To Check Leap Year Using Ternary Operator

Source Code: C Program To Find The Day on 01 January using Gregorian Calendar Using Ternary or Conditional Operator

#include < stdio.h >

int main()
{
    int ref_year = 1900, year, leap = 0, nonleap = 0, total_days = 0, day = 0;

    printf("Enter a year between 1900 and 2099\n");
    scanf("%d", &year);

    while(ref_year < year)
    {
        (ref_year % 100 == 0) ?
        ( (ref_year % 400 == 0)?
          (leap++):
          (nonleap++)
        ) :
        ( (ref_year % 4 == 0)?
          (leap++):
          (nonleap++)
        );

        ref_year++;
    }

    total_days = nonleap * 365 + leap * 366;
    day        = total_days % 7;

    printf("\nThe day on 01 January %d was ", year);

    switch(day)
    {
        case 0: printf("Monday.\n");
                break;
        case 1: printf("Tuesday.\n");
                break;
        case 2: printf("Wednesday.\n");
                break;
        case 3: printf("Thursday.\n");
                break;
        case 4: printf("Friday.\n");
                break;
        case 5: printf("Saturday.\n");
                break;
        case 6: printf("Sunday.\n");
                break;
    }

    return 0;
}

Output 1:
Enter a year between 1900 and 2099
2019

The day on 01 January 2019 was Tuesday.

Output 2:
Enter a year between 1900 and 2099
2020

The day on 01 January 2020 was Wednesday.

Output 3:
Enter a year between 1900 and 2099
2021

The day on 01 January 2021 was Friday.

Output 4:
Enter a year between 1900 and 2099
2022

The day on 01 January 2022 was Saturday.

Output 5:
Enter a year between 1900 and 2099
2023

The day on 01 January 2023 was Sunday.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Draw Pyramid of Numbers, using While Loop

Lets write a C program to draw / print / display a pyramid / triangle formed from Decimal numbers(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), using while loop.

Related Read:
Nested While Loop: C Program
C Program To Draw Pyramid of Stars, using While Loop
C Program To Draw Pyramid of Alphabets, using While Loop

Expected Output for the Input

User Input:
Enter the maximum no of rows for Pyramid
5

Output:

    
     0
    123
   45678
  9012345
 678901234

Pyramid With 20 Rows
pyramid of numbers

Video Tutorial: C Program To Draw Pyramid of Numbers, using While Loop


[youtube https://www.youtube.com/watch?v=qxUYMf-Fn18]

YouTube Link: https://www.youtube.com/watch?v=qxUYMf-Fn18 [Watch the Video In Full Screen.]

Logic To Draw Pyramid of Numbers, using While Loop

We ask the user to enter the maximum number of rows for the pyramid and store it inside the address of variable num. We declare and initialize a variable row to 1(indicating first row of the pyramid).

In the outer while loop we check if row is less than or equal to num. For each iteration of the while loop we increment the value of row by 1. So the row value will have the row number i.e., for each iteration of the outer while loop we select row one by one (to print the numbers in that selected row).

Inside first inner while loop we print the adequate number of space for each row. Inside the second inner while loop we actually print the numbers needed for each row.

At the end, result will be a pyramid with the number of rows as input by the user.

Source Code: C Program To Draw Pyramid of Numbers, using While Loop

#include < stdio.h >

int main()
{
    int num, i, row = 1, number = 0;

    printf("Enter the maximum no of rows for Pyramid\n");
    scanf("%d", &num);

    while(row <= num)
    {
        i = 0;
        while(i <= (num-row))
        {
            printf(" ");
            i++;
        }

        i = 0;
        while(i < (2*row-1))
        {
            printf("%d", number);

            if(number == 9)
                number = 0;
            else
                number++;

            i++;
        }
        printf("\n");
        row++;
    }
    return 0;
}

Output
Enter the maximum no of rows for Pyramid
14

              0
             123
            45678
           9012345
          678901234
         56789012345
        6789012345678
       901234567890123
      45678901234567890
     1234567890123456789
    012345678901234567890
   12345678901234567890123
  4567890123456789012345678
 901234567890123456789012345

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Draw Pyramid of Alphabets, using While Loop

Lets write a C program to draw / print / display a pyramid / triangle formed from uppercase / capital letter English Alphabets, using while loop.

Related Read:
Nested While Loop: C Program
C Program To Draw Pyramid of Stars, using While Loop

Expected Output for the Input

User Input:
Enter the number of rows for Pyramid
5

Output:

    
     A
    BCD
   EFGHI
  JKLMNOP
 QRSTUVWXY

Pyramid With 20 Rows
pyramid of alphabets

Video Tutorial: C Program To Draw Pyramid of Alphabets, using While Loop


[youtube https://www.youtube.com/watch?v=eDPYA_c73I4]

YouTube Link: https://www.youtube.com/watch?v=eDPYA_c73I4 [Watch the Video In Full Screen.]

Logic To Draw Pyramid of Alphabets, using While Loop

We ask the user to enter the maximum number of rows for the pyramid and store it inside the address of variable num. We declare and initialize a variable count to 1(indicating first row of the pyramid).

In the outer while loop we check if count is less than or equal to num. For each iteration of the while loop we increment the value of count by 1. So the count value will have the row number i.e., for each iteration of the outer while loop we select row one by one (to print the alphabets).

Inside first inner while loop we print the adequate number of space for each row. Inside the second inner while loop we actually print the alphabets needed for each row.

At the end the result will be a pyramid with the number of rows as input by the user.

ASCII Value of Capital Letter English Alphabets

ASCII value of A is 65

ASCII value of B is 66

ASCII value of C is 67

ASCII value of D is 68

ASCII value of E is 69

ASCII value of F is 70

ASCII value of G is 71

ASCII value of H is 72

ASCII value of I is 73

ASCII value of J is 74

ASCII value of K is 75

ASCII value of L is 76

ASCII value of M is 77

ASCII value of N is 78

ASCII value of O is 79

ASCII value of P is 80

ASCII value of Q is 81

ASCII value of R is 82

ASCII value of S is 83

ASCII value of T is 84

ASCII value of U is 85

ASCII value of V is 86

ASCII value of W is 87

ASCII value of X is 88

ASCII value of Y is 89

ASCII value of Z is 90

Reference: C Program To Print All ASCII Characters and Code

Source Code: C Program To Draw Pyramid of Alphabets, using While Loop

#include < stdio.h >

int main()
{
    int num, count = 1, i, alphabet = 65;

    printf("Enter the number of rows for Pyramid\n");
    scanf("%d", &num);

    while(count <= num)
    {
        i = 0;
        while(i <= (num-count))
        {
            printf(" ");
            i++;
        }

        i = 0;
        while(i < (2*count-1))
        {
            printf("%c", alphabet);

            if(alphabet == 90)
            {
                alphabet = 64;
            }

            alphabet++;
            i++;
        }
        printf("\n");
        count++;
    }

    return 0;
}

Output
Enter the number of rows for Pyramid
14

              A
             BCD
            EFGHI
           JKLMNOP
          QRSTUVWXY
         ZABCDEFGHIJ
        KLMNOPQRSTUVW
       XYZABCDEFGHIJKL
      MNOPQRSTUVWXYZABC
     DEFGHIJKLMNOPQRSTUV
    WXYZABCDEFGHIJKLMNOPQ
   RSTUVWXYZABCDEFGHIJKLMN
  OPQRSTUVWXYZABCDEFGHIJKLM
 NOPQRSTUVWXYZABCDEFGHIJKLMN

Note: Inside second nested while loop we are checking for the condition – if alphabet is equal to 90(ASCII value of Z), and then reinitializing it to 64(but ASCII value of A is 65), that is because after the if condition is executed we have alphabet++; statement which increments the value of variable alphabet from 64 to 65(which is the ASCII value of A).

Alphabets and ASCII Value
We can even write the code in if else block as shown below:

        i = 0;
        while(i < (2*count-1))
        {
            printf("%c", alphabet);

            if(alphabet == 90)
            {
                alphabet = 65;
            }
            else
            {
                alphabet++;
            }
            i++;
        }

In this case we assign the value of variable alphabet to 65(ASCII value of A) once it has reached a value of 90(ASCII value of Z).

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

C Program To Calculate Area of Rhombus

Lets write a C program to calculate area of a Rhombus using its side and a diagonal. We ask the user to input the value of side and a diagonal.

A Rhombus is a polygon having 4 equal sides in which both the opposite sides are parallel and opposite angles are equal.

area of rhombus

First we calculate the value of second diagonal. Once we know the value of both the diagonals of the Rhombus, its easy and straightforward to calculate the area of Rhombus using the formula:

q = sqrt( (4 x side x side) – (p x p) );
p = sqrt( (4 x side x side) – (q x q) );

area = (p x q) / 2.0;
OR
area = (p x q) x 0.5;

where p and q are diagonals of the Rhombus.

Expected Output for the Input

User Input:
Enter length of side of the Square
10.5

Output:
Area of the Square is 110.250000
Perimeter of the Square is 42.000000
Diagonal of the Square is 14.849242

Video Tutorial: C Program To Calculate Area of Rhombus


[youtube https://www.youtube.com/watch?v=Cw2rQWgmbvc]

YouTube Link: https://www.youtube.com/watch?v=Cw2rQWgmbvc [Watch the Video In Full Screen.]

Source Code: C Program To Calculate Area of Rhombus

#include<stdio.h>
#include<math.h>

int main()
{
    float area, side, p, q;

    printf("Enter the length of side and a diagonal\n");
    scanf("%f%f", &side, &p);

    q    = sqrt( (4 * side * side) - (p * p) );
    area = (p * q) * 0.5;

    printf("Area of the Rhombus is %f \n", area);

    return 0;
}

Output 1:
Enter the length of side and a diagonal
5
7.07
Area of the Rhombus is 25.000000

Output 2:
Enter the length of side and a diagonal
10
16
Area of the Rhombus is 96.000000

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert