Concept explainers
Why should you indent the statements in the body of a loop?
Explanation of Solution
Reason for statement indention:
Some of the reasons for “indenting C++ statements in the body of a loop” are:
- The body of a loop contains C++ statements and it gets executed once the expression is valid. Otherwise it won’t execute.
- Multiple loop statements are enclosed by braces ({}) and should be intended, because, it separates the condition statements from surrounding code.
- Hence, it helps the programmer to easily identify the statements that are conditionally-executed.
Example:
Consider the following example program contains conditionally-executed statements:
Program code:
//Include required header files
#include <iostream>
#include<iomanip>
using namespace std;
//Main function
int main()
{
//declare the variable “n” as integer set “n” as 5
int n = 5;
//loop i values for 5 times
for (int i = 1;i <= n;i++)
{
//check the number is even
if (i % 2 == 0)
{
//if so, display it
cout << "\n"<<i<<" is even";
}
}
cout << endl;
return 0;
}
The highlighted statements are indented within the loop.
2 is even
4 is even
Want to see more full solutions like this?
Chapter 5 Solutions
STARTING OUT W/C++,...(LL)-W/ACCESS
Additional Engineering Textbook Solutions
Starting Out with Java: Early Objects (6th Edition)
Absolute Java (6th Edition)
Starting Out with Java: From Control Structures through Data Structures (4th Edition) (What's New in Computer Science)
Software Engineering (10th Edition)
Starting Out with Python (4th Edition)
Java: An Introduction to Problem Solving and Programming (7th Edition)
- Describe the difference between the while loop and the do-while loop.arrow_forwardhow does a programmer decide to use while loop versus a for loop?arrow_forwardWe use For loop instead of a while loop when we know exactly how many times you want to loop through a block of code. True Falsearrow_forward
- C++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningMicrosoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,Programming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:Cengage
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENT