sheet 2

19
Sheet 2 control structures

Upload: weam-elsahar

Post on 16-Nov-2015

4 views

Category:

Documents


2 download

DESCRIPTION

C programming control structures

TRANSCRIPT

  • Sheet 2

    control structures

  • if condition

    if (condition) statement

    if (x == 100) cout

  • Relational and equality operators ( ==, !=, >, =, Greater than

    < Less than

    >= Greater than or equal to

  • Relational and equality operators ( ==, !=, >, =, 4) // evaluates to true. (3 != 2) // evaluates to true. (6 >= 6) // evaluates to true. (5 < 5) // evaluates to false.

  • Logical operators ( !, &&, || )

    !(5 == 5) // evaluates to false !(6

  • Logical operators ( !, &&, || )

    ( (5 == 5) && (3 > 6) ) // evaluates to false ( (5 == 5) || (3 > 6) ) // evaluates to true

  • if condition

    if (x == 100) { cout

  • if else

    if (x == 100) cout

  • if else

    if (x > 0) cout

  • Question 6 (Sheet 1)

    Write a program that reads in the values for a, b, and c and find the roots of the polynomial:

    2 + + = 0

  • Question 6 (Sheet 1)

    Write a program that reads in the values for a, b, and c and find the roots of the polynomial:

    2 + + = 0

    2 4

    2

  • Question 6 (Sheet 1)

    a. The first coefficient is zero: Program terminates with an

    error message.

    b. Complex roots: Program prints solutions including the imaginary part.

    c. One real solution: Program states that there is only one solution and prints it.

    d. Two different real solutions: Program prints both normally.

  • Loops

    Do I know the number of repetitions?

    Yes (for loop) for (initialization; condition; increase) statement;

    No (while and do-while) while (expression)

    statement;

  • for loop

  • Question 1

    Write a program that prints the square of all numbers from 1 to 20.

  • Question 2

    Write a program that computes and displays the sum of odd integers in the range 0 to 100, inclusive.

  • Conditional operator ( ? )

    X= (7==5) ? 4 : 3 // returns 3 X= (7==5+2) ? 4 : 3 // returns 4 X= 5>3 ? a : b //X=a

  • Question 4

    Write a program to read a collection of exam scores ranging in values from 1 to 100. Your program should find and print the average score, the maximum and the minimum scores. the program will terminate if the value -99 is entered by the user.

  • Question 5

    Write a program fragment that uses nested loops to produce the following output: 1 12 123 1234 12345 123456 1234567 12345678 123456789