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

Calculate Sum and Average of N Numbers using Arrays: C Program

Lets write a C program to calculate Sum and Average of N numbers using Arrays and using macros and for loop.

Related Read:
Calculate Sum and Average of N Numbers without using Arrays: C Program

Formula To Calculate Sum and Average

int a[5] = {2, 4, 6, 5, 9};

sum = 2 + 4 + 6 + 5 + 9;
average = sum / 5.0;

Result
sum = 26;
average = 5.2;

Important Note:
Look at the formula for calculating average. If you divide any number by integer number, it’ll only return integer value and discard the digits after decimal point. So make sure to divide the number by floating point value. To convert integer to float, make use of typecasting syntax.

Typecasting

int N = 5;

sum = 2 + 4 + 6 + 5 + 9;
average = sum / (float)N;

Since N is integer type variable, dividing any number by N would give us integer data. For some input it’ll result in wrong result. To fix it, we make use of typecasting and cast the type of N to float using above syntax.

Example: Expected Output

Enter 5 integer numbers
5
2
6
4
3

Sum of 5 numbers: 20

Average of 5 numbers: 4.000000

array with size 5

Video Tutorial: Calculate Sum and Average of N Numbers using Arrays: C Program


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

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

Source Code: Calculate Sum and Average of N Numbers using Arrays: C Program

Method 1

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, sum = 0;
    float avg;

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

    for(i = 0; i < N; i++)
    {
        sum = sum + a[i];
    }

    avg = sum / (float)N;

    printf("\nSum of %d numbers: %d\n", N, sum);
    printf("\nAverage of %d numbers: %f\n", N, avg);

    return 0;
}

Output 1:
Enter 5 integer numbers
2
5
6
8
10

Sum of 5 numbers: 31

Average of 5 numbers: 6.200000

Output 2:
Enter 5 integer numbers
1
2
3
4
5

Sum of 5 numbers: 15

Average of 5 numbers: 3.000000

Logic To Calculate Sum and Average of Array Elements

We ask the user to input N integer numbers. N is a macro and we’ve assigned 5 to it. Integer numbers input by the user is stored inside array variable a[N]. N being the size of the array.

SUM
We use for loop and iterate N times to fetch all the array elements. Variable i is assign a initial value of 0 and for loop iterates until i < N. Inside for loop we add the value of individual array element(a[i]) to previous value of variable sum. Once i < N condition is false, control exits for loop.

AVERAGE
Outside for loop we calculate average by using the formula:
average = sum / (float)N;

Once sum and average are calculated we output the result on to the console window.

Source Code: Calculate Sum and Average of N Numbers using Arrays: C Program

Method 2: Improved Source Code

#include<stdio.h>

#define N 5

int main()
{
    int a[N], i, sum = 0;
    float avg;

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

    avg = sum / (float)N;

    printf("\nSum of %d numbers: %d\n", N, sum);
    printf("\nAverage of %d numbers: %f\n", N, avg);

    return 0;
}

You could even calculate sum inside the for loop which is used to accept input from the user. Whenever user inputs a number it is immediately added to the previous value of variable sum.

Advantages of using above source code
We don’t iterate through the array to fetch individual elements of the array and then add it to calculate sum. We calculate sum inside first for loop itself which is used to accept input by user. This method is faster and cheaper on resource usage.

Important Notes:

1. Make use of macros to assign size of array.
2. Make sure to declare variable avg(to calculate average) as float or double.
3. Make sure to divide variable sum by floating point or double type value and not by integer. In order to convert a integer variable or macro, make use of typecasting.

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 Function

Lets write a C program to print the multiplication table for a user input number, using function/method. The table should get displayed in the following format:

Example: Multiplication table of 5
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

Coding Challenge on Numbers!
Print the multiplication table which gives the following output:

multiplication table for number 37

Hint: Initialize count to 3. Increment the value of count by 3 for each iteration of for loop.

Answer: We’ve posted the source code to above coding challenge at the end of this blog post.

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

