# C - Exercise 5

C Programming

Share

In this exercise section of the tutorial we will write some C program.

## Write a program in C to take 5 integer values from user and print the average

For this we will create a 1D array lets say, `num` of type int and size 5.

``````/**
* file: avg-1d-array.c
* author: yusuf shakeel
* date: 2011-01-04
* description: average program
*/

#include <stdio.h>
int main(void)
{
//variable
int num[5], i, sum;
float avg;

//user input
printf("Enter 5 integer values: ");
for (i = 0; i < 5; i++) {
scanf("%d", &num[i]);
}

//compute average
sum = 0;
for (i = 0; i < 5; i++) {
sum += num[i];
}
avg = (float) sum / 5;

//output
printf("Average: %f\n", avg);

printf("End of code\n");
return 0;
}
``````

Output

``````Enter 5 integer values: 1 2 3 4 5
Average: 3.000000
End of code
``````

## Write a program in C to take integer marks (0-100) of 3 tests of 4 students and print the highest score of respective student

In the problem we will create a 2D array `marks` of type `int` having 4 rows for the four students and 3 columns for the three tests.

We will also create a 1D array `maxMark` of type `int` and size 4 to store the max mark of the 4 students.

``````/**
* file: 1d-2d-array.c
* author: yusuf shakeel
* date: 2010-12-21
* description: 1d 2d array and max score program
*/

#include <stdio.h>
int main(void)
{
//variable
int
marks[4][3],
maxMark[4],
r, c;

//user input
for(r = 0; r < 4; r++) {
printf("Enter marks of 3 tests of Student #%d: ", (r + 1));
for(c = 0; c < 3; c++) {
scanf("%d", &marks[r][c]);
}
}

//find max mark
for(r = 0; r < 4; r++) {
maxMark[r] = 0;
for(c = 0; c < 3; c++) {
if (marks[r][c] > maxMark[r]) {
maxMark[r] = marks[r][c];
}
}
}

//output
printf("---------- Max Marks ----------\n");
for(r = 0; r < 4; r++) {
printf("Max mark of Student #%d is %d\n", (r + 1), maxMark[r]);
}

printf("End of code\n");
return 0;
}
``````

Output

``````Enter marks of 3 tests of Student #1: 80 90 50
Enter marks of 3 tests of Student #2: 60 70 80
Enter marks of 3 tests of Student #3: 50 80 60
Enter marks of 3 tests of Student #4: 90 70 50
---------- Max Marks ----------
Max mark of Student #1 is 90
Max mark of Student #2 is 80
Max mark of Student #3 is 80
Max mark of Student #4 is 90
End of code
``````

## Write a program in C to find the respective average marks of 3 students in 4 subjects

Given, marks are integer value between 0 to 100.
Marks of Student #1: 90 60 80 60
Marks of Student #2: 89 78 90 88
Marks of Student #3: 90 66 99 87

Try to write this program yourself.

Share