0% found this document useful (0 votes)
70 views87 pages

Logical Statements and Selection Structures

The document discusses using logical statements and selection structures in C programming to solve problems involving conditional logic. It provides an example of using an if-else statement to write a program that determines if a number is positive or negative. The program takes a float variable as input, uses an if statement to check if it is greater than or equal to 0, and prints "positive" or "negative" depending on the result. Selection structures like if-else statements allow a program to choose alternative paths of execution based on certain conditions being true or false.

Uploaded by

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

Logical Statements and Selection Structures

The document discusses using logical statements and selection structures in C programming to solve problems involving conditional logic. It provides an example of using an if-else statement to write a program that determines if a number is positive or negative. The program takes a float variable as input, uses an if statement to check if it is greater than or equal to 0, and prints "positive" or "negative" depending on the result. Selection structures like if-else statements allow a program to choose alternative paths of execution based on certain conditions being true or false.

Uploaded by

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

Logical Statements and Selection

Structures
Car Loan Problem
• You have saved some amount to use as a down payment
on a car. Before beginning your car shopping, you decide to
write a program to help you figure out what your monthly
payment will be, given the car’s purchase price, the
monthly interest rate, and the time period over which you
will pay back the loan. The formula for calculating your
payment is
payment = iP / (1 - (1 + i)-n )
where P = principal (the amount you borrow)
i = monthly interest rate (1/12 of the annual rate)
n = total number of payments
Total number of payments is usually 36, 48, or 60 (months).
Program should then display the amount borrowed and the
monthly payment rounded to two decimal places.
Car Loan problem

Input Output Logic Involved

Purchase price, Amount Compute Monthly


down payment, borrowed and payment
annual interest EMI = i*P / (1 - (1 + i)-n )
rate and total
number of
payments
Algorithm for Car Loan Problem
• Read input such as Purchase price, down
payment, annual interest rate and total number
of payments from user
• amount_Borrowed = purchase_Price –
down_Payment
• EMI = i*P / (1 - (1 + i)-n )
• Print amount_Borrowed and EMI rounded to
two decimal places
Implementation in C
• Already learnt to read input and print values
• Learnt about arithmetic operators
• The expression has to find power of a value
• Similarly some problems may need to find
square root or log values, trigonometric values
etc...
• Have to learn to format output as it is specified
in problem to print two digits after decimal point
Library Functions
• Predefined Functions and Code Reuse
• A primary goal of software engineering is to
write error-free code.
• Code reuse - reusing program fragments that
have already been written and tested
whenever possible, is one way to accomplish
this goal.
Scanf and printf
• scanf and printf are also predefined functions
that are defined in the header file stdio.h

• scanf - returns the number of items


successfully read

• printf() - returns the number


of characters successfully written on the output
Example

On giving inputs as:


34
45
Output of Program is:
Scanf ret 2
Print ret 12
Formatting Output
• Additional arguments in pritnf to format as
requested by user:

• %[flags][width][.precision][length]specifier
Formatting Output
Flags Description
- Left-justify within the given field width; Right
justification is the default
+ Forces to precede the result with a plus or
minus sign (+ or -) even for positive numbers.
By default, only negative numbers are
preceded with a -ve sign.
(space) If no sign is going to be written, a blank space
is inserted before the value
0 Left-pads the number with zeroes (0) instead
of spaces, where padding is specified
Formatting Output
Width Description
(number) Minimum number of characters to be printed. If
the value to be printed is shorter than this number,
the result is padded with blank spaces.
.precision Description
.number precision specifies the minimum number of digits
to be written. If the value to be written is shorter
than this number, the result is padded with leading
zeros.
Formatting Output
length Description
h Argument is interpreted as a short int or unsigned
short int (only applies to integer specifiers: i, d, o,
u, x and X).
l argument is interpreted as a long int or unsigned
long int for integer specifiers (i, d, o, u, x and X),
and as a wide character or wide character string
for specifiers c and s.
L argument is interpreted as a long double (only
applies to floating point specifiers: e, E, f, g and G)
Example for Formatting
Output
Example for Formatting
Output
Example for Formatting
Output
printf(“:%s:\n”, “Hello, world!”); - nothing special happens
printf(“:%15s:\n”, “Hello, world!”); print 15 characters. If
string is smaller then “empty” positions will be filled with
“whitespace.”
printf(“:%.10s:\n”, “Hello, world!”); statement prints the
string, but print only 10 characters of the string.
printf(“:%-10s:\n”, “Hello, world!”); statement prints the
string, but prints at least 10 characters. If the string is
smaller “whitespace” is added at the end.
printf(“:%-15s:\n”, “Hello, world!”); statement prints
the string, but prints at least 15 characters. The string
in this case is shorter than the defined 15 character,
thus “whitespace” is added at the end (defined by the
minus sign.)
printf(“:%.15s:\n”, “Hello, world!”); statement prints
the string, but print only 15 characters of the string. In
this case the string is shorter than 15, thus the whole
string is printed.
To compile – gcc carloan.c –lm
./a.out
When input is:
400000
100000
10
36
Output is:
Loan Amount 300000.00
Monthly installment 9680.16
Nature of a Solution
• A solution may be classified into acidic, very
acidic, neutral, alkaline or very alkaline based
on its pH value. The nature of the solution is
given by the following table and determined
as shown in the figure:
pH value Nature of Solution
0 to 2 Very acidic
Greater than 2 and less than 7 Acidic
Equal to 7 Neutral
Greater than 7 and less than 12 Alkaline
Greater than 12 Very Alkaline
Nature of a Solution
pH problem

