TestingDocs.com
Software Testing website
  • Automation
    • Selenium
    • JBehave Framework
  • Tutorials
    • MySQL Tutorials
    • Testlink
    • Maven
    • Git
  • IDEs
    • IntelliJ IDEA
    • Eclipse
  • Flowcharts
    • Flowgorithm
    • Raptor
  • About

C++

C++ iteration using for loop

C++

Introduction

In this post, we will discuss for loop as it is used often in C++ programs. For loop allows you to execute the action for each iteration in the loop.

Syntax

for(for initialization; for expression ; post expression)

{

// loop statements

}

Loop statements can be a single statement or group of statements nested within curly braces.

Flowchart

 

Sample program

The following code prompts user to enter a number. It uses a for loop to compute the factorial of the number.

/*************************
* C++ for loop demo
*************************/

#include <iostream>
using namespace std;

int main()
{
 int n;
 int factorial=1;
 cout << "Please enter a number : " ;
 cin >> n;
 // for loop
 for(int i=2; i<=n; i++)
 {
 factorial *= i;
 }
 cout << n << " factorial is = " << factorial << endl;
 return 0;
}

run output: Please enter a number : 5 5 factorial is = 120 Process returned 0 (0x0) execution time : 49.577 s Press any key to continue.

 

 

For loop is executed until the expression involving the index variable i is false to exit the loop as shown in the flow chart. Any for statement can be converted into a while loop statement in C++.   

 

—

C++ Tutorials

C++ Tutorials on this website:

https://www.testingdocs.com/c-coding-tutorials/

For more information on the current ISO C++ standard

https://isocpp.org/std/the-standard

Related Posts

C++ /

Install GCC C++ Compiler on OpenSuse

C++ /

Sum of Digits of a Number C++ Program

C++ /

C++ Hello World Program

C++ /

Object-Oriented Programming Language Examples

C++ /

Object-Oriented Programming Features

‹ C++ while statement› C++ if-else statement

Recent Posts

  • Scaler Academy – An Online Learning Platform
  • Difference between PHP and JavaScript?
  • MS Access Data Types
  • Install RAPTOR Avalonia on CentOS
  • Download RAPTOR Avalonia Edition on Windows
  • npm doctor command
  • Build & Run CLion Project
  • Create New CLion C Project on Windows
  • Configure CLion Toolchains on Windows
  • Launch CLion IDE on Windows

Back to Top

Links

  • Contact
  • Privacy Policy
  • Cookie Policy

www.TestingDocs.com