C++ Lesson 2
Learning Objectives:
1. How to use for loop?
2. Single loop
3. How to trace the value of variable?
Preview objectives
1. Nested Loop (double loop)
Exercise 2-1: observe the output
#include <iostream>
using namespace std;
int main() {
int i;
i=1;
for (i;i<4;i=i+1){
cout<<"*";
}
return 0;
}
Exercise 2-2: observe the output
#include <iostream>
using namespace std;
int main() {
int i;
i=1;
for (i;i<4;i=i+1){
cout<<"*"<<"\n";
}
return 0;
}
<<作業2-1>>
讓使用者自行輸入次數,然後輸出相應數目的 * 。
輸出如下圖:
Exercise 2-3: observe the output
#include <iostream>
using namespace std;
int main() {
int i;
i=1;
for (i;i<=50;i=i+1){
cout<<i<<" ";
}
return 0;
}
<<Assignment 2-2>>
Output the numbers from 10 to 40 as follow:
<<Assignment 2-3>>
Output the even numbers from 1 to 50 as follow:
<<Assignment 2-4>
Let the user enter a smaller number first, and then a greater number and then output all the integers(整數) between these two numbers. The output is as follow:
Preview Exercise:
#include <iostream>
using namespace std;
int main() {
int i,j;
int total;
int length;
i=1;
j=1;
cout<<"enter the number of digits per row: ";
cin>>length;
cout<<"enter the total numbers: ";
cin>>total;
for (i;i<=total;i++){
for (j;j<=length;j++){
cout<<i<<",";
i=i+1;
}
i=i-1;
cout<<"\n";
j=1;
}
}




沒有留言:
張貼留言