Input Output Alternate Ways


for Solution
pH value of Nature of Compare value
solution solution and make
decision
Algorithm

• Get the pH value of the solution from the user

• Write instructions that will make decision for


nature of solution as per details in the table

• Print the nature of the solution


Partial C code
#include<stdio.h>
void main()
{
float ph_Value; // Declare necessary variables
//Get the ph_Value from the user
scanf(“%d”,&ph_Value);
// Based on ph_Value make decision and print
}
Type of Instructions
• Instructions are organized into three kinds of
control structures to control execution flow:
– Sequence
– Selection
– Repetition
• A selection control structure chooses which
alternative to execute
Compound Statements
• Until now we have been using only sequential flow
• A compound statement, written as a group of
statements bracketed by { and } , is used to specify
sequential flow.
• {
statement 1 ;
statement 2 ;
...
statement n ;
}
Data Types
• No boolean and no String data type in C as in
Python
• C uses 0 and 1 values to indicate true and false
Defining Constants
• Similar like a variable declaration except the
value cannot be changed
• In declaration, const keyword is used before or
after type
• int const a = 1; const int a =2;
• It is usual to initialise a const with a value as it
cannot get a value any other way.
Preprocessor definition
• #define is another more flexible method to
define constants in a program
• #define TRUE 1
• #define FALSE 0
• #define NAME_SIZE 20
• Here TRUE, FALSE and NAME_SIZE are constant
Relational and Equality Operators
• Variable relational-operator variable
• Variable relational-operator constant
• Variable equality-operator variable
• Variable equality-operator constant
Relational and Equality Operators
Examples
Memory with Values
Logical Operators
• To form more complicated conditions or logical
expressions
• Three operators:
– And (&&)
– Or (||)
– Not(!)
Logical And
Logical Or
Logical Not
True/False Values
• For numbers all values except 0 is true
• For characters all values except ‘/0’ (Null
Character) is true
!flag

1 (true)
x + y / z <= 3.5

5.0 <= 3.5 is 0 (False)


!flag ||(y + z >= x-z)

1 ||1 = 1
Short Circuit Evaluation
• Stopping evaluation of a logical expression as
soon as its value can be determined is called
short-circuit evaluation

• Second part of ‘&&’ does not gets evaluated


when first part is evaluated as False

• Second part of ‘||’ does not gets evaluated when


first part is evaluated as true
Short Circuit Evaluation
• (num % div == 0) – Runtime error if div = 0

• But prevented when written as

• (div != 0 && (num % div == 0))


Comparing Characters
• We can also compare characters in C using the
relational and equality operators
Logical Assignment
• even = (n % 2 == 0);

• in_range = (n > -10 && n < 10);


• is_letter = ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z');

• Variable in_range gets 1 (true) if the value of n is


between −10 and 10 excluding the endpoints;

• is_letter gets 1 (true) if ch is an uppercase or a


lowercase letter.
When 'A‘ = 60 and 'B' =13
Syntax of if Statement Two
Alternatives
Form 1:
if ( condition )
statement T ;
Eg:
if (x > 0.0)
pos_prod = pos_prod * x;
If condition evaluates to true (a nonzero value), then
statement T is executed; otherwise, statement T is
skipped.
Syntax of if Statement Two
Alternatives
Form 2:

if ( condition )

statement T ;

else

