Artikel Terkait Tutorial C
In computer programming, loop cause a certain piece of program to be executed a certain number of times. Consider these scenarios:
There are 3 types of loops in C++ Programming:
- You want to execute some code/s certain number of time.
- You want to execute some code/s certain number of times depending upon input from user.
There are 3 types of loops in C++ Programming:
- for Loop
- while Loop
- do...while Loop
C++ for Loop Syntax
for(initialization statement; test expression; update statement) {
code/s to be executed;
}
How for loop works in C++ Programming?
The initialization statement is executed only once at the beginning of the for loop. Then the test expression is checked by the program. If the test expression is false, for loop is terminated. But if test expression is true then the code/s inside body offor
loop is executed and then update expression is updated. This process repeats until test expression is false.Flowchart of for Loop in C++
Example 1: C++ for Loop
C++ Program to find factorial of a number (Note: Factorial of positive integer n = 1*2*3*...*n)
#include <iostream>
using namespace std;
int main() {
int i, n, factorial = 1;
cout<<"Enter a positive integer: ";
cin>>n;
for (i = 1; i <= n; ++i) {
factorial *= i; // factorial = factorial * i;
}
cout<< "Factorial of "<<n<<" = "<<factorial;
return 0;
}
Output
Enter a positive integer: 5
Factorial of 5 = 120
In this program, user is asked to enter a positive integer which is stored in variable n (supposed user entered 5). Here is the working of
for
loop in this program:- Initially,
i = 1
, test expression is true, factorial becomes 1. - Variable i is updated to 2, test expression is true, factorial becomes 2.
- Variable i is updated to 3, test expression is true, factorial becomes 6.
- Variable i is updated to 4, test expression is true, factorial becomes 24.
- Variable i is updated to 5, test expression is true, factorial becomes 120.
- Variable i is updated to 6, test expression is false,
for
loop is terminated.
for
loop. In such case, it is better to define variable at the time of initialization statement.for (int i = 0; i <= n; ++i){In the above C++ code, i is local to
... .. ...
}
for
loop, that is, you cannot use it outside for
loop but makes program more readable.Selain Sebagai Penyedia Panduan Belajar Database dan Tutorial Pemrograman, Kami Juga Membagikan Kumpulan Source Code Program Aplikasi dan Ebook Pemrograman Terlengkap yang Bisa Anda Dapatkan Secara Gratis di Halaman :
Rekomendasi Web Hosting
- 20rb perbulan. Diskon hingga 40% kode kupon: MCP Daftar disini (apache).
- 10rb perbulan. Diskon hingga 75% kode kupon: MCP Daftar disini (litespeed).
- 10rb perbulan. Diskon hingga 70% kode kupon: aff-MCP Daftar disini (apache).