In: Computer Science
C++ Code
Using all for loops
1. Print 5 lines with 1 asterisk per line
2. Print 5 asterisk on 1 line. Endl at the end of the line.
3. Ask for a positive # and print that many asterik on the next line.
4. Using 2 for loops one inside of another that only prints 1 asterik, print a hill shaped triangle:
Ex( Input a number a: 4
*
**
***
****
5. Change the for statements to print the triangle upside down.
1.
Code:-
#include <bits/stdc++.h>
using namespace std;
int main() {
for(int i=0;i<5;i++) // for loop to iterate 5 times
cout<<"*"<<endl; //print one asterik mark per line
return 0;
}
Output:-
2.
Code:-
#include <bits/stdc++.h>
using namespace std;
int main() {
for(int i=0;i<5;i++) // for loop to iterate 5 times
cout<<"*"; //print five asterik mark per line
return 0;
}
Output:-
3.
Code:-
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cout<<"Input a number"<<endl;
cin>>n; //Ask for positive integer
for(int i=0;i<n;i++) // for loop to iterate n times
cout<<"*"; //print n asterik mark per line
return 0;
}
Output:-
4.
Code:-
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cout<<"Input a number"<<endl;
cin>>n; //Ask for positive integer
for(int i=0;i<n;i++) // for loop to iterate n times
{ for(int j=0;j<=i;j++) // second for loop to print pattern in hill shaped triangle
cout<<"*";
cout<<endl;
}
return 0;
}
Output:-
5.
Code:-
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cout<<"Input a number"<<endl;
cin>>n; //Ask for positive integer
for(int i=0;i<n;i++) // for loop to iterate n times
{ for(int j=n;j>i;j--) // second for loop to print the triangle upside down
cout<<"*";
cout<<endl;
}
return 0;
}
Output:-