Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C Programming Language Goals • Practice with creating and using arrays Tasks 1.

ID: 3696819 • Letter: C

Question

C Programming Language

Goals

• Practice with creating and using arrays

Tasks

1. Write a program to count how many pets the students have in a given class:

a. The largest number of students in a class is 20. Hint: Define a symbolic constant to set this limit and use this to define the array size and when checking for appropriate input range.

b. Ask the user to enter how many students are in their class. (Check for valid input) Hint: You need to use repetition to ensure the number entered is greater than 0 and less than or equal to 20. Use the symbolic constant defined above.

c. For each student in class, ask the user to enter how many pets he/she has and save that number in an array. Hint: The array will have a size of 20, which is the maximum number of students possible, but you will not use the entire array for smaller classes.

d. Print a summary of the number of pets for each student.

e. Print the total number of pets in the class.

2. The output should look similar to the example below:

How many students are in your class (max 20)? 5

How many pets does student 1 have? 0

How many pets does student 2 have? 1

How many pets does student 3 have? 2

How many pets does student 4 have? 0

How many pets does student 5 have? 3

Number of pets for each student: 0 1 2 0 3

Your class has a total of 6 pets

Explanation / Answer

#include<stdio.h>
#include<stdlib.h>
#define max 20

int main()
{
   int a[max],i,n,sum=0;
   printf("How many students are in your class (max 20)? ");
   scanf("%d",&n);
   if(n==0 || n<=20)
   {
       for(i=0;i<n;i++)
       {
       printf("How many pets does student %d have? ",i+1);
       scanf("%d",&a[i]);
       sum=sum+a[i];
       }
       printf("Number of pets for each student :");
       for(i=0;i<n;i++)
       {
           printf("%d ",a[i]);
       }
       printf(" Your class has a total %d pets",sum);
   }
   else
   {
   printf("Invlaid input");
}
   return 0;
}