C Program To Re-arrange Even and Odd Elements of An Array

Lets write a C program to re-arrange even and odd elements of an array.

Note: We need to arrange EVEN numbers at the top and ODD numbers to the bottom of the same array.

Example: Expected Input/Output

Enter 5 integer numbers
11
10
13
12
15

After re-arranging even and odd elements …
10
12
13
11
15

Visual Representation

Rearranging even and odd elements of an array

Video Tutorial: C Program To Re-arrange Even and Odd Elements of An Array


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

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

Source Code: C Program To Re-arrange Even and Odd Elements of An Array

#include<stdio.h>

#define N 10

int main()
{
    int a[N], i, j = N, temp;

    printf("Enter %d integer numbers\n", N);
    for(i = 0; i < N; i++)
        scanf("%d", &a[i]);

    for(i = 0; i <= j; i++)
    {
        if(a[i] % 2 != 0)
        {
            while(j > i)
            {
                j--;
                if(a[j] % 2 == 0)
                {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                    break;
                }
            }
        }
    }

    printf("\nAfter re-arranging even and odd elements ...\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 10 integer numbers
1
2
3
4
5
6
7
8
9
10

After re-arranging even and odd elements …
10
2
8
4
6
5
7
3
9
1

Logic To Re-arrange Even and Odd Elements of An Array

First we accept N integer numbers from the user and store it inside a[N]. Using “for loop” we iterate through the array elements one by one.

Inside For Loop
We initialize i to 0, which is the first index of any array. We iterate through this “for loop” until i is less than or equal to j. j represents the number of elements already sorted from bottom(N – 1) of the array. i.e., from index j to (N – 1) all the elements are already odd numbers. For each iteration of the for loop we increment the value of i by 1.

First if condition – inside for loop
Aim of our C program is to move all the even elements to top and odd elements to the bottom. So if the “for loop” selected element, which is present in a[i] already has a even number then we let that number stay there itself, and increment the value of i by one. If the “for loop” selected number, which is present in a[i] has odd number, then we start searching for a even number from the bottom of the same array to swap it with a[i].

Inside While loop
Assume that a[i] has a odd number. Now lets initialize j to the size of array, which is N. “While loop” executes until j is greater than i. Here i represents the number of elements already sorted from the top. i.e., from index 0 to i all the elements are already even numbers.

This “while loop” executes until j is greater than i. The value of i is set by “for loop”. It’s the index of the element which is selected by the “for loop”, which has ODD number. i.e., if the control has entered “while loop” that means a[i] has ODD number. “While Loop” checks for EVEN element from the bottom of the array to swap it with the ODD number present at a[i].

Second if condition – inside while loop
As soon as control enters the while loop we reduce the value of j by 1. So now j is (N – 1), which is the last element of any array. Next, if the “while loop” selected element, which is present at a[j] has EVEN number, then we swap that number with the ODD number present in a[i], and break out of the while loop.

For each iteration of “while loop” we decrement the value of j by 1. And we do not reset the value of j for each iteration of “for loop”.

Printing re-arranged array elements
Once control exits “for loop” we print the array elements from 0 to N -1 and it’ll have all EVEN numbers at the top and ODD numbers at the bottom.

Explanation With Example

If int a[5] = {11, 10, 13, 12, 15};
ODD: a[i] % 2 != 0
EVEN: a[j] % 2 == 0

    j = N;
    for(i = 0; i <= j; i++)
    {
        if(a[i] % 2 != 0)
        {
            while(j > i)
            {
                j--;
                if(a[j] % 2 == 0)
                {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                    break;
                }
            }
        }
    }
ia[i]ODDja[j]EVENSwap
011TRUE415FALSENO
011TRUE312TRUEYES
110FALSE213FALSENO

As you can see from above table swapping occurs at a[0] and a[3]. a[0] has integer number 11 and a[3] has integer number 12. So after swapping these numbers a[5] will be: {12, 10, 13, 11, 15}; So a[0], a[1] has EVEN numbers and a[2], a[3], a[4] has ODD numbers.

Important Note: i always represents the number of elements sorted from top(EVEN numbers), and j represents the index from (N – 1) which are sorted from bottom(ODD numbers).

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 Print Multiplication Table Using Macros

In this video lets see how we can print multiplication table(from 1 to 10) for any positive user input value, using Macros.

Related Read:
C Program To Print Multiplication Table Using While Loop

Video Tutorial: C Program To Print Multiplication Table Using Macros


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

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

Source Code: C Program To Print Multiplication Table Using Macros

#include<stdio.h>

#define MULTI(num, count) printf("%d x %d = %d\n", num, count, (num*count))

int main()
{
    int num, count = 1;

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

    printf("\nMultiplication Table for %d is: \n\n", num);

    while(count <= 10)
    {
        MULTI(num, count);
        count++;
    }

    return 0;
}

Output 1:
Enter a positive number
5

Multiplication Table for 5 is:

5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Output 2:
Enter a positive number
4

Multiplication Table for 4 is:

4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

Here we are initializing variable count to 1 and iterating the while loop until count is less than or equal to 10. For each iteration we’re executing macro MULTI(num, count). But before compilation itself preprocessor will have replaced MULTI(num, count) by its macro expansion, which is printf(“%d x %d = %d\n”, num, count, (num*count)).

Note: If you see \ inside macro expansion – it is called as Macro continuation(\) operator. It is used to continue the code in next line, in macro expansion.

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 GCD using Repeated Subtraction

Lets write a C program to find Greatest Common Divisor of two positive integer numbers using repeated subtraction.

Related Read:
C Program to Find GCD or HCF of Two Numbers
C Program To Find GCD and LCM of Two Numbers using Euclidean algorithm
C Program To Find GCD using Pointers and Functions

Video Tutorial: C Program To Find GCD using Repeated Subtraction


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

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


Source Code: C Program To Find GCD using Repeated Subtraction

#include<stdio.h>

int main()
{
    int num1, num2;

    printf("Enter 2 positive integer numbers\n");
    scanf("%d%d", &num1, &num2);

    num1 = (num1 < 0) ? -num1 : num1;
    num2 = (num2 < 0) ? -num2 : num2;

    printf("\nGreatest Common Divisor of %d and %d is ", num1, num2);

    while(num1 != num2)
    {
        if(num1 > num2)
        {
            num1 = num1 - num2;
        }
        else
        {
            num2 = num2 - num1;
        }
    }

    printf("%d.\n", num1);

    return 0;
}

Output 1:
Enter 2 positive integer numbers
20
30

Greatest Common Divisor of 20 and 30 is 10.

Output 2:
Enter 2 positive integer numbers
1980
1617

Greatest Common Divisor of 1980 and 1617 is 33.

Logic To Find GCD using Repeated Subtraction

Lets assume that num1 = 15 and num2 = 20. Lets calculate GCD for these 2 numbers.

While loop iterates until num1 is equal to num2.

num1num2Greater NoSubtract NumbersResult
1520num2 = 20num2 =
num2 – num1
num2:
20 – 15 = 5
155num1 = 15num1 =
num1 – num2
num1:
15- 5 = 10
105num1 = 10num1 =
num1 – num2
num1:
10- 5 = 5
55Both Are Equalnum1 == num2GCD is 5.

You can see below code in the C program i.e., converting a negative number into positive. Our source code above works only for positive integer numbers without this code. If the user enters negative value we use ternary operator to make it a positive value.

    num1 = (num1 < 0) ? -num1 : num1;  
    num2 = (num2 < 0) ? -num2 : num2;  

Here we check if num1 is less than 0. If true, then value of num1 is negative. So we multiply the number by -, which gives us a positive number. For example, if num1 is -15, then -(-15) is +15.

Ternary Operator / Conditional Operator In C

You can make use of simple if else statement like below, to convert negative number into positive:

#include<stdio.h>
if(num1 < 0)
   num1 = num1 * -1;

if(num2 < 0)
   num2 = num2 * -1;

That would convert a negative number to positive number.

While Loop
While loop iterates until num1 is not equal to num2. Once num1 is equal to num2, control exits while loop. Whatever is present in num1 or num2 is the GCD of 2 positive integer numbers entered by the user.

Inside while loop, we check if num1 is greater than num2. If true, we subtract num2 from num1 and store it back inside variable num1. Else if num2 is greater than num1, then we subtract num1 from num2 and store it back inside num2. We repeat this until num1 is equal to num2.

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 Convert Year To Roman Equivalent

Write a general-purpose function to convert any given year into its Roman equivalent. Use these Roman equivalents for decimal numbers:

1 – i, 5 – v, 10 – x, 50 – l, 100 – c, 500 – d, 1000 – m.

Example:
Roman equivalent of 1988 is mdcccclxxxviii.
Roman equivalent of 1525 is mdxxv.

Related Read:
while loop in C programming
else if statement in C
Function / Methods In C Programming Language

Chart for Roman equivalents of decimal numbers

DecimalRoman Equivalent
1000m
500d
100c
50l
10x
5v
1i

Video Tutorial: C Program To Convert Year To Roman Equivalent


[youtube https://www.youtube.com/watch?v=oocEj-8u4o8]

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

Spurce Code: C Program To Convert Year To Roman Equivalent

#include<stdio.h>

void roman(int num)
{
    while(num)
    {
        if(num >= 1000)
        {
            printf("m");
            num = num - 1000;
        }
        else if(num >= 500)
        {
            printf("d");
            num = num - 500;
        }
        else if(num >= 100)
        {
            printf("c");
            num = num - 100;
        }
        else if(num >= 50)
        {
            printf("l");
            num = num - 50;
        }
        else if(num >= 10)
        {
            printf("x");
            num = num - 10;
        }
        else if(num >= 5)
        {
            printf("v");
            num = num - 5;
        }
        else if(num >= 1)
        {
            printf("i");
            num = num - 1;
        }
    }

    printf("\n");
}

int main()
{
    int year;

    printf("Input the year to get its Roman Equivalent\n");
    scanf("%d", &year);

    roman(year);

    return 0;
}

Output 1:
Input the year to get its Roman Equivalent
1988
mdcccclxxxviii

Output 2:
Input the year to get its Roman Equivalent
1525
mdxxv

Output 3:
Input the year to get its Roman Equivalent
2500
mmd

Output 4:
Input the year to get its Roman Equivalent
2020
mmxx

Output 5:
Input the year to get its Roman Equivalent
2021
mmxxi

Logic To Convert Year To Roman Equivalent

We ask the user to enter the year in decimal number format and store it inside variable year. Next we pass this user input year to function roman.

Inside function roman, we copy the value of year to a local variable num. We write a while loop and iterate until value of num is positive. Control exits while loop once num is equal to 0.

Inside while loop we check if the value of num is greater than or equal to 1000. If true, then we print roman equivalent of 1000, which is m. And then we decrement the value of num by 1000.

For each iteration of the while loop we check if num is greater than or equal to 1000 or 500 or 100 or 50 or 10 or 5 or 1. To whichever number the value of num matches we printout its corresponding representation in roman:

i.e., 1 – i, 5 – v, 10 – x, 50 – l, 100 – c, 500 – d, 1000 – m.

and also immediately decrement the value by its matched decimal equivalent. We keep doing this until num value is 0.

Example:

If user input year is 1525

IterationnumMatchRoman EquivalentNew Value of num
115251000m525
2525500d25
32510x15
41510x5
555v0

In above table, last value of num is 0, so control exits while loop. So roman equivalent of year 1525 is mdxxv.

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 Sum of Series 1/1! + 2/2! + 3/3! + …. + n/n!

Lets write a C program to add first seven terms of the following series 1 / 1! + 2 / 2! + 3 / 3! + ….. + 7 / 7!

We’ve also written the C program to ask the user to enter the number of terms of the series that has to be added. You can find code to both of it below.

Related Read:
For Loop In C Programming Language
while loop in C programming
C Program To Find Factorial of a Number using For Loop

C Program To Find Sum of Series 1/1! + 2/2! + 3/3! + …. + n/n!


[youtube https://www.youtube.com/watch?v=Nok-OqhKpDY]

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


Source Code: C Program To Find Sum of Series 1/1! + 2/2! + 3/3! + …. + 7/7!

 

int main()
{
    int num = 1, count;
    float sum = 0.0, fact;

    while(num <= 7)
    {
        fact = 1;
        for(count = 1; count <= num; count++)
        {
            fact = fact * count;
        }

        sum = sum + (num / fact);

        num++;
    }

    printf("Sum of series is %f\n", sum);

    return 0;
}

Output:
Sum of series is 2.718056

In above code, while loop iterates from 1 to 7. For each iteration for loop calculates the factorial of the selected number – which is present in variable num. Outside for loop, we add the individual series elements. At the end of while loop execution, variable sum will have sum of 7 terms of the series.

Source Code: C Program To Find Sum of Series 1/1! + 2/2! + 3/3! + …. + n/n!

 

int main()
{
    int num = 1, count, limit;
    float sum = 0.0, fact;

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

    while(num <= limit)
    {
        fact = 1;
        for(count = 1; count <= num; count++)
        {
            fact = fact * count;
        }

        sum = sum + (num / fact);

        num++;
    }

    printf("Sum of %d terms of series is %f\n", limit, sum);

    return 0;
}

Output 1:
Enter the number of terms
7
Sum of 7 terms of series is 2.718056

Output 2:
Enter the number of terms
8
Sum of 8 terms of series is 2.718254

In above code, we ask the user to enter the number of terms in the series that needs to be added. While loop iterates until the user entered number of times. Inside for loop we calculate the factorial of the selected number(number is selected by while loop and it’ll be present in variable num). Outside the for loop we add the individual series element. At the end of execution of while loop we’ll have sum of the series until user entered number of terms in the series.

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