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 Count Each Digit In A Number using Arrays

Lets write a C program to count repetition of each digit in a positive integer number using array.

Related Read:
C Program To Check Repetition of Digit In A Number using Arrays

Example: Expected Output

Enter a positive number
11201

0 has appeared 1 times.
1 has appeared 3 times.
2 has appeared 1 times.

Digit Count Using Array

Video Tutorial: C Program To Count Each Digit In A Number using Arrays


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

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

Source Code: C Program To Count Each Digit In A Number using Arrays

Method 1

#include<stdio.h>

int main()
{
    int a[10] = {0}, num, rem, i;

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

    while(num)
    {
        rem = num % 10;
        a[rem] = a[rem] + 1;
        num = num / 10;
    }

    printf("\n");

    for(i = 0; i < 10; i++)
    {
        if(a[i] != 0)
            printf("%d has appeared %d times.\n", i, a[i]);
    }

    return 0;
}

Output 1:
Enter a positive number
1105135

0 has appeared 1 times.
1 has appeared 3 times.
3 has appeared 1 times.
5 has appeared 2 times.

Output 2:
Enter a positive number
12345

1 has appeared 1 times.
2 has appeared 1 times.
3 has appeared 1 times.
4 has appeared 1 times.
5 has appeared 1 times.

Logic To Count Each Digit In A Number

We ask the user to enter a positive integer number. We then fetch individual digits from the number using while loop.

Important Note:
1. Initially all the array elements are initialized to zero.
2. We take array size as 10. Because we need to accommodate 10 digits i.e., 0 to 9. Using digits 0 to 9 we could formulate any positive integer number.

Array with zeros initialized

Inside While loop
While loop keeps executing until num is 0. Once num is 0, control exits while loop. First we fetch the last digit of the user input number by modulo dividing it by 10, and store it inside variable rem. Next we use this rem value as index of array variable a. i.e., a[rem] and add 1 to the previous value of a[rem]. Next we reduce the user input number by 1 digit from the end by dividing the number by 10. i.e., num = num / 10. This line of code shifts the decimal point from right to left by 1 place. But since num is integer variable and 10 is also integer(by which we divide user input number), we only get the integer part of the number and the number after decimal point gets discarded.

Printing / Displaying The Result or The Count
We iterate through the entire array and display the non-zero values along with the index number. Index number is nothing but the individual digits of the user input number.

Explanation With Example

If num = 112021;
So individual digits are 1, 1, 2, 0, 2, 1

    while(num)
    {
        rem = num % 10;
        a[rem] = a[rem] + 1;
        num = num / 10;
    }
num = num / 10rem = num % 10a[rem] = a[rem] + 1
1120211a[1] = 1
112022a[2] = 1
11200a[0] = 1
1122a[2] = 2
111a[1] = 2
11a[1] = 3
0

When the control exits while loop (once num is 0), a[0] has value 1, a[1] has value 3, a[2] has value 2. That simply means, digit 0 has appeared 1 time in the user input number. Digit 1 has appeared 3 times in the user input number. Digit 2 has appeared 2 times in the user input number.

Source Code: C Program To Count Each Digit In A Number using Arrays

Another method: Method 2

#include<stdio.h>

int main()
{
    int a[10] = {0}, num, rem, temp;

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

    temp = num;

    while(num)
    {
        rem = num % 10;
        a[rem] = a[rem] + 1;
        num = num / 10;
    }

    printf("\n");

    while(temp)
    {
        rem = temp % 10;

        if(a[rem] != 0)
            printf("%d appeared %d time.\n", rem, a[rem]);

        a[rem] = 0;
        temp = temp / 10;
    }

    return 0;
}

Output 1:
Enter a positive number
11253001

0 has appeared 2 times.
1 has appeared 3 times.
2 has appeared 1 times.
3 has appeared 1 times.
5 has appeared 1 times.

Output 2:
Enter a positive number
112021

0 has appeared 1 times.
1 has appeared 3 times.
2 has appeared 2 times.

Logic To Count Each Digit In A Number: Method 2

Here the program is same except the displaying part logic.

    while(temp)
    {
        rem = temp % 10;

        if(a[rem] != 0)
            printf("%d appeared %d time.\n", rem, a[rem]);

        a[rem] = 0;
        temp = temp / 10;
    }

variable temp has user input number. Here we fetch individual digit of the user input number, and if it is non-zero, then we print whatever value is present at that index. Once we print the value, we over-write the value at that index by 0. Next we reduce the number by one digit from left/end by dividing the number by 10.

This way we only iterate through the while loop by limited number of times. i.e., The number of iteration is equal to the number of unique digits the user input number has.

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 Check Repetition of Digit In A Number using Arrays

