Lab Assignment 13:Control Structure Review

  1. The following program uses switch structure. Please convert this switch structure to if-else structure without changing the running result.

#include<iostream>

using namespace std;

int main()

{

int x, y, z;

cout<"Please input a number between 0-2: ";

cin>x;

cout<"Please input two integers: ";

cin>y>z;

switch(x)

{

case 0:

y++;

case 1:

case 2:

z--;

break;

default:

cout<”Invalid input”;

}

return 0;

}

  1. A year is leap year if either (1) or (2) holds:

(1)it is divisible by 400.

(2)it is divisible by 4 but not divisible by 100.

Input: an integer representing the year from a user

Output: “leap year” or “plain year”

  1. Write a program:

Input three integers from a user (call them a, b, c).

Output the message that correctly describes the numbers:

– "Three negative"

– "Two negative and one non-negative"

– "One negative and two non-negative"

–"Three non-negative"

  1. Write a program to prompt user to input an integer n and output the value of factorial n(written n!) Note: factorial n is the product of integers between 1 and n. For example, 4! = 1*2*3*4.Please use for loop in this problem!
  1. Using nested loop to output the following:
  1. file I/O + while(!filename.eof()) + if…else

A file (named by data.txt) has a list of integers, but no one knows how many numbers are there in this file. Please write a program that reads the list of numbers from a file and print out the largest number.

For example, if the file contains:

23 12 45 19 2 100

your program will output:

The largest number is: 100

* Please remember to include Comments.

Extra Credit: file I/O and while loop

Write a program that reads a list of numbers from a file. For each number, it outputs both the individual digits of the number in an equation and the sum of the digits onto an output file.

For example, if the file contains:

2345

123

45

19

your program will output:

2 + 3 + 4 + 5 = 14

1 + 2 + 3 = 6

4 + 5 = 9

1 + 9 = 10

NOTE: You DO NOT know how many lines the file contains.

Hint:

  1. use eof() to judge if we reach the end of the input file. If the input file is not ended, you can read the input from the file line by line.

For example, if you declare:

ifstream inData;

you can use the structure:

while(!inData.eof())

{

}

  1. For each line, you can look each line as a stream of character, use ifstreamVariable.get(ch) to read them one by one, and then change them into integer.

For example, if you declare:

ifstream inData;

char ch;

You can get the digit one by one by using:

inData.get(ch);

if ch=’\n’, then it is the end of the line.

  1. You can change a character ‘5’ into an integer 5 by abstracting a character ‘0’ since ‘5’ – ‘0’ = 5(integer).

For example, if you declare:

int digit;

you can get the digit by:

digit=ch – ‘0’;

* Please remember to include Comments.