Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

Computing Fundamentals

Dr. Muhammad Yousaf Hamza


Decisions

Dr. Muhammad Yousaf Hamza


To decide even/odd
#include<stdio.h>
int main()
{
int num;
printf("Please enter an integer number:\n");
scanf("%d",&num);

if(num%2==0)
printf("\nThe number %d is an even number",num);

if(num%2!=0)
printf("\nThe number %d is an odd number",num);
getchar(); getchar();
return 0;
}
Dr. Muhammad Yousaf Hamza
To decide even/odd
#include<stdio.h>
int main()
{
int num;
printf("Please enter an integer number:\n");
scanf("%d",&num);

if(num%2==0) // Here only one check.


printf("\nThe number %d is an even number",num);

else
printf("\nThe number %d is an odd number",num);
getchar(); getchar();
return 0;
}
Dr. Muhammad Yousaf Hamza
Control Statements

Dr. Yousaf, PIEAS


Conditional Tasks
• if it is the condition, then I will do task A
Real Life Examples:
• if it is the condition, then I will do task A, else
(i.e. otherwise), I will do task B.
Real Life Examples:
• if it is the condition, then I will do task A,
else if it is the condition then I will do task B,
else I will do task C.
Real Life Examples:
Dr. Yousaf, PIEAS
Sequential execution
• Sequential execution
– Statements executed one after the other in the
order written
– Sequence structures: Built into C.
Programs executed sequentially by default

Dr. Yousaf, PIEAS


Control Structures
Transfer of control
– When the next statement executed is not the next
one in sequence

• Selection structures: C has three types:


if, if/else, and switch

• Repetition structures: C has three types:


for, while, and do/while (Later)

Dr. Yousaf, PIEAS


if statements

Dr. Yousaf, PIEAS


