0% found this document useful (0 votes)
27 views

CMP1401: Introduction To Programming With C: Ece Gelal Soyak Bahc Es Ehir Universitesi

This document discusses control flow statements in C programming such as if/else statements and switch statements. It provides examples of basic if/else statement structure and usage, relational and logical operators, and nested conditional statements. It also offers some good practices for writing clear conditional code using explicit comparisons, braces, and proper indentation.

Uploaded by

hicape5709
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

CMP1401: Introduction To Programming With C: Ece Gelal Soyak Bahc Es Ehir Universitesi

This document discusses control flow statements in C programming such as if/else statements and switch statements. It provides examples of basic if/else statement structure and usage, relational and logical operators, and nested conditional statements. It also offers some good practices for writing clear conditional code using explicit comparisons, braces, and proper indentation.

Uploaded by

hicape5709
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

If/Else Statements Switch Statements Sum-Up

CMP1401: Introduction to Programming with C


0 1
14
Ece Gelal Soyak

P
Bahçeşehir Üniversitesi

C M
Week 4: Relational and Logical Operators
Nov. 3, 2020

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 1 / 28


If/Else Statements Switch Statements Sum-Up

In this lecture...

0 1
Introduction to Control Statements

1
This week we’ll study Conditionals
Next week is Loops
4
Switch Statements
P
enum data type

C M
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 2 / 28
If/Else Statements Switch Statements Sum-Up

Basic Structure of a C Program

#include <...>
/∗

∗/
// libraries to be included

function declarations go next (week 11)

0 1
int main()
{
// variable declarations first

14
P
int i ;
float f ;

// executable statements go next

}
i ++;
printf ( ” i =%d\n”, i ) ;

return(0) ;

C M
Variable declarations are grouped together at the beginning of the program.
Two or three spaces are used to indent sections of code.
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 3 / 28
If/Else Statements Switch Statements Sum-Up

What is a “Conditional Statement”?

Used to determine whether some instructions should be executed


Depending on a condition

0 1
Syntax:
if ( [BOOLEAN CONDITION] )
14
{
P
<statement to execute if condition is true>
}
else
{
C M
<statement to execute if condition is false>
}

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 4 / 28


If/Else Statements Switch Statements Sum-Up

Example

0 1
if (number < 0)
{

14
P
printf ( ”Error! You must enter a positive number!”);
}

C M
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 5 / 28
If/Else Statements Switch Statements Sum-Up

Relational Operators

0 1
Operator
==
<
Description

14
true if operands are equal
true if left operand is less than right
>
<=
P
true if right operand is greater than right
true if left is less than or equal to right
>=

M
true if left is greater than or equal to right

C
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 6 / 28
If/Else Statements Switch Statements Sum-Up

Logical Operators

1
a true false
Negation ( ! )
!a false true

a b &&

4 0
1
true true true
AND ( && ) true false false
false
false
true
false
P
false
false

a
true
OR ( || ) true
C M b
true
false
||
true
true
false true true
false false false

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 7 / 28


If/Else Statements Switch Statements Sum-Up

Nested Conditionals
Example: Implement the following catalog grading:

Score
Letter
Grade
{
printf ( ”A”);

0 1
if ( studentGrade >= 90 ) // 90 and above gets ”A”

4
}
<60 F else if ( studentGrade >= 80 ) // 80−89 gets ”B”

1
60-70 D {
70-80 C printf ( ”B”);

P
80-90 B }
else if ( studentGrade >= 70 ) // 70−79 gets ”C”
90-100 A
{
printf ( ”C”);

C M }
else if ( studentGrade >= 60 ) // 60−69 gets ”D”
{

}
printf ( ”D”);

else // less than 60 gets ”F”


{
printf ( ”F”) ;
}
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 8 / 28
If/Else Statements Switch Statements Sum-Up

Good Practices - 1

It’s better to make the comparison explicit, like

0 1
4
if (x != 0)
{

}
DoSomething();

instead of
P 1
M
if (x)
{

C
DoSomething();
}

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 9 / 28


If/Else Statements Switch Statements Sum-Up

Good Practices - 2: Always Use Braces & Indentation

Indentation and spacing are ignored by the compiler, but are very
important for developers
0 1
14
Use braces {} when using if/else statements, even if you have only a
single statement to execute

P
You/someone else may need to add another statement in the same
block

C M
if ( hoursWorkedThisWeek > 45 )
printf ( ”%d hours weekly is a busy schedule\n”, hoursWorkedThisWeek);
printf ( ”You deserve a good rest in the weekend\n”);

