1 / 7

Loops - Exercises

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)

cmcbride
Download Presentation

Loops - Exercises

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Loops - Exercises

  2. 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

  3. 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

  4. 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".

  5. 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; }

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

  7. 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; }

More Related