Please read entire instructions. In a few paragraphs escribe the program below.
ID: 3781357 • Letter: P
Question
Please read entire instructions.
In a few paragraphs escribe the program below. State the requirements for the program and discuss the logical process your program uses to meet those requirements.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// creating dynamic memory
int *arr = (int *)malloc(100*sizeof(int));
int i=0, j=0, n=0; //initialize variables
while(n != -1) { //infinite loop which will stop when user enters -1
printf("Enter percentage grade(0-100). Enter -1 to stop: ");
scanf("%d",&n); //read grade
if(n != -1){ //if user entered grade is not -1
arr[i++] = n; //save it to array
} else { //if user entered -1, then exit this loop
break;
}
}
printf(" The grades are: ");
for(j=0; j<i; j++){ //loop which will iterate till no:of user entered grades
printf("%d ",arr[j]); //print the grade
}
printf(" ");
// deleting memory
free(arr);
return 0;
}
Explanation / Answer
Its a C Program
Requirements
1. The program Needs a dynamic memory of size 100.
2. User needs to enter percentage grade.
3. The grades should be displayed .
4. Allocated Memory needs to be freed.
5. Program ends.
Logical Process as how the requirements are achieved
1. The program includes few libraries that will be used like the standard library for functions and standard library for input/output.
2..Then The program Create a Dynamic memory from heap space of size 100 to store Integers. That is done using a library function from stdlib.h which is known as malloc. It will create an array of size 100 . Initially all the elements in an arraywill have some garbage values in it .
3. The program also declares temporary variables that will be used during the course of the program.
4. For entering grades , We write a while loop where user keeps entering the percentage grade betweem 0-100. The iinput from the console is picked up using a function in stdio.h which is known as scanf .
5. As soon as the user enters -1 means all the grades are entered. We keep track of count of how many grades user has entered.
6. Then all the entered grades are displayed using loop structres by iterating over an array of size calculated in Step 2.
7. Then Memory is freed using library function named as free (present in stdlib.h).
8. Then the program ends.
Let me know if there is any concern.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.