What does the above code output if hours worked is 35?

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 10 / 28


If/Else Statements Switch Statements Sum-Up

Example: Checking Whether The User Input is Valid


When the user specifies age, prompt a warning if input is not within
reasonable range

#include <stdio.h>

0 1
int main()
{

14
P
int age;
printf ( ”Enter your age: ” ) ;
scanf(”%d”, &age);

M
if ( age < 0 )
{
printf ( ” illegal input \n”) ;

C
}
else if ( age > 120 )
{
printf ( ” illegal input \n” ) ;
}
}

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 11 / 28


If/Else Statements Switch Statements Sum-Up

Good Practices - 3: Prevent Code Duplication

Previous code can be more concisely written as:

0 1
#include <stdio.h>

int main()

14
P
{
int age;
printf ( ”Enter your age: ” ) ;

M
scanf(”%d”, &age);
if ( age < 0 || age > 120)
{

}
}

C
printf ( ” illegal input \n” ) ;

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 12 / 28


If/Else Statements Switch Statements Sum-Up

Example: Preventing Division By Zero

What is wrong with the code below?

if ( scoreTotal/numScores > 0.90 )

0 1
{

}
// Do something

14
P
To prevent div by zero, we may use nested ifs, such that:

if ( numScores != 0)
{

C M
if ( scoreTotal/numScores > 0.90 )

}
// Do something

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 13 / 28


If/Else Statements Switch Statements Sum-Up

Good Practices - 4: Join Nested If’s, Smartly

We may write:

0 1
{
// Do something

14
if ( numScores !=0 && scoreTotal/numScores > 0.90 )

P
}

Does not increase computational overhead because:

C M
Evaluation stops as soon as value of test can be determined
Subexpressions are evaluated from left to the right
If numScores is 0, second part will not be evaluated

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 14 / 28


If/Else Statements Switch Statements Sum-Up

Switch-Case Statement

1
Switch is more efficient and elegant than if/else, if the behavior of the
program can be organized as a succession of separate cases
selected by an integer value
Syntax:
4 0
switch ( [OPERAND] )
{
case <condition1> :
< statement > ;
P 1
M
break;
case <condition2> :
< statement > ;
break;
default:
< statement > ;
break;
C
}
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 15 / 28
If/Else Statements Switch Statements Sum-Up

Switch Example
#include <stdio.h>

1
int main()
{

0
int k;
printf ( ”Enter a value between 1 and 3 : ”) ;

4
scanf ( ”%d” , &k);
switch(k)

1
{
case 1:

P
printf ( ”one!\n” ) ;
break;
case 2:
printf ( ”two!\n” ) ;
break;
case 3:
printf (
break;
default :
printf ( C M
”three!\ n”) ;

”Didn’t get it , did you?\n”) ;


break;
}
}
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 16 / 28
If/Else Statements Switch Statements Sum-Up

Example: Day of Week

0 1
14
Write a program that gets the number of the day and outputs the day

P
(“Monday” for 1, “Tuesday” for 2, ...).

C M
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 17 / 28
If/Else Statements Switch Statements Sum-Up

Day of Week - If/Else Solution

#include <stdio.h>

0 1
else if (day == 4)

4
printf ( ”Thursday\n” );
int main()
else if (day == 5)
{

1
printf ( ”Friday\n” ) ;
int day;
else if (day == 6)
printf ( ”Enter an index for one of the
printf ( ”Saturday\n” );

P
seven days of the week: ”) ;
else if (day == 7)
scanf( ”%d”, &day);
printf ( ”Sunday\n” );
if (day == 1)
else

M
printf ( ”Monday\n” );
printf ( ”Not a valid day
else if (day == 2)
index\n” ) ;
printf ( ”Tuesday\n” );

C
return 0;
else if (day == 3)
}
printf ( ”Wednesday\n” );

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 18 / 28


If/Else Statements Switch Statements Sum-Up

Day of Week - Switch/Case Solution

#include <stdio.h>

int main()
{
0 1
case 4:
printf ( ”Thursday”);
break;
case 5:
int day;
printf ( ”Enter an index for one of the
seven days of the week: ”) ;
scanf(”%d”, &day);

14 printf ( ”Friday” ) ;
break;
case 6:
printf ( ”Saturday”);

P
switch (day) break;
{ case 7:
case 1: printf ( ”Sunday”);

M
printf ( ”Monday”); break;
break; default :
case 2: printf ( ”Not a valid day
printf ( ”Tuesday”);
break;
case 3:
printf ( ”Wednesday”);
break;
C }
}
break;

return 0;
index”) ;

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 19 / 28


If/Else Statements Switch Statements Sum-Up

Enumerated Type

Used when an attribute can take a value from a limited set


We defined enum type by:
0 1
14
Naming (labeling) each possible value
Assigning each possible value an integer value (code)
Collect these values in an enumeration

P
Example: enum State { INIT, ACTIVE, IDLE };

M
This way, no need to know underlying values
Names of constants (indicating purpose) is sufficient

C
We could reverse above by giving explicit values:
enum State { IDLE=2, ACTIVE=1, INIT=0 };

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 20 / 28


If/Else Statements Switch Statements Sum-Up

enum Example (1/2)

#include <stdio.h>

0 1
int main()
{

14
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

enum Day today;


today = MONDAY;
P
M
printf ( ”%d\n”, today);

return(0) ;

C
}

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 21 / 28


If/Else Statements Switch Statements Sum-Up

enum Example (2/2)


Alternatively, you could declare a C type enum as follows:
#include <stdio.h>
int main()
{
0 1
typedef enum {
MONDAY,
TUESDAY,
WEDNESDAY,

14
P
THURSDAY,
FRIDAY,
SATURDAY,

M
SUNDAY
} Day;

}
enum Day today;
today = MONDAY;

C
printf ( ”%d\n”, today);

return(0) ;

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 22 / 28


If/Else Statements Switch Statements Sum-Up

enum Tips

If enum values are initialized, those are the values

If first enum is not initialized, its value is zero


0 1
4
Any other enum that is not initialized, its value is:

1
enum Foo { a, b, c = 10, d, e = 1, f , g = f + c };
value of previous enum+1

P
a = 0, b = 1, c = 10, d = 11, e = 1, f = 2, g = 12

M
Enum values are implicitly-convertible to integral types

C
enum color { RED, YELLOW, GREEN = 20, BLUE };
enum color col = RED;
int n = BLUE; // n == 21

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 23 / 28


If/Else Statements Switch Statements Sum-Up

Switch example with Enumerated Type

enum Color { RED, GREEN, BLUE };

0 1
4
enum Color r = RED;

switch(r )
{
case RED:
printf ( ”red\n”);
break;
case GREEN:
P 1
M
printf ( ”green\n”);
break;
case BLUE:

}
printf ( ”blue\n”) ;
break;

C
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 24 / 28
If/Else Statements Switch Statements Sum-Up

An Interactive Code on Broccoli ,

#include <stdio.h>

int main()
{
0 1
{
printf ( ”Do you like broccoli [y/n]>”) ;
scanf( ”%c”, &response);
if ( response == ’y’)

14
P
printf ( ”Good for you, broccoli is healthy\n”) ;
}
else

M
{
printf ( ”Well, there’s no accounting for taste ..\ n”) ;
}

}
return 0;

C
Above code has a bug...Can you see it?

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 25 / 28


If/Else Statements Switch Statements Sum-Up

Another Enum Example


int i = −1;

scanf(”%d”, &i) ;

switch( i )

0 1
printf ( ”Enter your choice: ” ;

enum Choice
{
{

14 case EASY:
printf ( ”Easy\n”;
break;

P
EASY = 1, case MEDIUM:
MEDIUM = 2, printf ( ”Medium\n”;
HARD = 3 break;

M
}; case HARD:
printf ( ”Hard\n”;
break;

C
default :
printf ( ” Invalid
Selection\n”;
break;
}

Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 26 / 28


If/Else Statements Switch Statements Sum-Up

Exercise - 1

0 1
14
(a) Write a C program that takes in the index of a month (1 for January, 2
for February, ...etc.) and displays how many days there are in that month.

P
(b) Now modify the above code, this time accounting for leap years (i.e.,
when February is 29 days instead of 28).

C M
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 27 / 28
If/Else Statements Switch Statements Sum-Up

Exercise - 2

0 1
14
Write a C program that gets two integer numbers from the user and checks
whether the first integer number is a multiple of the second integer number.
If it is, program will print “The first integer is a multiple of second integer”,

P
and “The first integer is not a multiple of second integer”, otherwise.
(Hint: Also check any divide by zero condition, and if necessary give

M
warning message that prints “Divide by zero error!”).

C
Ece Gelal Soyak · Bahcesehir University CMP1401 · Week 4 – Nov. 3, 2020 28 / 28

You might also like