Docsity

C Programming: Operators, Control Structures and I/O, Slides of Computer Programming

Partial preview of the text

Download C Programming: Operators, Control Structures and I/O and more Slides Computer Programming in PDF only on Docsity!

Operators

^ == test equality

x == y

^ =

assignment

x = y

^ !=

not equal ^ >=

greater than or equal ^ <=

less than or equal

More operators

^ >

greater than ^ <

less than ^ no space between operators ^ = = is invalid

== OK

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)

If else

if(income

>^

printf(“pay

tax”);

else

printf(“find

a^

better

job”);

one

of

these

statements

always

execute

Single and Compound Statements

Single statements:^ if^

( condition)true_statement; else false_statement

;

Multiple statements:^ if^

( condition)

{

……} else^ { …… }

Switch Statements

^ Switch statements look like thisexample:

switch

(expression)

{

value_

:^ statements_1;

break;

value_

:^ statements_2;

break;

...value_n

:^ statements_n;

break

default

C Operators

^ The increment Operator^ 

Increment

x++ or ++x

^ Decrement

x–- or –-x

^ Shorthand Assigns^ 

x*=

(multiply x by 3; x = x * 3) ^ x+=

(add 5 to x) ^ x-=10 (subtract 10 from 6) ^ x/=

(halve x)

Precedence rules

^ set rules for precedence ^ use parenthesis

Conditional operator

marks

>^

printf(“passed”)

printf(“failed”);  condition^ ^ marks >50  Execute^ ^ 1st statement if condition is true^ ^ 2nd statement if condition is false

printf

printf

(“the

answer

is

= %d”,

x);

^ Specifies data type & where to get thevalue to display.

More printf

printf

(“%8.4f %d\n”, total,

sum);

^ display^ 

a real #

total with 4 decimal places

^ an integer

sum

More scanf

scanf(“%f”,&num_f);

^ read in floating point value

Loops

^ Repeat a series of statements ^ Not reasonable to copy statementsmultiple time ^ Need a way to repeat a block of code ^ Loops allow repetition