Lab 8 Loop Practice for loops IST 132 Fall 2013 Tom PaciFunk

Lab #8: Loop Practice (for loops)

IST 132- Fall 2013 -Tom Paci-Funk

Goals

• use repetition (looping) control structures

• construct counter-controlled loops

Overview

For this lab, you will write C++ code to practice controlling a for-loop with a counter variable.  Choose good variable names.Write comments you understand.    You can include all of these in the same file and just make them comments so you can turn them on independently.

1. Use a for loop to print the integers from 1 to 20 down the side of the monitor screen.

2. Use a for loop to print the integers from 21 to 35 on one line.

3. Use a for loop to print the integers from 35 to 1 in decreasing order.

4. Display the cubes of the first 10 positive integers in decreasing order.

5. Input a value for x from the keyboard. Display the value of x and decrease x by 0.5 as long as x is positive.

6. Input 5 integers from the keyboard. Output the average of all the numbers.

7. Input a value for n from the keyboard. Display the sum of the integers from 1 to n.

Solution

Question 1:

#include <iostream>

using namespace std;

int main()
{
for(int i=1; i<=20; i++){
cout<<i<<endl;
}

return 0;
}

Question 2:

#include <iostream>

using namespace std;

int main()
{
for(int i=21; i<=35; i++){
cout<<i<<\" \";
}

return 0;
}

Question 3:

#include <iostream>

using namespace std;

int main()
{
for(int i=35; i>=1; i--){
cout<<i<<\" \";
}

return 0;
}

Question 4:

#include <iostream>

using namespace std;

int main()
{
for(int i=10; i>=1; i--){
cout<<i*i*i<<endl;
}

return 0;
}

Question 5:

#include <iostream>

using namespace std;

int main()
{
int x;
cout<<\"Enter x value: \";
cin >> x;

for(double i=x; i>=0; i = i - 0.5){
cout<<i<<endl;
}

return 0;
}

Question 6:

#include <iostream>

using namespace std;

int main()
{
int n;
int sum = 0;
double average = 0;
cout<<\"Enter 5 numbers: \"<<endl;
for(int i=0; i<5; i++){
cin >> n;
sum = sum + n;
}
average = sum/(double)5;
cout<<\"Average is \"<<average<<endl;

return 0;
}

Question 7:

#include <iostream>

using namespace std;

int main()
{
int n;
int sum = 0;
cout<<\"Enter n value: \";
cin >> n;
for(int i=1; i<=n; i++){
  
sum = sum + i;
cout<<sum<<endl;
}
  
cout<<\"Sum is \"<<sum<<endl;

return 0;
}

Lab #8: Loop Practice (for loops) IST 132- Fall 2013 -Tom Paci-Funk Goals • use repetition (looping) control structures • construct counter-controlled loops Ove
Lab #8: Loop Practice (for loops) IST 132- Fall 2013 -Tom Paci-Funk Goals • use repetition (looping) control structures • construct counter-controlled loops Ove
Lab #8: Loop Practice (for loops) IST 132- Fall 2013 -Tom Paci-Funk Goals • use repetition (looping) control structures • construct counter-controlled loops Ove

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site