循环部分和数组作业(第6周)

更新时间:2023-09-25 14:56:01 阅读量: 综合文库 文档下载

说明:文章内容仅供预览,部分内容可能不全。下载后的文档,内容与下面显示的完全一致。下载之前请确认下面内容是否您想要的,是否完整无缺。

一、 代码练习:(只书写主要代码,变量定义、预处理命令等可省略)

1. 编写一个for循环程序,打印1~100间的所有奇数,每1行输出5个数。

2. 编写一个do/while循环来对10~0向下计数。

3. 编写一段while循环程序,计算1~10间除3和6之外的所有整数的和。并将结果打印

出来。

4. 编写计数控制的for循环程序,从1~10进行重复,并打印出计数结果。当计数器值为6

时,终止循环。

5. 修改上题中的程序,应用continue语句打印除6以外的所有值。

6. 声明数组为一个整数数组,包含3行3列。假设const变量arraySize已经被

定义为3。该数组包含多少个元素?

7. 使用一条for循环语句把数组的每个元素初始化为它的下标之和。假设整型

变量i和j被声明为控制变量。

二、 程序输出练习:阅读以下程序代码段,写出程序的输出结果(注意,请勿在计算机上执行程序).

1. 以下程序的输出结果是什么?

int x = 1;

while ( x <=3 ) { x++; cout << “The value of x is: “<< x << endl; }

cout << “The final value of x is: “ << x << endl;

2. 下面的for循环的输出是什么?

for ( int i = 0; i < 5; i++ ) cout << i << “ “;

3. 以下程序段的输出结果是什么?

int grade1 = 65; int grade2 = 55;

cout << “The student with a grade of “ << grade1 <<” “ << ( grade1 >= 60 ? “Passed\\n” : “Failed\\n” ); cout << “The student with a grade of ” << grade2 <<” “ << ( grade2 >= 60 ? “Passed\\n” : “Failed\\n” );

4. 以下程序段的输出结果是什么?

for ( int i = 1; i <= 10; i++ ) { switch ( i ) { case 1 : cout << “The value of x is 1\\n”; break; case 4 : cout << ”The value of x is 4\\n”; case 6: cout << “The value of x is 6\\n”; break; default: cout << “The value of x is neither 1, 4 nor 6\\n”; } }

5. 以下程序段的输出结果是什么?

int x;

for ( x = 1; x <= 10; x++ ) { if ( x == 7 ) break; if (x == 3 ) continue; cout << x << “ “; }

cout << endl << “The final value of x is: “ << x << endl;

6. 以下程序段的输出是什么?

int x = 1;

for ( ; x <=3 ; x++ ) ; cout << “The value of x is: “ << x << endl;

三、 程序调试练习:利用Visual C++开发环境对程序进行调试,使程序运行正确。(若能在原题上修改也可,若标识不清楚,可重写这段程序)

1. 找出a,b,c三个数中最大值,最小值,中间值。 #include #include using namespace std; int main() { int a, b, c, largest,x; cin>>a>>b>>c>>endl; x=(a>b)?a:b; largest=(x>c)?x:c; int smallest; x=(a

middle=b; if (c!=largest & c!=smallest) middle=c; cout<

【提示:当a=3, b=5, c=3时程序运行正确吗?】 修改后正确程序如下:

2. 找出a,b,c三个数中最大值,最小值,中间值。

#include #include using namespace std; int main() { int a, b, c, middle; cin>>a,b,c; if (a>=b && a<=c ) middle=a; else if (b>=a && b<=c) middle = b; else middle =c; cout<<\ return 0; }

【提示:当a=4, b=5, c=3时程序运行正确吗?】 修改后正确代码如下:

3. 下面的程序用以计算1~5之间所有整数的乘积。

#include using namespace std; int main() {

for ( int i = 1; i < 5 ; i++ ) { int product = 1; product *= i; }

}

cout << “The product is : “ << product << endl; return 0;

修改后正确代码如下:

4. 下面的程序用于打印出在5~1000之间的可以被5整除的所有整数。

#include using namespace std; int main() {

int i = 5;

for ( ; ; i += 5 ) { cout << i << “ “; if ( i = 1000 ) break; return 0; }

修改后正确代码如下:

5. 下面的程序用switch语句来打印x is 5,x is 10或x is neither 5 nor 10。

#include using namespace std; int main() {

int x;

cin >> x ;

switch ( x ) { case: 5 cout << “x is 5\\n”; case: 10 cout << “ x is 10\\n”; case default: cout << “x is neither 5 nor 10\\n”; }

本文来源:https://www.bwwdw.com/article/fhnd.html

Top