Get a Program to Run Again C
Learning C: The Input and Process Until Done Template and the while Loop
In this article, I hash out the adjacent major construct in C — the loop. I'll start past introducing a new program template related to loops, the Input and Process Until Done template, and then I'll demonstrate how to implement this template using 1 C looping construct — the while statement.
The Input and Process Until Done Template
One of the nigh mutual things you exercise in a computer plan is repeatedly as the user for information and procedure that data until in that location is no more data to input. The Input and Process Until Done template provides an outline for how to write the lawmaking for this task.
Here is the pseudocode for the template:
Echo the post-obit until finished:
Read a value
Process the value
An example, which I'll demonstrate in C downwardly below, is to decide the boilerplate grade on a exam past inputting all the exam scores and and so calculating the average once the last test grade is entered. Here is some possible pseudocode for this problem:
While at that place are more grades to enter:
Prompt the user to enter a grade
Go the grade from the keyboard
Add the grade to the running total
Compute the average
At present allow's come across how to implement this template using the while statement.
The while Statement
The beginning C construct I'll prove you for implementing loops in C is the while statement. The while statement tests a condition and executes a gear up of statements while the condition is true.
Here is the syntax template for the while statement:
while (expression) {
argument(s); // the loop body
}
I'll begin with a simple example — a counting programme that counts from one to ten. Here is the program:
#include <stdio.h>
#include <stdlib.h> int chief()
{
int number = 1;
while (number <= 10) {
printf("number is: %d\n", number);
number++;
}
render 0;
}
printf("Terminate of program.\n");
Here's how this program executes. The variable number is initialized to 1. In the next line number is tested to see if its value is less than or equal to 10. It is then control falls into the loop body and the printf role is called. The side by side line increments number by 1. So control jumps back upwards to the decision-making expression (number <= 10), and since 2 is less than or equal to 10, the loop torso is executed over again. This continues until the value of number becomes 11. Then the expression is tested and since xi is not less than or equal to 10, the expression is false and command jumps to the first line subsequently the end of the loop torso.
This program gives me the opportunity to list out the steps you should follow when writing a while statement. The first step is to country a status you want to agree true so the statements inside the loop trunk will execute. This problem calls for counting from 1 to 10 so I want the loop to execute while the value of the variable number is less than or equal to ten.
The 2d step is to initialize or assign a value to the variable in the controlling expression such that the expression evaluates to true going into the loop trunk. Past initializing number to i I am assured the loop will run at least once.
The third step is to perform whatever task you want the loop to perform. In this case the job is to display the current value of number.
The quaternary and terminal step is to change the controlling expression and so the loop will eventually end. If y'all don't perform this step, the loop will run indefinitely or until the computer runs out of memory. This is called an countless or infinite loop. I avoid an endless loop by increment number by one at the bottom of the loop, right before the test.
Here is the output from this program:
number is: one
number is: 2
number is: three
number is: 4
number is: v
number is: 6
number is: 7
number is: viii
number is: nine
number is: 10 This type of loop is called a count-controlled loop because yous can await at the program and know how many times the loop will iterate (repeat). In the program above its ten times considering the variable is initialized to 1 and the plan stops afterward the variable reaches ten.
Count-controlled loops are more frequently written using the for argument, which I'll discuss in a future commodity.
The other blazon of loop is a sentinel-controlled loop. This type of loop runs until a special value is encountered which causes the loop to stop. The special value is part of the while statement's expression.
Sentinel-Controlled Loops and the Input and Process Until Washed Template
The Input and Procedure Until Done template is often implemented with a sentry-controlled loop. Here is the pseudocode for a problem that is best solved with this template:
While there are more grades to enter:
Prompt the user to enter a form
Get the grade from the keyboard
Add the grade to the running total
Compute the average
Now let'due south write a program that implements this pseudocode:
int master()
{
int class, count, total = 0;
char more = 'Y';
count = 0;
while (more == 'Y') {
printf("Enter a grade: ");
scanf("%d", &class);
total += grade;
count++;
getchar();
printf("Enter another grade (Y/N)? ");
scanf("%c", &more);
}
double average = (bladder)total / count;
printf("The course average is %.2f", boilerplate);
return 0;
} Here is the output from one run of this plan:
Enter a grade: 67
Enter another grade (Y/North)? Y
Enter a grade: 71
Enter another class (Y/N)? Y
Enter a class: 83
Enter another course (Y/N)? Y
Enter a grade: 91
Enter another grade (Y/N)? Y
Enter a class: 99
Enter another grade (Y/N)? N
The form average is 82.20 One problem with this program is that the input is continually beingness interrupted by the prompt asking if the user wants to enter another course. Another way to use a watch value is to selection a form that cannot be earned, such as -1, and entering that class is a signal for the programme to cease.
Here is the program rewritten with such a picket value:
int primary()
{
int class, count, total = 0;
char more = 'Y';
count = 0;
printf("Enter a form: ");
scanf("%d", &class);
while (class != -i) {
full += form;
count++;
getchar();
printf("Enter a class: ");
scanf("%d", &grade);
}
double boilerplate = (float)total / count;
printf("The grade average is %.2f", average);
return 0;
} Here is the output from one run of this program:
Enter a grade: 81
Enter a form: 77
Enter a grade: 92
Enter a course: 85
Enter a grade: -ane
The class boilerplate is 83.vii Another use of a scout-controlled loop is for data validation. For case, the program you lot are writing needs the user to enter a positive number and anything less than 1 is unacceptable. You can use one equally a spotter value, maxim in outcome, if you enter anything less than 1, that data is not valid and delight enter a new value that is at least equal to 1.
Here is a programme that demonstrates the use of a sentinel value in data validation:
int main()
{
int data = 0;
while (data < one) {
printf("Enter a number: ");
scanf("%d", &data);
}
printf("You entered a valid number.\north");
return 0;
} Here is the output from ane run of this program:
Enter a number: 0
Enter a number: -1
Enter a number: -100
Enter a number: 0
Enter a number: ii
Yous entered a valid number. Here is another example in which the user is expected to enter a value between one and 100:
int main()
{
int grade = 0;
while (grade < i || class > 100) {
printf("Enter a grade value of one to 100: ");
scanf("%d", &class);
}
printf("%d is between i and 100.\north", grade);
return 0;
} Here is the output from i run of this plan:
Enter a grade value of 1 to 100: -ane
Enter a form value of 1 to 100: thou
Enter a course value of one to 100: 0
Enter a class value of 1 to 100: 101
Enter a class value of 1 to 100: 85
85 is between 1 and 100. I've strayed a bit from the Input and Procedure Until Done template but performing data validation using loops is an important tool every developer can use then I thought it was important to show it to y'all now.
That's it for this article on loops and the Input and Process Until Done template. In my adjacent article we'll continue learning how to implement this template using a different looping construct — the do-while statement.
Thanks for reading and please reply to this article or e-mail me with your comments and suggestions.
Source: https://levelup.gitconnected.com/learning-c-the-input-and-process-until-done-template-and-the-while-loop-d8be9b5a772d
0 Response to "Get a Program to Run Again C"
Postar um comentário