statement F ;
Example
if (x >= 0.0)
printf("positive\n");
else
printf("negative\n");
If condition evaluates to true ( a nonzero value), then
statementT is executed and statementF is skipped;
otherwise, statementT is skipped and statementF is
executed.
Example 1
• #include<stdio.h>
void main()
{
float i=0.0f;
if(i)
printf("Yes");
else
printf(“No”);
}
Output 1
• No
Example 2
• #include<stdio.h>
void main()
{
int i=-3;
if(i)
printf("Yes");
else
printf(“No”);
}
Output 2
• Yes
Example 3
• #include<stdio.h>
void main()
{
char i =‘a’;
if(i)
printf("Yes");
else
printf(“No”);
}
Output 3
• Yes
Example 4
• #include<stdio.h>
void main()
{
int a = 2 , b=5;
if ((a==0)&&(b=1))
printf(“Hi”);
printf(“a is %d and b is %d”, a, b);
}
Output 4
• a is 2 and b = 5
Example 5
• #include<stdio.h>
void main()
{
int a = 2 , b=5;
if ((a==2)&&(b=1))
printf(“Hi”);
printf(“a is %d and b is %d”, a, b);
}
Output 5
• a is 2 and b = 1
Conditional Operator (Ternary Operator)

Syntax:
expression 1 ? expression 2 : expression 3

“if expression 1 is true (that is, if its value is non-zero), then the
value returned will be expression 2, otherwise the value returned
will be expression 3”.
Conditional Operator (Ternary Operator)

Example:
char a ;
int y ;
scanf ( "%c", &a ) ;
y = ( a >= 65 && a <= 90 ? 1 : 0 ) ;
Here 1 would be assigned to y if a >=65 && a <=90 evaluates to
true, otherwise 0 would be assigned
Conditional Operator (Ternary Operator)

• Not necessary that conditional operators should be used


only in arithmetic statements
Eg1:
int i ;
scanf ( "%d", &i ) ;
( i == 1 ? printf ( "Amit" ) : printf ( "All and sundry" ) )
Eg2:
char a = 'z' ;
printf ( "%c" , ( a >= 'a' ? a : '!' ) ) ;
Nested
• Conditional operators can be nested :
int big, a, b, c ;
big = ( a > b ? ( a > c ? 3: 4 ) : ( b > c ? 6: 8 ) ) ;

a>b?g=a:g=b;

Compiler Error

a>b?g=a:(g=b);
Partial C code of Isogram Problem Extended
/* Code to get the number of letters from user and print it*/
#include<stdio.h>
int main()
{
int num_Of_Letters; // Declaration of variable is mandatory in C
int num_Of_Words ; // Memory is allocated but not initialized
scanf(“%d”,&num_Of_Letters);
//If num_Of_Letters in less than or equal to zero then error
if (num_Of_Letters<=0)
printf(“Invalid input”);
Partial C code of Isogram Problem Extended
else
{
printf(“Number of letters is %d”,num_Of_Letters);
// multiply all numbers from n to 1 to find number of
// number of isogram words that can be formed
}
}
Nested if Statements
if (x >= 0.0)
printf("positive\n");
else
printf("negative\n");
If condition evaluates to true ( a nonzero value), then
statementT is executed and statementF is skipped;
otherwise, statementT is skipped and statementF is
executed.
Nested if Statements
if ( condition1 )
statement1
else if ( condition2 )
statement2
. . .
else if ( conditionn)
statementn
else
statemente
Example
/* increment num_pos, num_neg, or num_zero depending on x */

if (x > 0)

num_pos = num_pos + 1;

else if (x < 0)

num_neg = num_neg + 1;

else /* x equals 0 */

num_zero = num_zero + 1;
#define statements
• These are preprocessor directives that are used
define constants

• When a value is defined using #define, if there is a


change in value it is easier to make modification
Class of the Ship
• Each ship serial number begins with a letter
indicating the class of the ship. Write a program
that reads a ship’s first character of serial
number and displays the class of the ship.
Nested if Statements
Switch Statement
• Useful when the selection is based on the value
of a single variable or of a simple expression
(called the controlling expression)

• Value of this expression may be of type int or


char , but not of type double
Syntax of Switch Statement
switch ( controlling expression )
{
label set1
statements1
break;
label setn
statementsn
break;
default:
statementsd
}
Syntax of Switch Statement
• When a match between the value of the
controlling expression and a case label value is
found, the statements following the case label
are executed until a break statement is
encountered.
• Then the rest of the switch statement is
skipped.
• If no case label value matches the controlling
expression, the entire switch statement body is
skipped unless it contains a default label.
Output

BattleshipCruiserDestroyerFrigateNo match

When input is b
In Lab Practice Problem
The table below shows the normal boiling points of
several substances. Write a program that prompts the
user for the observed boiling point of a substance in °C
and identifies the substance if the observed boiling
point is within 5% of the expected boiling point. If the
data input is more than 5% higher or lower than any of
the boiling points in the table, the program should
output the message Substance unknown.
Substance Normal boiling point
(°C)
Water 100
Mercury 357
Copper 1187
Silver 2193
Gold 2660

You might also like