Video Tutorial: C Program To Print Multiplication Table Using Function


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

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


Source Code: C Program To Print Multiplication Table Using Function

#include<stdio.h>

void tables(int);

int main()
{
    int num;

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

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

    tables(num);

    return 0;
}

void tables(int num)
{
    int count;

    for(count = 1; count <= 10; count++)
    {
        printf("%d x %d = %d\n", num, count, num*count);
    }
}

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
2

Multiplication Table for 2 is:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

Output 3:
Enter a positive number
7

Multiplication Table for 7 is:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

Output 4:
Enter a positive number
9

Multiplication Table for 9 is:
9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90

Logic: Multiplication Table

User enters a positive number, we store it inside variable num. We pass this number entered by the user to a function called tables().

Inside tables() function we write a for loop. We initialize the for loop counter variable count to 1 and iterate through this for loop until count is less than or equal to 10 – because we want to display multiplication tables from 1 to 10. For each iteration of for loop we increment the value of count by 1.

Inside for loop we display the multiplication table.

You can also watch C Program To Print Multiplication Table Using While Loop video tutorial.

Just For Some Number Fun

Here I’m initializing 3 to count variable. For loop executes until count is less than or equal to 27. For each iteration of for loop count value increments by 3.

We assign 37 to num variable. Check the output.

Source Code: Some numerology!

#include<stdio.h>

void tables(int);

int main()
{
    int num = 37;

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

    tables(num);

    return 0;
}

void tables(int num)
{
    int count;

    for(count = 3; count <= 27; count += 3)
    {
        printf("%d x %d = %d\n", num, count, num*count);
    }
}

Output:
Multiplication Table for 37 is:

37 x 3 = 111
37 x 6 = 222
37 x 9 = 333
37 x 12 = 444
37 x 15 = 555
37 x 18 = 666
37 x 21 = 777
37 x 24 = 888
37 x 27 = 999

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 Count Prime Numbers Between Range

Lets write a C program to count prime numbers between user entered/input range of numbers, using function/method.

Prime Number: is a natural number greater than 1, which has no positive divisors other than 1 and itself.

Related Read:
C Program To Find Prime Number or Not using For Loop

Video Tutorial: C Program To Count Prime Numbers Between Range


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

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

Source Code: C Program To Count Prime Numbers Between Range

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

int isPrime(int num)
{
    int inum = sqrt(num), prime = 1, count;

    for(count = 2; count <= inum; count++)
    {
         if(num % count == 0)
         {
            prime = 0;
            break;
         }
    }

    return(prime);
}

int main()
{
    int start, end, temp, num, slno = 0, on_off;

    printf("Enter start and end value\n");
    scanf("%d%d", &start, &end);

    printf("Do you want to print prime numbers? (yes = 1, no = 0)\n");
    scanf("%d", &on_off);

    if(start > end)
    {
        temp  = start;
        start = end;
        end   = temp;
    }

    if(on_off)
        printf("\nPrime numbers between %d and %d are:\n\n", start, end);

    for(num = start; num <= end; num++)
    {
        if(num == 1)
        {
            continue;
        }

        if( isPrime(num) )
        {
            slno++;

            if(on_off)
            {
                printf("%d. %d is prime number.\n", slno, num);
            }
         }
    }

    printf("\nThere are %d prime numbers between %d and %d.\n", 
             slno, start, end);

    return 0;
}

Output 1:
Enter start and end value
10
30
Do you want to print prime numbers? (yes = 1, no = 0)
1

Prime numbers between 10 and 30 are:

1. 11 is prime number.
2. 13 is prime number.
3. 17 is prime number.
4. 19 is prime number.
5. 23 is prime number.
6. 29 is prime number.

There are 6 prime numbers between 10 and 30.

Output 2:
Enter start and end value
10
30
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 6 prime numbers between 10 and 30.

Output 3:
Enter start and end value
1
10
Do you want to print prime numbers? (yes = 1, no = 0)
1

