0% found this document useful (0 votes)
64 views9 pages

3 and 4 - If - Else, Switch

This document discusses different types of decision making structures in programming, including IF-ELSE statements, compound IF-ELSE statements, relational operators, logical operators, and the SWITCH statement. Key points covered include: 1. The basic IF statement executes code if a condition is true, while IF-ELSE executes one code block if true and another if false. 2. Compound IF-ELSE checks multiple conditions using IF-ELSEIF-ELSE. 3. Relational operators like >, <, == compare values and result in true or false. 4. Logical operators like AND (&&) and OR (||) combine expressions. 5.

Uploaded by

Simon Rizvi
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)
64 views9 pages

3 and 4 - If - Else, Switch

This document discusses different types of decision making structures in programming, including IF-ELSE statements, compound IF-ELSE statements, relational operators, logical operators, and the SWITCH statement. Key points covered include: 1. The basic IF statement executes code if a condition is true, while IF-ELSE executes one code block if true and another if false. 2. Compound IF-ELSE checks multiple conditions using IF-ELSEIF-ELSE. 3. Relational operators like >, <, == compare values and result in true or false. 4. Logical operators like AND (&&) and OR (||) combine expressions. 5.

Uploaded by

Simon Rizvi
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/ 9

PRG 155 DECISION MAKING - IF - ELSE

Programs we have written so far consisted of a sequence of steps executed one after the
other. The program ended when all statements had been executed.

Now we expand our horizons and look at the decision making capability of the
computer. There are two kinds of BRANCHES.

1- Open Branch – The IF statement

Example:

This program checks to see if a number is positive.. If it's positive, the program prints
"Your number is positive." Then, for either case whether the number is positive or
negative, the program prints "Goodbye".

