How to Run a Loop Again After It Ends C++
Learning C: The Input and Process Until Done Template and the while Loop
In this article, I talk over the adjacent major construct in C — the loop. I'll start by introducing a new plan template related to loops, the Input and Procedure Until Done template, and then I'll demonstrate how to implement this template using one C looping construct — the while argument.
The Input and Process Until Washed Template
One of the nigh common things yous practise in a reckoner program is repeatedly as the user for data and procedure that data until there is no more data to input. The Input and Process Until Done template provides an outline for how to write the code for this task.
Here is the pseudocode for the template:
Repeat the post-obit until finished:
Read a value
Procedure the value
An case, which I'll demonstrate in C down below, is to determine the boilerplate grade on a examination past inputting all the test scores and so computing the boilerplate once the concluding examination grade is entered. Here is some possible pseudocode for this trouble:
While there are more grades to enter:
Prompt the user to enter a class
Become the course from the keyboard
Add the grade to the running total
Compute the average
Now let's see how to implement this template using the while statement.
The while Statement
The start C construct I'll show yous for implementing loops in C is the while statement. The while argument tests a status and executes a gear up of statements while the status is true.
Here is the syntax template for the while statement:
while (expression) {
statement(s); // the loop body
}
I'll begin with a simple case — a counting program that counts from one to 10. Here is the program:
#include <stdio.h>
#include <stdlib.h> int main()
{
int number = 1;
while (number <= ten) {
printf("number is: %d\n", number);
number++;
}
return 0;
}
printf("Stop of program.\n");
Here's how this program executes. The variable number is initialized to i. In the side by side line number is tested to encounter if its value is less than or equal to 10. It is and so control falls into the loop body and the printf office is called. The next line increments number by ane. Then control jumps back up to the decision-making expression (number <= 10), and since 2 is less than or equal to x, the loop body is executed once more. This continues until the value of number becomes 11. And then the expression is tested and since eleven is not less than or equal to x, the expression is false and command jumps to the first line after the terminate of the loop body.
This programme gives me the opportunity to list out the steps you should follow when writing a while statement. The get-go step is to state a condition yous want to concord truthful and then the statements inside the loop trunk will execute. This problem calls for counting from one to 10 so I want the loop to execute while the value of the variable number is less than or equal to x.
The second stride is to initialize or assign a value to the variable in the controlling expression such that the expression evaluates to truthful going into the loop torso. By initializing number to 1 I am assured the loop will run at least once.
The third step is to perform whatever chore you want the loop to perform. In this case the task is to display the current value of number.
The fourth and last footstep is to modify the controlling expression so the loop will eventually stop. If you don't perform this step, the loop volition run indefinitely or until the computer runs out of memory. This is called an endless or infinite loop. I avoid an countless loop by increment number by 1 at the lesser of the loop, right earlier the test.
Here is the output from this program:
number is: 1
number is: 2
number is: 3
number is: 4
number is: 5
number is: 6
number is: 7
number is: eight
number is: 9
number is: 10 This type of loop is called a count-controlled loop because you lot can expect at the plan and know how many times the loop volition iterate (repeat). In the programme above its 10 times because the variable is initialized to 1 and the program stops after the variable reaches ten.
Count-controlled loops are more ofttimes written using the for statement, which I'll discuss in a future article.
The other type of loop is a sentinel-controlled loop. This blazon of loop runs until a special value is encountered which causes the loop to end. The special value is part of the while statement'due south expression.
Scout-Controlled Loops and the Input and Process Until Done Template
The Input and Process Until Washed template is often implemented with a watch-controlled loop. Here is the pseudocode for a problem that is all-time solved with this template:
While there are more grades to enter:
Prompt the user to enter a form
Become the grade from the keyboard
Add the grade to the running total
Compute the boilerplate
Now let's write a program that implements this pseudocode:
int main()
{
int grade, count, total = 0;
char more than = 'Y';
count = 0;
while (more == 'Y') {
printf("Enter a grade: ");
scanf("%d", &course);
full += form;
count++;
getchar();
printf("Enter another grade (Y/Northward)? ");
scanf("%c", &more);
}
double average = (bladder)total / count;
printf("The grade average is %.2f", average);
return 0;
} Here is the output from one run of this program:
Enter a grade: 67
Enter some other form (Y/N)? Y
Enter a grade: 71
Enter another course (Y/N)? Y
Enter a class: 83
Enter another grade (Y/N)? Y
Enter a grade: 91
Enter another course (Y/N)? Y
Enter a grade: 99
Enter some other grade (Y/N)? N
The grade average is 82.20 Ane problem with this programme is that the input is continually being interrupted by the prompt asking if the user wants to enter another grade. Another mode to use a sentinel value is to option a form that cannot be earned, such every bit -i, and inbound that form is a signal for the program to end.
Here is the program rewritten with such a sentinel value:
int main()
{
int grade, count, total = 0;
char more = 'Y';
count = 0;
printf("Enter a course: ");
scanf("%d", &course);
while (grade != -1) {
full += grade;
count++;
getchar();
printf("Enter a course: ");
scanf("%d", &class);
}
double average = (float)total / count;
printf("The grade average is %.2f", average);
render 0;
} Here is the output from i run of this plan:
Enter a grade: 81
Enter a course: 77
Enter a grade: 92
Enter a grade: 85
Enter a grade: -ane
The class average is 83.vii Another use of a scout-controlled loop is for data validation. For example, the program yous are writing needs the user to enter a positive number and anything less than ane is unacceptable. You can utilise 1 equally a sentinel value, maxim in effect, if you enter anything less than ane, that data is not valid and please enter a new value that is at least equal to 1.
Hither is a plan that demonstrates the utilize of a lookout man value in data validation:
int main()
{
int data = 0;
while (data < 1) {
printf("Enter a number: ");
scanf("%d", &information);
}
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: 2
You lot entered a valid number. Here is another example in which the user is expected to enter a value between 1 and 100:
int main()
{
int grade = 0;
while (course < i || class > 100) {
printf("Enter a grade value of one to 100: ");
scanf("%d", &grade);
}
printf("%d is between ane and 100.\northward", grade);
return 0;
} Here is the output from i run of this program:
Enter a grade value of i to 100: -i
Enter a form value of 1 to 100: 1000
Enter a form value of i to 100: 0
Enter a form value of 1 to 100: 101
Enter a grade value of 1 to 100: 85
85 is betwixt ane and 100. I've strayed a bit from the Input and Process Until Done template but performing information validation using loops is an important tool every programmer can utilise so I thought it was important to show it to y'all now.
That'south it for this article on loops and the Input and Process Until Washed template. In my adjacent article we'll go on learning how to implement this template using a dissimilar looping construct — the do-while argument.
Thanks for reading and delight respond to this article or email me with your comments and suggestions.
christopherting1950.blogspot.com
Source: https://levelup.gitconnected.com/learning-c-the-input-and-process-until-done-template-and-the-while-loop-d8be9b5a772d
0 Response to "How to Run a Loop Again After It Ends C++"
Post a Comment