Print a string N number of times in C++
Hey, guys today we are going to learn how to print a string N number of times in C++. We can print a string N number of times with the help of iteration statements also known as loops. Before starting with the program lets discuss iteration statements.
Iteration statements / Loops
Iteration statements are used to execute a statement or a block of statements multiple numbers of times depending on the condition specified. In other words, loops execute a block of given statements repeatedly until the specified condition is true. Iteration statements involve ‘initialisation’, ‘test expression’ and ‘updating expression’. 3 iteration statements used in C++ are :
- for loop: This entry controlled loop iterate the block of statement a specific no of times.Syntax:
for(initialisation;test_expression;updating_expression) { statements; }
- while loop: This entry controlled loop iterates the block of statements. It is mostly used when the number of iterations is not known beforehand. more info Its syntax is:
initalisation; while(test_expression) { statements; updating_expression; }
- do-while loop: This is an exit controlled loop which means it executes the statement block once even if the test expression is false. Its syntax is:
initialisation; do{ statements; updating_expression; } while(test_expression);
Program to print a string N number of times using for loop
#include <iostream> using namespace std; int main() { int N; cout<<"Enter the value of N"; cin>>N; for(int i=1;i<=N;i++) { cout<<"Hello, Have a nice day "<<endl; } return 0; }
Output:
Enter the value of N 2 Hello, Have a nice day Hello, Have a nice day
C++ Program to print a string N number of times using while loop
#include <iostream> using namespace std; int main() { int N; cout<<"Enter the value of N"; cin>>N; int i=1; while(i<=N) { cout<<"Hello, Have a nice day "<<endl; i+=1; } return 0; }
Output:
Enter the value of N 3 Hello, Have a nice day Hello, Have a nice day Hello, Have a nice day
Program to print a string N number of times using do-while loop
#include <iostream> using namespace std; int main() { int N; cout<<"Enter the value of N"; cin>>N; int i=1; do { cout<<"Hello, Have a nice day "<<endl; i+=1; }while(i<=N); return 0; }
Output:
Enter the value of N 4 Hello, Have a nice day Hello, Have a nice day Hello, Have a nice day Hello, Have a nice day
Also, refer:
Leave a Reply