Before starting to write code, it is important to have a clear picture of what t
ID: 3575116 • Letter: B
Question
Before starting to write code, it is important to have a clear picture of what the program should do and the steps in the process for reaching the desired result. Choose either the program for part 1 or part 2 of this unit's assignment and write out in plain English what the program needs to do and describe the steps in the process to solve the problem. Focus on a clear explanation of the process of solving the problem, not writing C. While it is a good idea to do this for both programs, you only need to discuss one in this post.
Here is the code I need spoken for.
#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
The program address the following problem :
To create an array of max of 100 integers(grades) dynamically using pointers and malloc function
Then take 3 Integer variables with initial value 0.
Use one variable to take input grade
Another one to index each position in array
Another one variable to re access all elements in array to output after completing input.
The input section ends when user enters -1 and then prints the grades inputted till then using a for loop.
Now in the code after declaration's use a while loop to continuously input grades sequentially into an array using a index variable (i) until the last input grade(n) not equal -1.
If the condition breaks then the controls skips out of while due to else condition in the loop and then the output loop executes until the current index in array (I.e i) printing each grade.
Finally the memory allocated to arr is freed using free function .
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.