Prime numbers between 1 and 10 are:

1. 2 is prime number.
2. 3 is prime number.
3. 5 is prime number.
4. 7 is prime number.

There are 4 prime numbers between 1 and 10.

Output 4:
Enter start and end value
1
300
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 62 prime numbers between 1 and 300.

Output 5:
Enter start and end value
1
1000
Do you want to print prime numbers? (yes = 1, no = 0)
0

There are 168 prime numbers between 1 and 1000.

Logic To Count Prime Numbers Between Range

First we ask the user to enter the range and store it inside address of variables start and end. We make sure that start value is less than end value. If start value is greater than end value, we use a temporary variable to swap the values of start and end.

Swap 2 Numbers Using a Temporary Variable: C

Next we ask the user if he / she wants to display the prime numbers between the range or just want to know the count of prime numbers between the entered range. We store the user answer in a variable called on_off.

We start the for loop: We initialize the loop counter variable num to start and iterate through the loop until num is less than or equal to end. For each iteration of the for loop we increment the value of num by 1. This for loop selects number one by one from start to end. And this selected number, which is present inside variable num is checked for prime or not. If its prime we display it to the console window and keep track of the count of prime numbers, if not we simply ignore that non-prime number.

We use a function to check if the selected number present in variable num is a prime number or not. We call the function/method isPrime() inside if condition and pass the value of num to it. isPrime() returns 1 or 0 value. 1 means true and 0 means false. So if isPrime() returns 1, then the if condition becomes true and we increment the value of slno by 1 and optionally printout the prime number. If isPrime() returns 0, then we simply ignore it and go to the next number.

isPrime() function has the logic to determine if the given number is prime or not. We have explained the complete logic of this in a separate video tutorial, link to which is present below.

C Program To Find Prime Number or Not using For Loop

Note:
1. We are including math.h header file or library file since we are using sqrt() builtin method. sqrt() method is present inside math.h file.

2. We are also using continue and break keywords in our program and we’ve explained about it in detail in separate videos. Please watch them for more clarity about the topic.

Continue Statement In C Programming Language
break Statement In C Programming Language

Stay subscribed to our blog and YouTube channel. Thank you ..

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 Express A Number as Sum of Two Prime Numbers

Lets write a C program to check whether a user input/entered positive number can be expressed as sum of two prime numbers or not.

Related Read:
C Program To Find Prime Number or Not using While Loop

Prime Number: Any natural number which is greater than 1 and has only two factors i.e., 1 and the number itself is called a prime number.

Note: The user entered number need not be a prime number. But the 2 numbers, sum of which is equal to the original number, must be prime numbers.

For example, if user enters num as 14. Number 14 is not a prime number. We get following result:

3 + 11 = 14
7 + 7 = 14

Numbers 3, 11 and 7 are prime numbers.

Example:

If user enters num = 14;

First Iteration
num = 14;
count = 2; // First prime number in the series

(num-count) => (14-2) = 12;

count + (num-count) = num
2 + 12 = 14.

But 12 is not a prime number. So we discard this 2 + 12 = 14.

Second Iteration
num = 14;
count = 3; // Next Prime Number in the series

(num-count) => (14-3) = 11;

count + (num-count) = num
3 + 11 = 14.

Both 3 and 11 are prime numbers. So we display 3 + 11 = 14.

Third Iteration
num = 14;
count = 5; // Next Prime Number in the series

(num-count) => (14-5) = 9;

count + (num-count) = num
5 + 9 = 14.

But 9 is not a prime number. So we discard this 5 + 9 = 14.

Forth Iteration
num = 14;
count = 7; // Next Prime Number in the series

(num-count) => (14-7) = 7;

count + (num-count) = num
7 + 7 = 14.

Number 7 is a prime numbers. So we display 7 + 7 = 14.

Fifth Iteration
num = 14;
count = 11; // Next Prime Number in the series

(num-count) => (14-11) = 3;

