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

Comparing Floating Point Variable With a Value In C Programming

In this video tutorial lets see how we can compare a floating point variable with a constant value, and lets see the result.

Related Read:
Sizeof Operator in C Programming Language
C Program To Convert Decimal Number To Binary Number, using While Loop

The Problem

If you assign 0.7 to a floating point variable num and then inside if condition you check if num == 0.7, it returns false. Because here variable num is of data type float and the constant value 0.7 is considered as double type data.

Comparison

Video Tutorial: Comparing Floating Point Variable With a Value In C Programming


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

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

Source Code: Comparing Floating Point Variable With a Value In C Programming

#include<stdio.h>

int main()
{
    float num = 0.7;

    if(num == 0.7)
        printf("Yes, true\n");
    else
        printf("Not True\n");

    return 0;
}

Output:
Not True

Some of you might get surprised with the result. But there is nothing to be surprised. It’s working the way it is intended to work.

Reason

We need to keep the basics in mind. When we input decimal numbers, it gets converted into Binary number system and then the further calculation occurs.

Now getting back to our problem: value present in floating point variable num is converted to its binary equivalent. But float has 4 bytes of memory storage.

#include<stdio.h>

int main()
{
    float num = 0.7;

    printf("%d\n", sizeof(num));
    printf("%d\n", sizeof(0.7));

    return 0;
}

Output:
4
8

Next the constant value 0.7 is converted into its binary equivalent. Since its data type is double, it has 8 Bytes of memory for storage. Hence it can store higher precision number.

Now the comparison between these two binary number occurs. Inside double, the binary number has more precision compared to floating point variable – due to available memory for each data type.

For Example:

#include<stdio.h>
int main()
{
    float PI = 3.14;
    double M_PI = 3.14159265358979323846;

    if(PI == M_PI)
        printf("YES\n");
    else
        printf("NO\n");

    return 0;
}

Output:
NO

Even though both variable PI and M_PI has value of PI in it, they’re not equal.

Quick Fix

There are 2 quick fixes for this bug:

1. Typecast constant value to float.
2. Declare double type variable instead of floating point variable.

1. Typecast constant value to float.

#include<stdio.h>
int main()
{
    float num = 0.7;

    if(num == 0.7f)
        printf("Yes, true\n");
    else
        printf("Not True\n");

    return 0;
}

Output:
Yes, true

Inside if condition, we’ve converted double value 0.7 into floating point data, by appending f to it.

2. Declare double type variable instead of floating point variable.

#include<stdio.h>

int main()
{
    double num = 0.7;

    if(num == 0.7)
        printf("Yes, true\n");
    else
        printf("Not True\n");

    return 0;
}

Output:
Yes, true

Best Example:

We had written a C program to Find Grade of Steel. One of our reader reported this comparison bug, and we fixed it using above method mentioned in this video.

Purposefully we’ve not altered the old code. We’ve preserved both old and new code, so that people can learn from our mistake. Take a look at: C Program To Find Grade of Steel

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 Size of Pointer Variables

Lets write a C program to find out the size or the number of bytes occupied by pointer variables of different data type in your computers memory.

Related Read:
Sizeof Operator in C Programming Language
Basics of Pointers In C Programming Language

Video Tutorial: C Program To Find Size of Pointer Variables


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

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


Source Code: C Program To Find Size of Pointer Variables

#include<stdio.h>

int main()
{
    printf("Size of int pointer = %d bytes.\n", sizeof(int*));
    printf("Size of char pointer = %d bytes.\n", sizeof(char*));
    printf("Size of float pointer = %d bytes.\n", sizeof(float*));
    printf("Size of double pointer = %d bytes.\n", sizeof(double*));
    printf("Size of long int pointer = %d bytes.\n", sizeof(long*));
    printf("Size of short int pointer = %d bytes.\n", sizeof(short*));

    return 0;
}

Output:
Size of int pointer = 4 bytes.
Size of char pointer = 4 bytes.
Size of float pointer = 4 bytes.
Size of double pointer = 4 bytes.
Size of long int pointer = 4 bytes.
Size of short int pointer = 4 bytes.

If you observe the output of above C program you can see that pointer variables, irrespective of their data type, consume 4 bytes of data in the memory.