#include<stdio.h>
int main()
{
int age;
printf("Please enter your age in years:\n");
scanf("%d",&age);
if(age<=12)
printf("Please go to Child Specialist in Room 10\n");
printf(“Allah Hafiz");
getchar();
return 0;
}

Dr. Yousaf, PIEAS


The if Selection Structure
Selection structure:
• Used to choose among alternative courses of action
if(age<=12)
printf("Please go to Child Specialist in Room
10\n");
• If condition is true Print statement is executed and
program goes on to next statement
• If false, print statement is ignored and the
program goes onto the next statement
• Indenting makes programs easier to read

Dr. Yousaf, PIEAS


The if Selection Structure
if structure is a single-entry/single-exit
structure Diamond symbol
(decision symbol)
Indicates decision is
to be made contains
Print “Please go to an expression that
true Child Specialist in can be true or
age <= 12 false
Room 10”
Test the condition,
false
follow appropriate
path
Print “Allah Hafiz”

Dr. Yousaf, PIEAS


#include<stdio.h>
int main()
{
int age;
printf("Please enter your age in years\n");
scanf("%d",&age);
if(age<=12)
{
printf("Please go to Child Specialist in Room 10\n");
printf(“ Fee is Rupees 400/=\n");
} // Note the use of braces
printf(“Allah Hafiz");
getchar();
return 0;
}

Dr. Yousaf, PIEAS


The if Statement
• Form 1:
if (expression)
statement1;
next statement;

Dr. Yousaf, PIEAS


#include<stdio.h>
int main()
{
int age;
printf("Please enter your age in years\n");
scanf("%d",&age);
if(age<=12)
printf("Please go to Pediatrics in Room 10\n\n");
if(age>12)
printf("Please go to Medical Specialist in Room 15\n");
printf(“Allah Hafiz");
getchar();
return 0;
}

Dr. Yousaf, PIEAS


if else statements

Dr. Yousaf, PIEAS


#include<stdio.h>
int main()
{
int age;
printf("Please enter your age in years\n");
scanf("%d",&age);

if (age<=12)
printf("Please go to Child Specialist in Room 10\n\n");
else
printf("Please go to Medical Specialist in Room 15\n");

printf(“Allah Hafiz");
getchar();
return 0;
}
Dr. Yousaf, PIEAS
The if Statement
• Form 1:
if (expression)
statement1;
next statement;
• Form 2:
if (expression)
statement1;
else
statement2;

next statement;

Dr. Yousaf, PIEAS


The if/else Selection Structure
• if
– Only performs an action if the condition is true
• if/else
– Specifies an action to be performed both when the
condition is true and when it is false
• Once again
if (age<=12)
printf("Please go to Pediatrics in Room 10\n\n");
else
printf("Please go to Med. Spec. in Room 15\n");

– Note spacing/indentation conventions

Dr. Yousaf, PIEAS


The if/else Selection Structure
Flow chart of the if/else selection
structure

false true
age < = 12
print “15” print “10”

Dr. Yousaf, PIEAS


#include<stdio.h>
int main()
{
int age;
printf("Please enter your age in years\n");
scanf("%d",&age);
if (age<=12)
printf("Please go to Child Specialist in Room 10, Fee is
Rupees 400/=\n“);
if(age > 12 && age < 60 )
printf("Please go to Medical Specialist in Room 15, Fee is
Rupees 400/=\n");
if(age >= 60)
printf("Please go to Medical Specialist in Room 19, Fee is
Rupees 200/=\n");
getchar();
return 0; }

Dr. Yousaf, PIEAS


if else if statements

Dr. Yousaf, PIEAS


#include<stdio.h>
int main()
{
int age;
printf("Please enter your age in years\n");
scanf("%d",&age);
if (age<=12)
printf("Please go to Child Specialist in Room 10, Fee is Rupees
200/=\n");
else if(age < 60 )
printf("Please go to Medical Specialist in Room 15, Fee is
Rupees 400/=\n");
else
printf("Please go to Medical Specialist in Room 19, Fee is
Rupees 200/=\n");
getchar();
return 0;
}
Dr. Yousaf, PIEAS
The if/else Selection Structure
– Pseudocode for a nested if/else structure
If student’s grade is greater than or equal to 90
Print “A”
else
If student’s grade is greater than or equal to 80
Print “B”
else
If student’s grade is greater than or equal to 70
Print “C”
else
If student’s grade is greater than or equal to 60
Print “D”
else
Print “F”
Dr. Yousaf, PIEAS
The if else if example
#include <stdio.h>
int main ()
{
int x,y;
printf ("\nInput an integer value for x: ");
scanf ("%d", &x);
printf ("\nInput an integer value for y: ");
scanf ("%d",&y);
if (x==y)
printf ("x is equal to y\n");
else if (x > y)
printf ("x is greater than y\n");
else
printf ("x is smaller than y\n");
getchar(); return 0;
}
Dr. Yousaf, PIEAS
The if else examples
(1) Write a complete and efficient C program that would get
an integer from the user, if the number is greater than zero
print message “Positive” else if number is zero, print “Zero”
else print “Negative”.

(2) Get two integer numbers a and b from the user, if a is


greater than b print message “ A is greater”, if b is greater
print “B is greater”.

(3) Write a program that gets three numbers, a, b and c from


the user, the program should find and display the greatest of
the three numbers.

Dr. Yousaf, PIEAS


Relational Operators

Dr. Yousaf, PIEAS


Relational Operators
Relational operators allow you to compare
variables.
– They return a 1 value for true and a 0 for false.
Operator Symbol Example
Greater than > x > y
Less than < x< y
Greater than/equals >= x >= y
Less than/equals <= x <= y
Equals == x == y
Not equal != x != y NOT x = y

Dr. Yousaf, PIEAS


Relational Operators
Examples
• 5 > 4 is TRUE, 3 > 4 is FALSE
• 4 < 5 is TRUE, 4 < 4 is FALSE
• 4 >= 4 is TRUE, 3 >= 4 is FALSE
• 3 <= 4 is TRUE, 5 <= 4 is FALSE
• 5 == 5 is TRUE, 3==6 is FALSE
• 5!= 4 is TRUE, 5!=5 is FALSE

Dr. Yousaf, PIEAS


Logical Operators

Dr. Yousaf, PIEAS


#include<stdio.h>
int main()
{
int age;
printf("Please enter your age in years\n");
scanf("%d",&age);
if (age<=12)
printf("Please go to Child Specialist in Room 10, Fee is
Rupees 400/=\n“);
if(age > 12 && age < 60 )
printf("Please go to Medical Specialist in Room 15, Fee is
Rupees 400/=\n");
if(age >= 60)
printf("Please go to Medical Specialist in Room 19, Fee is
Rupees 200/=\n");
getchar();
return 0;
}
Dr. Yousaf, PIEAS
Logical Operators

• && AND

• || OR

• ! NOT

Dr. Yousaf, PIEAS


Logical Operators
• && ( logical AND )
– Returns true if both conditions are true
• || ( logical OR )
– Returns true if either of its conditions are true
• ! ( logical NOT, logical negation )
– Reverses the truth/falsity of its condition
– Unary operator, has one operand
• Useful as conditions in loops
Expression Result
true && false false
true || false true
!false true
Dr. Yousaf, PIEAS
Logical Operators
Examples
• If c=5 and d=2 then,((c==5) && (d>5)) returns false.

• If c=5 and d=2 then, ((c==5) || (d>5)) returns true.

• If c=5 then, !(c==5) returns false.

Dr. Yousaf, PIEAS


Be careful about Equality (==) and
Assignment (=) Operators
• Dangerous error
– Does not ordinarily cause syntax errors
if (x == 4 )
printf( “You are happy\n" );
• Checks value of x, if it is 4 then it prints You are happy
– Example, replacing == with =:
if ( x = 4 )
printf( “You are happy\n" );
• This always prints You are happy
• 4 is nonzero, so expression is always true.
• Logic error, not a syntax error
if ( x = 0 )
printf( “You are happy\n" );
What’s output?

Dr. Yousaf, PIEAS


Logical Operators
More Examples
Statement Expression

A and B are positive numbers A>0 && B>0

B and C are non zero numbers B!=0 && C!=0

B is an odd number Try It

A and B are greater than 20 or Try It


C and D are less than 100

Dr. Yousaf, PIEAS


Operator Precedence
Operator Precedence level
() 1
~, ++, --, unary - 2
*, /, % 3
+, - 4
<<, >> 5
<, <=, >, >= 6
==, != 7
& 8
^ 9
| 10
&& 11
|| 12
=, +=, -=, etc. 14

Dr. Yousaf, PIEAS


Conditional Operator

Dr. Yousaf, PIEAS


Conditional Operator
if ( a < b)
c = a + 5;
else
c = b + 8;

// We can do this in compact form as


c = a < b ? a + 5 : b + 8; //Ternary conditional operator (?:)
Evaluate first expression. If true, evaluate second,
otherwise evaluate third.

Dr. Yousaf, PIEAS


Conditional Operator
• Ternary conditional operator (?:)

– Takes three arguments (condition, value if true,


value if false)

– Our pseudocode could be written:


grade >= 60 ? printf( “Passed\n” ) :
printf( “Failed\n” );

Dr. Yousaf, PIEAS


Conditional Operator

• The conditional operator essentially allows you to embed an


“if” statement into an expression
• Generic Form
exp1 ? exp2 : exp3 if exp1 is true
value is exp2
(exp3 is not evaluated)
if exp1 is false,
value is exp3
(exp2 is not evaluated)
Dr. Yousaf, PIEAS
Conditional Operator
• Example:
z = (x > y) ? x : y;
• This is equivalent to:
if (x > y)
z = x;
else
z = y;

Dr. Yousaf, PIEAS


switch statement

Dr. Yousaf, PIEAS


#include <stdio.h>
int main()
{
int day;
printf("The day number 1 means Monday\n");
printf("Please enter the number of day. \n The number must be
any integer value from 1 to 7\n");
scanf("%d",&day);
if (day == 1)
printf("Monday\n");
else if (day == 2)
printf("Tuesday\n");
else if (day == 3)
printf("Wednesday\n");
// You may complete it yourself

Dr. Yousaf, PIEAS


The if/else Selection Structure
Nested if/else structures
• In previous example, the nested if/else structure is to
be used.
• Test for multiple cases by placing if/else selection
structures inside if/else selection structures
• Deep indentation usually not used in practice
• How can we solve this example more conveniently?

• Switch statement is a convenient way to code it.

Dr. Yousaf, PIEAS


Switch Statement
If you have a large decision tree, and all
the decisions depend on the value of the
same variable, you will probably want to
consider a switch statement instead of a
ladder of if...else or else if constructions.

Dr. Yousaf, PIEAS


// Example of switch statement
#include <stdio.h>
int main()
{
int day;
printf("The day number 1 means
Monday\n");
printf("Please enter the number of day. \n
The number must be any integer value from
1 to 7\n");
scanf("%d",&day);
// Contd. (next page)
Dr. Yousaf, PIEAS
switch(day)
{
case 1: // 1 is one of possible value of day and so on.
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
// please write cases 3 to 6 yourself
case 7:
printf("Sunday\n");
break;
default:
printf(“You eneterd a wtong number. The number must be an
integer value from 1 to 7\n");
break;
}
getchar(); return 0;
} Dr. Yousaf, PIEAS
• switch
– Useful when a variable or expression is tested for
all the values which can happen and different
actions are taken
• Format
– Series of case labels and an optional default case
switch ( value ) Learn the syntax!!!
{
case 1: Don't forget to add "break"
actions
case 2:
actions
default:
actions
}
– break; exits from structure
Dr. Yousaf, PIEAS
The switch Structure
• Flowchart of the switch structure
true case a break
case a
action(s)
false
true case b break
case b
false action(s)

.
.
.
true case z break
case z
false action(s)

default
action(s)
Dr. Yousaf, PIEAS
Switch Statement
• The expression used in a switch statement must have an integral or
character type.
• You can have any number of case statements within a switch. Each case
is followed by the value to be compared and a colon.
• The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, the flow of
control will fall through to subsequent cases until a break is reached.
• A switch statement can have an optional default case, which appears at
the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.

Dr. Muhammad Yousaf Hamza


Mathematical Functions

Dr. Yousaf, PIEAS


#include<stdio.h>
#include<math.h> // use of math.h
#define PI 3.14
int main()
{
float y;

y = sin(PI/2.0); // argument is in radian

printf("%f", y);
getchar();
return 0;
}
Output: 1.000000
Dr. Yousaf, PIEAS
// If given theta is in degree, then convert it first into radians.
#include<stdio.h>
#include<math.h> // use of math.h
#define PI 3.14
int main()
{
float y;
float theta_deg, theta_rad;
theta_deg = 90.0;
theta_rad = (PI/180)*theta_deg;
y = sin(theta_rad); // argument is in radian
printf("%f", y);
getchar(); return 0; }
Output: 1.000000

Dr. Yousaf, PIEAS


Dr. Yousaf, PIEAS
• log() ……..> natural log
• log10() …………> base-10 logarithm
Dr. Yousaf, PIEAS
Dr. Yousaf, PIEAS
#include<stdio.h> k = floor(15.2);
#include<math.h>
printf(" k = %d\n",k);
#define PI 3.14 // output: 15
j = ceil (15.2);
int main()
{ printf(" j = %d\n",j);
// output: 16
int k, j, r;
double x = 25.0, y, z; r = abs (-67);
printf(" r = %d\n",r);
y = sqrt(x); // output: 67
printf("y = %lf\n", y); // y = 5.000000 getchar();
return 0;
z = pow(y,3); // y^3, z = 125.000000
}
printf(" z = %lf\n", z);

Dr. Yousaf, PIEAS


Dr. Yousaf, PIEAS
Calculator using switch statement
Develop a C code that asks the user to select
the option for maths operation (+,-,*,/,%,sqrt
etc) then ask the user to enter the numbers and
display the result.

Do it Yourself

Dr. Yousaf, PIEAS


Examples
Write a program that prints 1 star as

Dr. Yousaf, PIEAS


Examples
Write a program that prints 1 star as
#include<stdio.h>

int main()
{
printf("*");
getchar();
return 0;
}

Dr. Yousaf, PIEAS


Examples
Write a program that prints 2 stars as

Dr. Yousaf, PIEAS


Examples
Write a program that prints 2 stars as
#include<stdio.h>

int main()
{
printf("*\n*");
getchar();
return 0;
}

Dr. Yousaf, PIEAS

You might also like