70 likes | 82 Views
Loops - Exercises. Exercise 1. What is the value of x when the do ... while loop completes? int x = 10, k; do{ k = ++x; x -= 2; }while(k>0);. Answer: x=-2. Exercise 2. What is the value of t when the for loops complete? int t = 0; for ( int a=1; a<=5; a+=1)
E N D
Exercise 1 What is the value of x when the do ... while loop completes? int x = 10, k; do{ k = ++x; x -= 2; }while(k>0); Answer: x=-2
Exercise 2 What is the value of t when the for loops complete? int t = 0; for (int a=1; a<=5; a+=1) for (int b=1; b<=a; b+=2) t += a + b; Answer: t=51
Exercise 3 A car and a train are both traveling toward a railroad crossing on a collision course. The train is 1200 feet from the crossing and traveling at a constant speed of 40 feet per second. The car is 1500 feet away and traveling at 55 feet per second. Write a program to calculate and print each vehicles distance from the crossing at one-second intervals. If the car gets to the crossing first, print "Made it." If the train gets to the crossing first, print "Crash".
Exercise 3 - Solution #include <iostream> using namespace std; int main() { intt = 1200; intc = 1500; ints = 0; cout<<"S"<<"\t"<<"Train"<<"\t"<<"Car"<<endl; cout<<endl; while(t>0 && c>0) { t -=40; c -= 55; s++; cout<<s<<"\t"<<t<<"\t"<<c<<endl; } if(c < t) { cout<<"Made It!"<<endl; } else if(t<c) { cout<<"Crash!"<<endl; } cout<<endl; system("pause"); return 0; }
Exercise 4 Write a Loop that draws the following shape: * *** ***** *******
Exercise 4 - Solution #include <iostream> using namespace std; int main() { for(int i = 1;i<=4;i++) { for(int j =1;j<=4-i;j++) cout<<“ “; for(int k = 1;k<=(2*i)-1;k++) cout<<“*”; cout<<endl; } system("pause"); return 0; }