#include<stdio.h>
main()
{
int number;
printf(“Enter an integer”);
scanf(“%i”,&number);
if (number >= 0) /* check if number >= 0 */
puts(“Your number is positive."); /* print this only if number >= 0 */

puts(“Goodbye“); /* then always print this line */


getch();
}

Here is how the IF construct works.

if ( Evaluate this EXPRESSION to determine if it's TRUE or FALSE )


If the expression is TRUE, then execute THIS statement

And then execute THIS statement and those that follow in either case
________________________________________________________________________

Any time more than one line is executed in case the EXPRESSION is TRUE you
MUST use braces:

if(number < 0)
{ // THE BRACE COMES UNDER THE i
printf("The number is less than zero"); // TAB LINES INSIDE BRACES
printf("Since we have more than one line we must uses { }"); // TAB
} THE CLOSING BRACE COMES UNDER THE OPENING BRACE

The braces come under the ‘i’ of the if, and EVERYTING INSIDE BRACES MUST
BE TABBED!!!
PRG 155 Relational Operators

A Relational Operator is a symbol that indicates the relationship between two quantities
compared in an expression. the result of the comparison is either TRUE or FALSE.

The following are expressions with the results of the comparison.

Say a=5, b=6, number = 10

a>b FALSE Is a greater than b?

a<b TRUE Is a less than b?

a= =b FALSE Is a equal to b? NOTE: Use of = = here

a >= number FALSE Is A greater than or equal to number?

number >= b TRUE Is number greater than or equal to b?

number != b TRUE Is number not equal to b?

The program interprets TRUE as a 1 (or 1 as TRUE) and FALSE as a 0 (or 0 as FALSE).
You can demonstrate this in the following program. Try it in the lab or at home.

value = 5 > 6;
printf(“ %d”, value); // This will print?

value = 6>5;
printf(“\n %d ”,value); // This will print?

value = b>7;
prinft(“\n%i”,value); // This will print?

A list of Relational Operators:

> Greater than


>= Greater than or equal
< Less than
<= Less than or equal
== Equal to
!= Not equal to

The ORDER is important. >= works, => does NOT work.


Evaluate the Following

A = 5 B = 10 C = 5

Expression TRUE or FALSE Value of Expression


(1 or 0)

(A > B)

A==C

B != C

A <= B

C != B

A<=C

A!>B

_______________________________________________________________________

Logical Operators

Expressions may be combined using Logical Operators to form more complex


expressions using the AND and the OR Logical Operators.

The symbol for:

AND is && ( as if one ampersand were not enough)

and for :

OR it is | |
Here is how AND and OR work:

First Part Second Part First Part AND First Part OR


Second Part Second Part

TRUE TRUE TRUE TRUE


TRUE FALSE FALSE TRUE
FALSE TRUE FALSE TRUE
FALSE FALSE FALSE FALSE

Example:

int a = 5, b = 6;

if (a = = b | | a = = 0) /* if a is equal to b OR a is equal to zero */


puts(" a = 0 or a = b ");

Evaluate the following expressions:

A = 5 B = 10 C = 5

Expression TRUE or FALSE Value of Expression

(A > B) && C == 5

A = = C && B < C

B != ( C - A )

B <= A || C != 6

C != B || 6 = = 2*5

A = = C && B > 5

( A + C ) = = B || A = = 1
2- Closed Branch – The IF ....... ELSE statement

Example:

#include(stdio.h)
main()
{
int number;
system(“cls”);

printf(“Enter a positive integer => “);


scanf(“%d”, &number);

if(number >= 0)
{
printf(“Thank you for entering a positive number\n”);
printf("Remember to use braces with more than one line of code");
}

else
{
printf(" %d is not a positive number!!!!!!!!”, number);
printf(" Once again, braces are used ( because of this statement)");
}

printf(“Thank you for participating”); // prints this no matter what


getch();
}

Let’s examine how the IF ... ELSE construct works.

if ( Evaluate this EXPRESSION )


{
If the expression is TRUE, then execute THIS statement
}
else
{
If the expression is FALSE execute THIS statement
}

And then execute this STATEMENT and those that follow in either case
Compound If / Else

You can have a string of if/else statements when more than two conditions are to be
checked.

For example, you would use the compound if/else if the user has to select one of three
options in a menu. Then, depending on the option selected the appropriate instructions
are entered. I have shown the date input, calculation and output for option a. For options
b and c I've just printed a statement ot keep the example shorter.

Example:

#include<stdio.h>
main()
{
float radius, Area_Circle;
char selection;
puts(" Selection Menu ");
puts("");
puts("a. Calculate the area of a circle.");
puts("b. Calculate the area of a rectangle.");
puts("c. Calculate the are of right triangle.");

printf("\n Please enter your selection a, b or c => ");


scanf(" %c", &selection);

if( selection == 'a')


{
puts("This will calculate the area of a circle.");
printf(" Please enter the radius of the circle => ");
scanf(" %f", &radius);
Area_Circle = 3.14159 * radius * radius;
printf("\n The area is %.2f ", Area_Circle );
}
else if( selection == 'b')
{
puts("You selected b");
}
else if(selection == 'c')
puts("You selected c");
else
puts("Wrong selection – try again");
getch();
}
Say the user is asked to enter a number. The program then prints a number of statements
regarding the number. A series of if statements can be used in this program. Every if
statement is tested, one after the other.

main()
{
int number;
printf("Please enter a number");
scanf("%i", &number);

system(cls); // this command clears what’s on the screen

printf(" You entered %i", number);

if(number >0)
printf(" \n\tThe number is greater than zero")
if(number < 0)
printf(" \n\tThe number is negative")
if(number%2 == 0)
printf("\n\tThe number is even ");
if(number%2 == 1)
printf("\n\tThe number is odd");
if(number%3 == 0)
printf("\n\tThe number is divisible by 3");
if(number > 100)
printf("\n\tThe number is greater than 100);
getch();
}
Switch and Conditional Operator

The if / else construct can be written more efficiently using the switch function. The switch can
only be used with integers or characters NOT float.

#include<stdio.h>
main()
{
char input;
printf("Enter A, B or C ");
scanf("%c",&input);

/* START OF IF/ELSE */

puts("USING MULTIPLE IF/ELSE");

if (input == 'A')
puts(" Letter A");

else if (input == 'B')


puts(" Letter B");

else if (input == 'C')


printf(" Letter C");

else
printf(" You selected the wrong letter");

printf("\nEnd of IF/ELSE\n");

/************************************************************/
/*OR YOU CAN USE A SWITCH INSTEAD - START OF SWITCH */

puts("\nUSING SWITCH");

switch(input)
{
case 'A' : printf(" Letter A");
break;
case 'B' : printf(" Letter B");
break;
case 'C' : printf(" Letter C");
break;
default : printf(" You selected the wrong letter");
}
printf("\nEnd of SWITCH");

Note the use of break; to force program flow to jump to the end of the switch.
The case label ( the constant used after "case" used in the switch must be either a
character or an integer.

Conditional Operator

This is a shortcut way of writing an If / Else statement called the Conditional Operator.
This type of question will be on the final.

Example:

if (A>5)
printf("A is greater than 5);
else
printf("A is less then 5);

This could be written in one line as:

A>5 ? printf("A is greater than 5) : printf("A is less than 5);

Exercise:

Convert the following to Conditional Operator format.

int x, y
if (x>0)
y = x;
else
y = -x;

What does this program do?

Write the following programs:

1. Use a switch to help the user select between various coloured sweaters (R for red, G
for green and B for blue). Then print the colour he/she selected.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy