Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 4 1 Loops - Exercises. Lecture 4 Exercise 1 2 What is the value of x when the do... while loop completes? int x = 10, k; do{ k = ++x; x -= 2;

Similar presentations


Presentation on theme: "Lecture 4 1 Loops - Exercises. Lecture 4 Exercise 1 2 What is the value of x when the do... while loop completes? int x = 10, k; do{ k = ++x; x -= 2;"— Presentation transcript:

1 Lecture 4 1 Loops - Exercises

2 Lecture 4 Exercise 1 2 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

3 Lecture 4 Exercise 2 3 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

4 Lecture 4 Exercise 3 4 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".

5 Lecture 4 Exercise 3 - Solution 5 #include using namespace std; int main() { int t = 1200; int c = 1500; int s = 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; }

6 Lecture 4 Exercise 4 6 Write a Loop that draws the following shape: * *** ***** *******

7 Lecture 4 Exercise 4 - Solution 7 #include 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; }


Download ppt "Lecture 4 1 Loops - Exercises. Lecture 4 Exercise 1 2 What is the value of x when the do... while loop completes? int x = 10, k; do{ k = ++x; x -= 2;"

Similar presentations


Ads by Google