Write a program to find out for a class of students, the number of families with 1, 2, 3, … up to 7 children. Data consists of number of children in each student's family. Design an appropriate format for the output.

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>
#define MAX 50

int main(int argc, char ** argv) {

    int students, data[MAX], children, i, counter = 0;
    printf("Enter number of students: ");
    scanf("%d", &students);
    for(i = 0; i < students; i++) {
        printf("Number of children in student No %d family: ", i+1);
        scanf("%d", &children);
        data[i] = children;
    }

    for (i = 0; i < students; i++){
        if (data[i] >= 1 && data[i] <= 7)
            counter++;
    }

    printf("\nNumber of families with 1, 2, 3,...7 children: %d\n", counter);
    return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Enter number of students: 5
Number of children in student No 1 family: 1
Number of children in student No 2 family: 10
Number of children in student No 3 family: 2
Number of children in student No 4 family: 8
Number of children in student No 5 family: 7

Number of families with 1, 2, 3,...7 children: 3

Brief Explanation

  • The program starts by requesting the number of students using the printf function. The printf functions provide formatted output conversion.
  • Using the function scanf, the number is read and assigned to the integer variable students. scanf reads characters from the standard input, interprets them according to the specification in format, and stores the results through the remaining arguments. scanf stops when it exhausts its format string, or when some input fails to match the control specification.
  • Using a for loop to loop through the number of students, the number of children in each student family is read and assigned to the variable children. The integer array data consists of the number of children in each student's family.
  • Using another for loop to loop through the number of students, a count of the number of families with 1, 2, 3 right up to 7 children is determined and printed to the standard output.
  • The return value of zero in the main function implies normal termination; non-zero values signal unusual or erroneous termination conditions.

Add comment


Security code
Refresh