Docsity

The If Statement and Logic Operators in C Programming, Slides of Computer Programming

Partial preview of the text

Download The If Statement and Logic Operators in C Programming and more Slides Computer Programming in PDF only on Docsity!

The If Statement

Syntax:

if (expression) statement;

If the expression is true (not zero), thestatement is executed.

If the expression is false, it is notexecuted.

You can group multiple expressionstogether with braces:

if (expression) {

statement 1;statement 2;statement 3; }

Logic Operators in ‘if’

Equal to

if (x==10)

Not equal to

if (x!=10)

Less than

if (x<10)

Greater than

if (x>10)

Less than / equal to

if (x<=10)

Greater than / equal to

if (x>=10)

Single and Compound Statements

Single statements:

if

(

condition)

true_statement; else

false_statement

;

Multiple statements:

if

(

condition)

{

…… } else

{

…… }

Nested If Statements

void

main(void)

int winner =3;printf(“…and the winner of ICC is ”);if (winner==1)

printf(“Pakistan”); else if (winner==2)

printf(“England”); else if (winner==3)

printf(“WI”); else

printf(“Australia”);

}

Switch Statements

Switch statements look like thisexample:

switch

(expression)

{

value_

:

statements_1;

break;

value_

:

statements_2;

break;

...value_n

:

statements_n;

break

default

switch

(winner)

{

case

1

:

printf(“Pakistan”);

break;

case

2

:

printf(“England”);

break;

. value_n

:

statements_n;

break

default:

The For Loop

Syntax:

for

(initialization; test;

increment)

statements;

The for loop will first perform theinitialization.

Then, as long test is TRUE,

it will execute statements.

After each

execution, it will increment.

For loop

Known number of iterations

for(count=1;count<=10;count++){

body

of

loop

While loop

Unknown number of iterations

degree

while

(degrees

decree

increment;

The While Loop

An example while loop looks like this:

void

main(void)

char

ch;

while

(ch

‘Q’

ch

‘q’)

… ch

getchar(

A ‘while’ for ‘for’

i=0;while(i<10){

body

of

the

loop;

i++;

} is

equivalent

to

for(i=0;

i<10;

i++)

body

of

the

loop;

A ‘for’ for ‘while’

for(;

degree<360;)

degree

increment;

A forever loop

Using for

for(;;){

printf(“Would

you

please

stop

teaching

C\n”);

Using while

while(1){

printf(“Would

you

please

stop

teaching

C\n”);

Fahrenheit-to-Celsius conversion

void main(void){

int deg_c, deg_f;deg_c = 0;while (deg_c <= 100){

deg_f = (deg_c-32)*5/9;printf("%4d degrees F = %4d degrees C\n", deg_c, deg_f);deg_c = deg_c + 10;

} }