Lets write a C program to check if any digit in a user input number appears more than once.

Note: Any positive integer number can be formed using only 0-9 digits. So we take an array with length 10. i.e., 0 to 9

array of size 10

Video Tutorial: C Program To Check Repetition of Digit In A Number using Arrays


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

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

Source Code: C Program To Check Repetition of Digit In A Number using Arrays

#include<stdio.h>

int main()
{
    int a[10] = {0}, num, rem;

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

    while(num)
    {
        rem = num % 10;

        if(a[rem] == 1)
            break;
        else
            a[rem] = 1;

        num = num / 10;
    }

    if(num)
        printf("There are repetition of digits in the number\n");
    else
        printf("There are no repetition of digits in the number\n");

    return 0;
}

Output 1:
Enter a positive number
123
There are no repetition of digits in the number

array of size 10

Output 2:
Enter a positive number
156
There are no repetition of digits in the number

array of size 10

Output 3:
Enter a positive number
1232
There are repetition of digits in the number

Logic To Check if any digit in user input number repeats or not

1. Since there are 10 digits i.e., 0 to 9 to form any number, we take array size as 10. We initialize all the elements of array to 0.

Related Read:
Basics of Arrays: C Program

2. We ask the user to input a positive number.

3. We iterate through the while loop until num is zero.

Related Read:
while loop in C programming

4. By modulo dividing user input number by 10, we fetch individual digits of number. We make use of this individual digit as index of the array. We over-write the initial value(which is zero) and assign 1 at that index position.

So presence of value 1 at an index specifies that the digit already exists in the number.

Related Read:
Modulus or Modulo Division In C Programming Language

5. So based on the presence of value 1 or 0 at particular index, our program decides if the digit is present more than once in a number or not.

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

Size of Array using Macro and Constant: C Program

In this video tutorial lets see how we can assign size of an array using macros and constants.

Related Read:
For Loop In C Programming Language
Introduction To Arrays: C Programming Language
Keywords, Constants, Variables: C

Disadvantage of Not Using Macro or Constant To Assign Array Size

If requirement of the program/software changes and you need to increase or decrease the array size, then you’ll have to be very careful and scan through the entire source code and make changes at multiple locations. Even if you skip changing the array size information at one place, you’ll start getting wrong results.

And if you have any business logic which makes use of array size, then you’ll have hard time rectifying and debugging the code. It’ll take unnecessary time and effort to make it work correctly once again.

By making use of Macros or constant variables you can handle this very efficiently. You can make the change at one place and it’ll take effect at all the places in your source code.

Watch the video below for demonstration of effectiveness of using macros and constants for assigning size of an array.

Video Tutorial: Assign Size of Array using Macro and Constant: C Program


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

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

Source Code: Size of Array using Macro and Constant: C Program

Without using Macros and/or constants

#include<stdio.h>

