Repeating a character using loop – CSKC
Sign In

Search

Solved Problem #CPP#2218    siteicon   siteicon  

Problem Statement - Repeating a character using loop

Write a program to repeat the character as given by the user for number of times as desired by the user. Show the repeated character in the same line. Use for loop for repeatition.

Solution

TC++ #2218

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Alternate (?) :

char c; //Storage variable as char type for single character to be given by user
int rc; //Storage variable for repetition count to be given by the user. int type
cout<<“Give a single character : “; cin>>c;
Collecting user input for character.

cout<<“Give repetition count : “; cin>>rc;
Collecting user input for repetition count

for(int i=0;i<rc;++i) cout<<c;
Loop runs till rc and prints the character in c. As there is no additional character in the cout chain, the symbol is printed repeatedly in the same line.

Common Errors

  • Some students make error in building the loops examples are.
    for(int i=0;i<=rc,++i) will print one additional time as the loop begins from 0.
    for(int i=1;i<rc,++i) will print 1 less time as loop starts from 1 and ends at less than count.Correct options are:
    for(int i=0;i<rc,++i)
    for(int i=1;i<=rc,++i)
    The first one out of these two options is preferable as comparison is just less than and not less than and equal to.


Share

Created: 5-Jan-2018 14:38 | Updated: 18-Dec-2018 18:36|