count + (num-count) = num
11 + 3 = 14.

Both 11 and 3 are prime numbers. But we’ve already displayed 3 + 11 = 14 in second iteration. So we do not display it again.

Condition to exit for loop
The condition to exit for loop is: when count is less than or equal to (num – count);

In above case, in fifth iteration: count value is 11. And (num-count) is 3. So 11 <= 3 returns false. So control exits for loop.

Video Tutorial: C Program To Express A Number as Sum of Two Prime Numbers


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

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


Source Code: C Program To Express A Number as Sum of Two Prime Numbers

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

int nxtPrime(int);
int isPrime(int);

int main()
{
    int num, count, flag = 0;

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

    for(count = 2; count <=(num-count); count = nxtPrime(count))
    {
        if(isPrime(num-count))
        {
            flag = 1;
            printf("%d + %d = %d\n", count, num-count, num);
        }
    }

    if(flag == 0)
    {
        printf("%d cannot be expressed as the sum of 2 prime numbers.\n", num);
    }


    return 0;
}

int nxtPrime(int num)
{
    do
    {
        num++;
    }while(!isPrime(num));

    return(num);
}

int isPrime(int num)
{
    int count, inum, prime = 1;

    inum = sqrt(num);

    for(count = 2; count <= inum; count++)
    {
        if(num % count == 0)
        {
            prime = 0;
            break;
        }
    }

    return(prime);
}

Output 1:
Enter a positive number
14
3 + 11 = 14
7 + 7 = 14

Output 2:
Enter a positive number
5
2 + 3 = 5

Output 3:
Enter a positive number
24
5 + 19 = 24
7 + 17 = 24
11 + 13 = 24

Output 4:
Enter a positive number
34
3 + 31 = 34
5 + 29 = 34
11 + 23 = 34
17 + 17 = 34

Output 5:
Enter a positive number
41
41 cannot be expressed as the sum of 2 prime numbers.

Note: Function nxtPrime() and isPrime() returns integer type data so its return type is int. And both these methods / functions accepts 1 integer type argument.

Logic To Express A Number as Sum of Two Prime Numbers

1. We ask the user to enter a positive number and store it inside variable num. Now we write the for loop. We initialize the loop counter variable count to 2 – because 2 is the first number in prime number series. We iterate through the for loop until count is less than or equal to (num-count). For each iteration of for loop we change the value of count to next prime number in the prime number series.

We use following simple expression to find and printout the result:
count + (num – count) = num;

We already know that value of count is prime number. Next inside for loop we check the second part of above expression i.e., (num-count) for prime number or not. If both count and (num-count) are prime numbers, then we output the values, if not, then we change the value of count to next prime number and check if (num-count) is prime or not. We continue doing this until count is less than or equal to (num-count);

2. We need to get next prime number for loop count variable count. So we need to define (write logic for) nxtPrime() method.

int nxtPrime(int num)
{
    do
    {
        num++;
    }while(!isPrime(num));

    return(num);
}

value of count is passed to nxtPrime() method, which is copied to local variable num. First we increment the value of num inside do block and then check the condition in while. If the number is prime then we exit the do-while loop and return the number orelse we keep incrementing the value of num and check if the new number is prime or not, by passing it to the function isPrime().

Table of all prime numbers up to 1,000:
prime numbers from 1 to 1000

3. Next we write the logic to check if the number is prime or not. We’ve already explained the complete logic in a separate video tutorial present at C Program To Find Prime Number or Not using While Loop.

int isPrime(int num)
{
    int count, inum, prime = 1;

    inum = sqrt(num);

    for(count = 2; count <= inum; count++)
    {
        if(num % count == 0)
        {
            prime = 0;
            break;
        }
    }

    return(prime);
}

This is the beauty of function. We call the function isPrime() 2 times. Once from main() function and once from nxtPrime() function. This avoids repeating our code. We write the code once in our function and call it any number of times in the program. This is called DRY concept in programming i.e., Do Not Repeat Yourself.

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