Note: “But the number of bytes allocated for different data types and pointer variables are machine dependent. 16-bit, 32-bit, 64-bit computers allocate different bytes of memory. But pointer variables of any data type will always have same number of bytes occupied in the memory. For Example, if the computer allocates 2 bytes for pointer variable, then all the pointer variables, irrespective of their data type, will occupy 2 bytes in the memory.”

A pointer variable of type float holds only the address of floating point variable. A char pointer variable holds only the address of char type variable. But still the address of all these type of pointer variable is number. Addresses are always numbers and it can’t be a character, a string or real/floating/double numbers.

Also note that addresses are unique. There can’t be 2 location in your computers memory with same address.

Note: Observe that I’m using %d as format specifier while printing the size of data type, that’s because sizeof() function/method returns integer type data i.e., number of bytes occupied in the computers memory.

Note: sizeof() method takes a single argument and it is not a function whose value is determined at run time, but rather an operator whose value is determined by compiler – so it’s called as compile time unary operator.

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

Basics of Pointers In C Programming Language

In today’s video tutorial lets learn basics of pointers in C programming language. Think of it as base of a building. If you can hold these basic concepts strong your building will be safer.

Topics Covered

1. What are pointers?
2. How to declare pointers.
3. How to access the value present at the address stored in pointer variable.
4. Using Address of operator.
5. Using Indirection operator.

What are pointers?

A pointer is a variable which refers to or points to an address in your computers memory.

Definition: A pointer variable is a variable which holds the address of another variable.

And since pointer variable is also a variable, it also has a unique address associated with it.

Operators

& is called “address of” operator.
* is called Indirection or “value at address” operator.

Video Tutorial: Basics of Pointers In C Programming Language


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

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


Source Code: Basics of Pointers In C Programming Language

#include<stdio.h>

int main()
{
    int num = 5;
    int *ptr; // pointer variable

    ptr = &num; // both hold address of num

    printf("Value of num = %d\n", num);
    printf("Address of num = %d\n", &num);
    printf("Address of ptr = %d\n", &ptr);
    printf("Value of ptr = %d\n", ptr);
    printf("Access value of num from ptr = %d\n", *ptr);
    printf("Access value of num from num = %d\n", *(&num));

    return 0;
}

Output:
Value of num = 5
Address of num = 6356732
Address of ptr = 6356728
Value of ptr = 6356732
Access value of num from ptr = 5
Access value of num from num = 5

Note: Whenever you declare and initialize a variable, for example, int num = 5; Your program does the following tasks:
1. Reserves space in your computers memory depending upon the data type.
2. Associates the name num with this memory location.
3. Stores the number 5 in this memory location.

Declaration of pointer variable

General Syntax
data_type* pointer_variable_name;

OR

data_type *pointer_variable_name;

Example:

int *ptr1;

int* ptr2;

Both these declaration are valid.

Rules for constructing pointer variable are same as that of regular variables: Rules for Constructing Variable Names: C

Assigning value to pointer variable

General Syntax
pointer_variable_name = &another_variable;

Example:

ptr = &num;

This stores the address of variable num as value of pointer variable ptr.

Declaring and Assigning value to pointer variable

Example:

int num = 5;
int *ptr;  // Declaration of pointer variable

ptr = &num;  // Assigning value to pointer variable

Note: While assigning address to pointer variable do not include * in front of pointer variable.

Values and addresses

num will have 5.
&num will have address of num.
&ptr will have address of ptr.
ptr will have address of num.
*ptr will have value of num.

Call by Value and Call by reference

Call by Value Example: C Program To Swap Two Numbers using Function
Call by Reference Example: C Program To Swap Two Numbers using Pointers

Note: Address can’t be negative values. So we can use %u as format specifier, which means unsigned integer.

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

Rules for Constructing Variable Names: C

Rules for constructing variable names are same for all the data types.

Related Read:
Rules for Constructing int, float, char constants: C

Rules for Constructing Variable Names: C


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

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


Rules for constructing variable names

1. First character in a variable name must be an alphabet or an underscore( _ ).

2. Variable name can have alphabet, digits and underscore.

3. No commas, space allowed in variable name.

4. No other special symbols other than underscore is allowed.

5. C variables are case sensitive. Ex: name and Name are two different variables.

6. You can not use keywords / reserve words as variable name in C.

Valid Variable Names
_name
user_name
age20
iMac

Invalid Variable Names
9hundred
Micro soft
Apple$computers

Note: All these rules for constructing variable names apply for all the data types in C.