int main()
{
    int a[5], i;

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

    printf("Array elements are:\n");
    for(i = 0; i < 5; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
4
5
Array elements are:
1
2
3
4
5

Here we have a array variable with size 5. We enter 5 integer variables and we display those elements using for loop. In for loop condition we mention the number of times it has to iterate.

Now assume that the requirement changes and we need to increase the size of array from 5 to 7:

#include<stdio.h>

int main()
{
    int a[7], i;

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

    printf("Array elements are:\n");
    for(i = 0; i < 7; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 7 integer numbers
1
2
3
4
5
6
7
Array elements are:
1
2
3
4
5
6
7

As you can see we made edits at 4 places. Its a very simple program and even in that we had to make 4 edits. What if the program is huge and the requirement changes?

Macros

Assign Array size using Macros

#include<stdio.h>

#define N 5

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

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

    printf("Array elements are:\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
4
5
Array elements are:
1
2
3
4
5

Observe the changes we’ve made in the source code. We’re defining a macro here. Macro template is N and macro expansion is 5. We replace the value 5 inside main method by macro name N.

#include<stdio.h>

#define N 7

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

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

    printf("Array elements are:\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 7 integer numbers
1
2
3
4
5
6
7
Array elements are:
1
2
3
4
5
6
7

Assume that the requirement changes and the client wants a list size of 7. Now instead of editing at multiple places, we only change the macro expansion from 5 to 7, and it starts working as intended.

Constants

Assign Array size using Constants

#include<stdio.h>

int main()
{
    const int N = 5;
    int a[N], i;

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

    printf("Array elements are:\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 5 integer numbers
1
2
3
4
5
Array elements are:
1
2
3
4
5

Observe the changes we’ve made in the source code. We’ve declared and initialized a constant variable N. Constant variable name is N and its value is 5. We replace the value 5 inside main method by constant variable N.

#include<stdio.h>

int main()
{
    const int N = 7;
    int a[N], i;

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

    printf("Array elements are:\n");
    for(i = 0; i < N; i++)
        printf("%d\n", a[i]);

    return 0;
}

Output:
Enter 7 integer numbers
1
2
3
4
5
6
7
Array elements are:
1
2
3
4
5
6
7

Assume that the requirement changes and the client wants a list size of 7. Now instead of editing at multiple places, we only change the value of constant variable N from 5 to 7, and the program works as intended.

Note: It’s always considered best practice to either use macros or constant variables to assign array size. This practice will prove to be very advantageous while writing big programs.

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

Multi-key Indexes and Arrays: MongoDB

We have learnt the basics of multi-key indexes in MongoDB. Lets look at an example to demonstrate the multi-key indexing on arrays.

arrays-multi-key-index-mongodb

foo: database name
name: collection name

Insert a document

1
2
3
4
5
6
7
8
MongoDB shell version: 2.6.1
connecting to: test
 
> use foo
switched to db foo
 
> db.name.insert({a: 1, b: 2, c: 3});
WriteResult({ "nInserted" : 1 })

Here we insert {a: 1, b: 2, c: 3} into “name” collection.

Multi-key Indexes and Arrays: MongoDB


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

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



Basic Cursor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
> db.name.find({a: 1, b: 2})
{ "_id" : ObjectId("53d8982b79142c385cddc607"), "a" : 1, "b" : 2, "c" : 3 }
 
> db.name.find({a: 1, b: 2}).explain()
{
        "cursor" : "BasicCursor",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "server" : "Satish-PC:27017",
        "filterSet" : false
}

We find() the document using fields “a” and “b” and the query/command returns a basic cursor, as we do not have indexing on them.

Related Read: index creation: MongoDB

Lets create index on a and b

1
2
3
4
5
6
7
> db.name.ensureIndex({a: 1, b: 1});
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

Previous there was only 1 index i.e., on “_id” Now there are 2 indexes – “_id” and “{a: 1, b: 1}”

Btree Cursor with multi-key as false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
> db.name.find({a: 1, b: 2}).explain()
{
        "cursor" : "BtreeCursor a_1_b_1",
        "isMultiKey" : false,
        "n" : 1,
        "nscannedObjects" : 1,
        "nscanned" : 1,
        "nscannedObjectsAllPlans" : 1,
        "nscannedAllPlans" : 1,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "a" : [
                        [
                                1,
                                1
                        ]
                ],
                "b" : [
                        [
                                2,
                                2
                        ]
                ]
        },
        "server" : "Satish-PC:27017",
        "filterSet" : false
}

After creating the index on “a” and “b”, chain explain() method on the same command, and it shows you that, now it returns a Btree Cursor.

Lets insert another document

1
2
> db.name.insert({a: [0, 1, 2], b: 2, c: 3});
WriteResult({ "nInserted" : 1 })

Lets insert an array as value to field “a” and scalar values to “b” and “c”.

Btree Cursor with Multi-key true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
> db.name.find({a: 1, b: 2})
{ "_id" : ObjectId("53d8982b79142c385cddc607"), 
  "a" : 1, "b" : 2, "c" : 3 }
{ "_id" : ObjectId("53d8986f79142c385cddc608"), 
  "a" : [ 0, 1, 2 ], "b" : 2, "c": 3 }
 
> db.name.find({a: 1, b: 2}).explain()
{
        "cursor" : "BtreeCursor a_1_b_1",
        "isMultiKey" : true,
        "n" : 2,
        "nscannedObjects" : 2,
        "nscanned" : 2,
        "nscannedObjectsAllPlans" : 2,
        "nscannedAllPlans" : 2,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 0,
        "nChunkSkips" : 0,
        "millis" : 0,
        "indexBounds" : {
                "a" : [
                        [
                                1,
                                1
                        ]
                ],
                "b" : [
                        [
                                2,
                                2
                        ]
                ]
        },
        "server" : "Satish-PC:27017",
        "filterSet" : false
}

Now append explain() method to our command, it shows us that it returns a Btree Cursor and multi-key as true. MongoDB engine need to match every element of the array present in field “a” with the scalar value of field “b”. Hence it uses Multi-Key indexing.

Multi-Key Condition in MongoDB

1
2
3
4
5
6
7
8
9
> db.name.insert({a: [0, 1, 2], b: [3, 4], c: 3});
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 10088,
                "errmsg" : "insertDocument :: caused by :: 10088 cannot 
                            index parallel arrays [b] [a]"
        }
})

It’s difficult to match every combination of the array elements present inside both “a” and “b” fields. If both keys/indexes has its value as an array, then it gets complicated. Thus, mongoDB doesn’t allow both keys to be arrays. Either one of them must be a scalar value.