0% found this document useful (0 votes)
12 views83 pages

Unit 2.1 C Notes by Prof. Shahid Masood

Uploaded by

yrfhj
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)
12 views83 pages

Unit 2.1 C Notes by Prof. Shahid Masood

Uploaded by

yrfhj
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/ 83

CABSMJ-1001 [2024-25]

CABSMJ-1001
Problem Solving Using C
Unit - II
CABSMJ-1001 [2024-25]

2. Relational Operators
 Used for comparing the two values, such as price of two items.
 The result of relational operation is a boolean value 0 or 1
which indicates whether the operation is false or true.
 C supports following SIX relational operators:
Operator Description Example:
int a=10, b=20;
== is equal to: checks if the values (a == b)
of two operands are equal /* 0 (false) */
!= is not equal to: checks if values (a != b)
of two operands are not equal /* 1 (true) */
> is greater than: checks if the (a > b)
value of left operand is greater /* 0 (false) */
than the value of right operand
Contd...
CABSMJ-1001 [2024-25]

Relational Operators (contd…)


Operator Description Example:
int a=10,b=20;
< is less than: checks if the value (a < b)
of left operand is less than the /* expression is
value of right operand evaluated to 1 (true) */

>= is greater than or equal to: (a >= b)


checks if the value of left /* relational expression
operand is greater than or equal is evaluated to 0 (false)
to the value of right operand */
<= is less than or equal to: (a <= b)
checks if the value of left /* relational expression
operand is less than or equal to is evaluated to 1 (true)
the value of right operand */
CABSMJ-1001 [2024-25]

Example: C program to illustrate the use of Relational


Operators
/* relopex.c */
#include<stdio.h>
main()
{ int a=10;
int b=20;
printf("%d\n",(a==b)); /* 0 (false) */
printf("%d\n",(a!=b)); /* 1 (true) */
Output
printf("%d\n",(a<b)); /* 1 (true) */
printf("%d\n",(a>b)); /* 0 (false) */ 0
printf("%d\n",(a>=b)); /* 0 (false) */ 1
1
printf("%d\n",(a<=b)); /* 1 (true) */
0
}
1
CABSMJ-1001 [2024-25]

3. Logical Operators
 Used to combine two/more relational expressions together, so
that we can test two/more conditions.
 The result of logical operators is a boolean value 0 or 1.
 C supports following 3 logical operators:
Operator Description Example:
int a=10, b=20, c=30;
&& Logical AND: if both the operands (a>b && c==30)
are true (non-zero) then condition /* ( 0 && 1 ) is
becomes true (i.e. 1) evaluated to 0 */
|| Logical OR: if any one or both (a>b || c==30)
operands are true (non zero) then /* ( 0 || 1 ) is
condition becomes true (i.e. 1) evaluated to 1 */
! Logical NOT: used to reverse the !(a>b && c==30)
logical state of its operand /* !( 0 && 1 ) is
evaluated to 1Contd...
*/
CABSMJ-1001 [2024-25]

Example: C program to illustrate the use of Logical AND


and Logical OR Operator
/* logicalopex.c */
#include<stdio.h>
main()
{ int a=10;
int b=20;
int c=30;
printf("%d\n",(a>b && c==30)); /* ( 0 && 1 )  0 (false) */
printf("%d\n",(a>b || c==30)); /* ( 0 || 1 )  1 (true) */
printf("%d\n",(!(a>b && c==30))); /* !(0 && 1 ) 1 (true) */
}
Output
0
1
1
CABSMJ-1001 [2024-25]

4. Assignment Operators
 Used to assign the value of expression on its right to the
variable on its left.
 C supports following SIX assignment operators:
Operator Description Example
= Simple Assignment: c = a + b;
Assigns the value of expression on its
right to the variable on its left.

Shorthand Assignment Operators


+= Add AND Assignment: c += a;
Adds the value on its right to the current eqv. to:
value of the variable on its left and c = c + a;
assigns the result to the variable on its left.
Contd...
CABSMJ-1001 [2024-25]
Shorthand Assignment Operators (contd…)
Operator Description Example
-= Subtract AND Assignment: c -= a;
subtracts the value on its right from the eqv. to:
current value of the variable on its left and c = c – a;
assigns the result to the variable on its left.
*= Multiply AND Assignment: c *= a;
multiplies the value on its right with the eqv. to:
current value of the variable on its left and c = c * a;
assigns the result to the variable on its left.
/= Divide AND Assignment: c /= a;
divides the current value of the variable on eqv. to:
its left with the value on its right and assigns c = c / a;
the result to the variable on its left.
%= Modulus AND Assignment: It takes c %= a;
modulus using the current value of the eqv. to:
variable on its left with the value on its right c = c % a;
and assigns the result to the variable on its left.
CABSMJ-1001 [2024-25]

Example: C program to illustrate the use of Shorthand


Assignment Operators
/* assignmentopex.c */
#include<stdio.h>
main()
{ int a=10;
a+=3; /* a = 10+3 = 13*/
printf("a=%d\n",a);
a-=3; /* a = 13-3 = 10 */
printf("a=%d\n",a);
a*=2; /* a = 10*2 = 20 */ Output
printf("a=%d\n",a); a=13
a/=2; /* a = 20/2 = 10 */ a=10
printf("a=%d\n",a); a=20
a%=3; /* a = 10%3 = 1 */ a=10
printf("a=%d\n",a); a=1
}
CABSMJ-1001 [2024-25]

Advantages of Shorthand Assignment Operators

1. Variable appearing on LHS need not be repeated making it


easier to write.
2. Statement is more concise and easier to read.

3. More efficient.

For example:
a[i+2*x] = a[i+2*x] + y; /* add y to the array element */
can be written using shorthand assignment operator as:
a[i+2*x] += y; /* a[i+2*x] is evaluated only once. */
CABSMJ-1001 [2024-25]

5. Increment and Decrement Operators


 Increment (++) operator adds 1 while decrement (--) subtracts 1
from the operand.
 They are:
Operator Description Example: int a=10;
int b=20;
++ Increment operator
Postfix form: operand++ int c = (a++) + b;
First use the value of operand in printf("%d %d",a,c);
the expression & then increment it. output: 11 30
Prefix form: ++operand int c = (++a) + b;
First increment the operand and printf("%d %d",a,c);
then evaluate the rest of the output: 11 31
expression.
Contd...
CABSMJ-1001 [2024-25]

Increment & Decrement Operators (contd…)


Operator Description Example: int a=10;
int b=20;
-- Decrement operator
Postfix form: operand-- int c = (a--) + b;
First use the value of the printf("%d %d",a,c);
operand in the expression & output: 9 30
then decrement it.
Prefix form: --operand int c = (--a) + b;
First decrement the operand printf("%d %d",a,c);
and then evaluate the rest of output: 9 29
the expression.
Note: 1. -, ++ and -- are unary operators (performed Right to Left).
2. They have higher precedence than arithmetic operators.
CABSMJ-1001 [2024-25]

Example: C program to illustrate the Use of Increment


and Decrement Operators
/* incrdecropex.c */
#include<stdio.h>
main()
{ int a=10, b=10, c, d; /* unary operators are performed R to L. */
c = a++ + ++a; /* a=12, c=22 */
d = b-- + --b; /* b=8, d=18 */
printf("a=%d, c=%d\n",a,c);
printf("b=%d, d=%d\n",b,d);
}

Output
a=12, c=22
b=8, d=18
CABSMJ-1001 [2024-25]

6. Conditional (or Ternary) Operator


 It is the only operator in C that takes three operands.
 It is a condensed form of the if-else statement that also returns
a value.

General form:
value = exp1 ? exp2 : exp3;
e.g. bigger = x>y ? x : y;

Working of Conditional Operator


 First exp1 is evaluated.
 If its value is nonzero (true) then the value of exp2 is returned.
 If its value is zero (false) then the value of exp3 is returned.
CABSMJ-1001 [2024-25]

Example-1: C program to illustrate the use of


Conditional Operator
/* ternaryopex1.c */
#include<stdio.h>
main()
{ int a , b, c ,d;
a = 10;
c = (a == 1) ? 20 : 30;
printf("Value of c is: %d\n",c);
d = (a >= 10) ? a+40 : a*10;
printf("Value of d is: %d\n",d);
} Output
Value of c is : 30
Value of d is : 50
CABSMJ-1001 [2024-25]

Prob

Write a C program that finds biggest among three integer


numbers using Ternary Operator.
CABSMJ-1001 [2024-25]

/* C program to find biggest among three integers */


/* ternaryopex2.c */
#include<stdio.h>
main()
{ int a = 10;
int b = 30;
int c = 20, big;
big = (a > b) ? a : b;
big = (c > big) ? c : big;
printf("Biggest is: %d\n",big);
big = (a>b) ? ((a>c)? a : c ) : ((b>c)? b : c );
printf("Biggest is: %d\n",big);
} Output
Biggest is: 30
Biggest is: 30
CABSMJ-1001 [2024-25]
A B A&B A|B
7. Bitwise Operators 0 0 0 0
0 1 0 1
 Work on bits and perform bit by bit operation.
1 0 0 1
 Can be applied to integer types (long, int, short)
1 1 1 1
and char type.
 C supports following SIX bitwise operators: short type integers
Operator Description Example: A=60, B=13 ,C=-20
& Bitwise AND: the result of & A = 0000 0000 0011 1100
operation is 1 if both the B = 0000 0000 0000 1101
bits have a value 1; A&B= 0000 0000 0000 1100
otherwise it is 0. = 12
| Bitwise OR: the result of | A = 0000 0000 0011 1100
operation is 1 if at least one B = 0000 0000 0000 1101
of the bits has a value 1; A|B= 0000 0000 0011 1101
otherwise it is 0. = 61
Contd...
CABSMJ-1001 [2024-25]
A B A XOR B
Bitwise Operators (contd…) 0 0 0
0 1 1
1 0 1
1 1 0

Operator Description Example: A=60, B=13 ,C=-20


^ Bitwise Exclusive OR (XOR): A = 0000 0000 0011 1100
the result of ^ operation is 1 B = 0000 0000 0000 1101
if only one of the bits is 1; A^B= 0000 0000 0011 0001
otherwise it is 0. = 49
~ Bitwise Complement:
• Unary operator. A = 0000 0000 0011 1100
• Inverts all the bits of its ~A = 1111 1111 1100 0011
operand making every 0 a = -61
1 and every 1 a 0.
Contd...
CABSMJ-1001 [2024-25]
Operator Description Example: A=60, B=13 ,C=-20
<< Bitwise Left Shift: operand<<n A = 0000 0000 0011 1100
• all the bits in the operand A<<2= 0000 0000 1111 0000
are shifted to the left by n = 240
positions.
C = 1111 1111 1111 0110
• Right most n bits that are
C<<2= 1111 1111 1101 1000
vacated will be filled with
= -80 Filled with 0s
zeros.
>> Bitwise Right Shift: operand>>n A = 0000 0000 0011 1100
• all the bits in the operand A>>2= 0000 0000 0000 1111
are shifted to the right by = 15 +ve number filled with 0s
n positions.
• Left most n bits that are C = 1111 1111 1111 0110
vacated will be filled with C>>2= 1111 1111 1111 1101
0s if the number is +ve and = -5 -ve number filled with 1s
with 1s if it is -ve.
Contd...
CABSMJ-1001 [2024-25]

8. Special Operators
 C supports following TWO special operators:
(i). Comma operator
(ii). sizeof operator

(i). Comma Operator


 Used to link the related expressions together.
 Comma linked expressions are evaluated left-to-right and the value
of right-most expression is the value of the combined expression:
e.g. value = ( x=10, y=5, x+y ); /* value = 15 */
 Above statement first assigns 10 to x, then assigns 5 to y, and
finally assigns 15 to value.
 Since comma operator has lowest precedence of all operators,
hence parentheses are necessary.
CABSMJ-1001 [2024-25]

Example1: int x = (1, 2, 3); /* x = 3 */


First 1 becomes the result of the parenthesis, then 2 becomes the
result of the parenthesis and then 3 which is finally assigned to x.
Example2: int a, b, x, y, z;
b = (a=4, 5, 6) / (x=2,y=3,z=4); /* b = 6/4 = 1 */
6 becomes the value of the 1st parenthesis and 4 becomes the
value of the 2nd parenthesis.
Q. Predict output of the following C program:
#include<stdio.h>
main()
{ int x=10, y;
/* Using Comma as operator */ Output
y = (x++, ++x); 12
printf("%d",y);
}
CABSMJ-1001 [2024-25]

(ii). sizeof Operator

 It returns the number of bytes that its operand occupies in


the memory.
 Operand may be a data type, variable or constant.
 Examples: Output
printf("%d\n",sizeof(int)); 4
printf("%d\n",sizeof(float)); 4
printf("%d\n",sizeof(double)); 8
double
printf("%d\n",sizeof(45.67)); 8
long int
printf("%d"\n,sizeof(1234L)); 4
long double
printf("%d\n",sizeof(2400.5L)); 16
CABSMJ-1001 [2024-25]

C Expressions
and
Precedence of
Operators
CABSMJ-1001 [2024-25]

C Expressions

 A C expression:
 is a combination of operators and their operands
 which results in a single value of type char/ int/ float/ double
etc.

 The expressions are evaluated by performing one operation at


a time.

 The precedence and associativity of operators decide the


order of evaluation of individual operations.
CABSMJ-1001 [2024-25]

Types of C Expressions
Example
1. Arithmetic expressions 4 - 2 + 12/8
Consist of operands and operators. =4–2+1
=3
2. Relational or Conditional expressions ( x%2 == 0 )
• Used to compare two operands or the
conditional operator is used. ( a<b )
• The result can be either zero (false) or non- true/false
zero value (true). exp1 ? exp2 : exp3
3. Logical expressions ( x>10 || y<11)
Consist of logical operators (&&, ||, ! ) that
result in either a zero (false) or non-zero ( a>b && b>c)
value (true).
CABSMJ-1001 [2024-25]

Precedence of C Operators
 A C expression (containing different types of operators) is evaluated
based upon their operator precedence & associativity.
 Operator precedence determines the order:
 in which operators are performed in an expression containing
 more than one operators with different precedence.

 Operators Associativity
 It is used when two operators of same precedence appear in
an expression.
 It can be from left-to-right or right-to-left.
e.g. statement x = 5 + 6 * 2 / 3; assigns 9 to x (and not 22/3=7).
x=5+4
x=9
CABSMJ-1001 [2024-25]

Order of Precedence of C Operators and their Associativity


Category Operator Associativity
Highest Parentheses ( ) [ ] . (dot operator) Left to right
precedence Unary + - ++ -- ! ~ sizeof & * (pointer reference) Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Bitwise Shift >> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Lowest Comma , Left to right
CABSMJ-1001 [2024-25]

How Individual Operations are Performed in C


Expressions
1. When both the operands are of same type?

 then the result of arithmetic operation also would be of


the same type.
 For example:

3/2=1 /* result will be of int type */

3.0f / 2.0f = 1.5 /* result will be of float type */

3.0 / 2.0 = 1.5 /* result will be of double type (because by


default both the operands are of double type) */
CABSMJ-1001 [2024-25]

How Individual Operations are Performed in C


Expressions

2. When both the operands are of different types?


 then first the lower type is automatically
converted into the higher type and Implicit type
casting
 then arithmetic operation is performed to
produce the result of higher type.
CABSMJ-1001 [2024-25]

Type Casting
CABSMJ-1001 [2024-25]

Type Casting (or Type Conversion) in C

 Conversion of one data type into another is known as type


casting or type-conversion.

 In the evaluation of expressions:


 containing mixed basic data types,
 C supports two types of type casting (or type conversion):
1. Explicit type casting

2. Implicit type casting


CABSMJ-1001 [2024-25]

1. Explicit Type Casting (or Explicit Type Conversion)

 Explicit type casting is forced type casting:


 where type conversion is specified explicitly by the programmer
 through the use of the cast operator.

 It is good programming practice to use the cast operator


whenever type conversions are necessary in the expression.

General form: to perform the explicit type casting:


(data_type) expression;
where,
data_type: any valid C data type, and
expression: may be a constant, variable or expression.
CABSMJ-1001 [2024-25]

Explicit Type Casting (Contd…)

 In many situations, we need to perform forced type casting.

Example-1: int a = 15, b = 4;


float res; Fractional part is lost
res = a / b; /* res = 3.000000 */
If we want to have fractional part also, then we will have to
typecast either a or b to float type:
res = (float)a / b; /* res = 3.750000 */

Example-2: char c = 'A';


int x = (int)c; /* Explicit casting from char to int */
printf("%d",x); /* output: 65 */
CABSMJ-1001 [2024-25]

2. Implicit Type Casting (or Implicit Type Conversion)

 It is automatic type casting:


 performed by the C compiler
 while evaluating expressions containing mixed basic data
types.

 During expression evaluation, if the operands are of different types:


 the lower type is automatically converted to the higher
type before the operation proceeds, and called promotion or
 the result is of the higher type. widening conversion
called narrowing
Note: While assigning a higher type to a lower type in C, implicit
type casting with data loss is performed, e.g.
int a = 15.0/4; /* a = 3 ( .75 is lost ) */
CABSMJ-1001 [2024-25]

Implicit
Type Casting

There is a
chance of
No Loss in some Loss
data in data
Promotion or Narrowing
Widening conversion
conversion
CABSMJ-1001 [2024-25]

Example - Implicit Type Casting


int i=5, x;
float f=22.5; Order of evaluation
double d=12.5; of operators
long l=100;
1 3 2 4
x = l / i + i * f - d;

long float

long float

float

float

double
Data loss may happen double
int
CABSMJ-1001 [2024-25]

Mathematical
Library
Functions
CABSMJ-1001 [2024-25]

Mathematical Library Functions


 C supports many mathematical functions that:
 are used for performing basic numeric operations, such as
 exponential, logarithm, square root, trigonometric functions etc.

 These functions are defined in math.h header file:


Trigonometric
sin(x) Returns sine of x (x in radians)
cos(x) Returns cosine of x (x in radians)
tan(x) Returns tangent of x (x in radians)
asin(x) Returns arc sine of x (x in radians)
acos(x) Returns arc cosine of x (x in radians)
atan(x) Returns arc tangent of x (x in radians)

Contd...
CABSMJ-1001 [2024-25]

Hyperbolic
sinh(x) Returns hyperbolic sine of x (x in radians)
cosh(x) Returns hyperbolic cosine of x (x in radians)
tanh(x) Returns hyperbolic tangent of x (x in radians)
Other functions Raises value of arg x to the next int value and
ceil(x) returns it.
ceil(4.3) gives 5.0
floor(x) Decreases value of arg x to the previous int value
and returns it.
floor(4.8) gives 4.0
exp(x) Returns value of ex (e=2.71828 is base of natural
logarithm) e.g.
exp(2.0) gives 7.38905609893065
abs(x) Returns absolute value (+ve quantity) of integer
argument x. abs(-45) gives 45
Contd...
CABSMJ-1001 [2024-25]

fabs(x) Returns absolute value (+ve quantity) of argument


x (x is a floating point number).
fabs(-45.67) gives 45.670000
log(x) Returns natural logarithm value (base e) of arg x
(x>0). x can be integer or floating point type.
log(5.5) gives 1.704748
log10(x) Returns natural logarithm value (base 10) of arg x
(x>0). x can be integer or floating point type.
log10(5.5) gives 0.740363
pow(x, y) Returns value of xy. x and can be integer or
floating point type. pow(5,3) gives 125.000000
sqrt(x) Returns square root of argument x. x can be
integer or floating point type. sqrt(25) gives 5.000000
round(x) Returns the nearest integer value to the number x
(x can be short/int/long/float/double/long double).
CABSMJ-1001 [2024-25]

Example: C Program to illustrate the use of Math functions:


/* mathfnex.c */
Output
#include<stdio.h> The absolute value of b - a is: 8
#include<math.h> The a ^ b is: 100.000000
#define PI 3.14159 The sqrt of a is: 3.162278
main() The sin(10 degrees) is: 0.173648
{ int a = 10, b=2;
printf("The absolute value of b - a is: %d\n",abs(b-a));
printf("The a ^ b is: %f\n",pow(a,b));
printf("The sqrt of a is: %f\n",sqrt(a));
printf("The sin(%d degrees) is: %f\n",a,sin(a*(PI/180)));
}
CABSMJ-1001 [2024-25]

Prob
Write a C program that reads principle, time, rate and number of
times interest is compounded per year (P, T, R, N) from the user
and finds compound interest. Compound interest formula is:
R N*T
CI = P * 1 +  -P
N
Where,
P = initial principal amount
R = interest rate (if R = 5% then R = 5/100 = 0.05)
N = number of times interest is compounded per year
T = number of years

For example, if P = 1200, T = 2 years, R = 5.4% and N = 4


(quarterly compounded), then CI = 135.89
CABSMJ-1001 [2024-25]
/* cintcalc.c */
#include<stdio.h>
#include<math.h>
main()
{ float p, r, t, n, ci;
printf("Enter principal amount (p): ");
scanf("%f", &p);
printf("Enter time in year (t): ");
scanf("%f", &t);
printf("Enter interest rate in percent (r): ");
scanf("%f", &r);
r = r/100;
printf("Enter no. of times interest is compounded per year (n): ");
scanf("%f", &n);
ci = p * pow((1+r/n),n*t) - p;
printf("Compound Interest = %.2f", ci);
}
CABSMJ-1001 [2024-25]

Output
Enter principal amount (p): 5000
Enter time in year (t): 2
Enter interest rate in percent (r): 5
Enter no. of times interest is compounded per year (n): 4
Compound Interest = 522.43
CABSMJ-1001 [2024-25]

Decision Making
and
Branching
CABSMJ-1001 [2024-25]

Selection (or Decision) Control Statement-1

Statements Statement-2

 Program statements are normally executed Statement-3


in sequence.
Default mode of
 To develop powerful programs, we need to execution of
control the order in which various program instructions
statements are executed.
 To control the order of execution of program statements, C
supports following decision making statements:
(a). Simple if statement
(b). if … else statement
(c). If … else if … else (or Ladder if) statement
(d). Switch…case statement
(e). goto statement
CABSMJ-1001 [2024-25]

(a). Simple if statement


 An expression is tested:
 If it is true – statement block (inside curly braces) is executed
 otherwise - control jumps to the statement following if
statement.
 General form: True or
False expr?
T

if (expression)
F statement block
{
statement block;
} Statement following
Statement following if; if statement

 A zero value is treated as false, and


 A non-zero value is treated as true.
CABSMJ-1001 [2024-25]

Examples

int a = 10, b = 20; int a = 10, b = 20;


True True
if ( a < b ) if ( a - b )
{ {
printf("Condition is true\n"); printf("Condition is true\n");
} }
..... . .......

Note: If there is only one


statement in the body of the if int a = 10, b = 20;
statement, then curly braces if ( a - b )
may be omitted. printf("Condition is true\n");
........
CABSMJ-1001 [2024-25]

(b). if…else statement


 An expression is tested:
 If it is true – true-block statements are executed
 otherwise – false-block statements are executed.

 General form: True or


False
If (expression)
F T
{ true-block statements; expr?
}
else false-block stats true-block stats
{ false-block statements;
}
statement following if; Statement following
if
CABSMJ-1001 [2024-25]

Prob: Write a C program that reads an integer number and


finds whether it is odd or even number.
/* oddeven.c */
#include<stdio.h>
main()
{ int n;
printf("Enter an integer number: ");
scanf("%d",&n);
if ( n%2 == 0 )
printf("It is Even number"); /* single statement – so curly */
else /* braces may be omitted. */
printf("It is Odd number");
Output
}
Enter an integer number: 25
It is Odd number
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads the values of three sides of a


triangle and finds its area using Heron’s formula :

area = √ s(s–a)(s–b)(s–c), where s=(a+b+c)/2

Note: The sides a, b, c will form a triangle if the condition


((a+b)>c and (a+c)>b and (b+c)>a) is true.
CABSMJ-1001 [2024-25]

/* trianglearea.c */
#include<stdio.h> output:
#include<math.h> Enter 3 sides of triangle: 4 6 8
main() Area of Triangle = 11.618950
{ float a, b, c, s, area;
printf("Enter 3 sides of triangle: ");
scanf("%f %f %f",&a,&b,&c);
if ( (a+b)>c && (b+c)>a && (a+c)>b )
{ s = (a + b + c) / 2;
area = sqrt( s*(s - a) * (s - b) * (s - c) );
printf("Area of Triangle = %f\n",area);
}
else
printf("Three sides do not form a triangle\n");
}
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads four integers and finds smallest.

How to find smallest?


Suppose a, b, c, d
Example:
contain 4 int numbers
small=a; a b c d
if (b<small) true 40 30 10 20
small=b; / 10
/ 30
small = 40
if (c<small) true
small=c;
if (d<small) false
small=d;
CABSMJ-1001 [2024-25]

/* smallestin4.c */
#include<stdio.h>
main()
{ int a, b, c, d, small;
printf("Enter four integers\n");
scanf("%d %d %d %d",&a,&b,&c,&d);
if (a==b && b==c && c==d)
printf("Numbers are equal\n");
else
{ small=a;
if (b<small) small=b;
if (c<small) small=c;
if (d<small) small=d; Output
Enter four integers
printf("Smallest = %d\n",small);
40 30 10 20
}
Smallest = 10
}
CABSMJ-1001 [2024-25]

(c). If … else if … else (or Ladder if) statement

 Used to select one block of statements for execution out of


many alternatives.

 It contains multiple expressions and a corresponding block of


statements for each expression.

 The expression is tested from the top of the ladder


downwards. As soon as a condition is true, the corresponding
statement block is executed.

 If no expression is true, then the block of statements


contained in else part is executed.
CABSMJ-1001 [2024-25]

General form: True or


False
if (expr1) T
{ stat-block-1; expr1? stat-block-1
} F
else if (expr2) T
expr2? stat-block-2
{ stat-block-2;
} F
:
: T
exprn? stat-block-n
else if (exprn)
{ stat-block-n; F
} default-block
Optional
else
{ default-block; Statement following
} ladder if statement
statement following if;
CABSMJ-1001 [2024-25]

Prob

Write a C program that reads a character and tests whether it is


an alphabet or digit or some other character.
CABSMJ-1001 [2024-25]

/* chartest.c */
#include<stdio.h>
#include<ctype.h>
main()
{ char ch;
printf("Enter any character: ");
ch = getchar();
if ( isalpha(ch) )
printf("The character is an alphabet");
else if ( isdigit(ch) )
printf("The character is a digit");
else
printf("the character is other than alphabet and digit");
}
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads an integer number and tests


whether:
1. The number is divisible by 5 and 8 both
2. Or the number is divisible by 8 only
3. Or the number is divisible by 5 only
4. Or the number is divisible by none of them.
CABSMJ-1001 [2024-25]

/* divby5and8.c */
Output
#include<stdio.h>
Enter an integer number: 120
main( )
Divisible by both 5 and 8
{ int a;
printf("Enter an integer number: ");
scanf("%d",&a);
if (a%5 == 0 && a%8 == 0)
printf("Divisible by both 5 and 8");
else if (a%8 == 0)
printf("Divisible by 8 only"); Output
else if (a%5 == 0) Enter an integer number: 100
Divisible by 5 only
printf("Divisible by 5 only");
else
printf("Divisible by none"); Output
} Enter an integer number: 98
Divisible by none
CABSMJ-1001 [2024-25]

Prob:
Write a C program that reads the annual income as input and
calculates the Income tax.
Use below given rules for Income Tax calculation:

Income Income Tax


Income upto: 2,50,000 Nil

Income between: 2,50,001 – 5,00,000 10% of Income exceeding 2,50,000

Income between: 500,001 - 10,00,000 25000 + 20% of Income exceeding 5,00,000

Income above 10,00,000 125000 + 30% of Income exceeding 10,00,000


/* inctax.c */ CABSMJ-1001 [2024-25]
#include<stdio.h>
main() Output
{ float income, itax; Enter Annual Income: 350000
printf("Enter Annual Income: "); Income Tax = 10000.00
scanf("%f",&income);
if ( income<0 )
printf("Invalid input\n"); Output
else Enter Annual Income: 1200000
{ if ( income<=250000 ) Income Tax = 185000.00
itax = 0;
else if ( income>=250001 && income<=500000 )
itax = 0.10*(income-250000);
else if ( income>=500001 && income<=1000000 )
itax = 25000 + 0.20*(income-500000);
else
itax = 125000 + 0.30*(income-1000000);
printf("Income Tax = %.2f",itax);
}
}
start CABSMJ-1001 [2024-25]

Flowchart write "Enter Annual Income"


read income

T
income < 0
F
write "Invalid input"
income<= T
250000 itax = 0
F
itax=
income>=250001 and T
0.10*(income-
income<=500000
250000)
F
income>=500001 and T itax=
income<=1000000 25000 +
F
0.20*(income-
itax = 125000 + 0.30*(income-1000000) 500000)

write "Income Tax=",itax

stop
CABSMJ-1001 [2024-25]

(d). Switch…case statement

 Used to select one block of statements for execution out of


many alternatives.
 It contains an expression which is evaluated to int or char value.
 The expression is evaluated once and compared with the
values of each case constant.
 If there is a match, the corresponding statements after the
matching constant are executed. For example, if the value of
the expression is equal to constant2, statements after case
constant2: are executed until break is encountered.
 If there is no match, the statements contained in default
section are executed.
CABSMJ-1001 [2024-25]
int/char value
switch (expr)
{ case const1: expr= T
set of statements-1; const1? set of stat-1
break; F
case const2: expr= T
const2? set of stat-2
set of statements-2;
break; F
:
: expr= T
constn? set of stat-n
case constn:
set of statements-n; F

Optional
break; set of stat-d
default:
set of statements-d; statement following
} switch
statement following switch;
CABSMJ-1001 [2024-25]

Prob:

Write a C program that reads an integer n (in the range from 1 to


7) and outputs corresponding day of week.

Note: 1 means Sunday and 7 means Saturday.


#include<stdio.h> /* weekday.c */ CABSMJ-1001 [2024-25]
main()
{ int n;
printf("Enter an integer (range: 1-7): ");
scanf("%d",&n);
switch (n)
{ case 1: printf("Sunday");
break;
case 2: printf("Monday");
break;
case 3: printf("Tuesday");
break;
case 4: printf("Wednesday"); Output
break; Enter an integer (range: 1-7): 3
case 5: printf("Thursday"); Tuesday
break;
case 6: printf("Friday");
break;
case 7: printf("Saturday"); Output
break; Enter an integer (range: 1-7): 8
default:
printf("Invalid input");
Invalid input
}
}
CABSMJ-1001 [2024-25]
Start

Flowchart write “Enter an int (Range: 1 to 7)”


read n

T
n=1?
F write “Sunday”
n=2? T

F write “Monday”
T
n=3? T
F write “Tuesday”
T
n=4?
F write “Wednesday”
T
n=5?
F write “Thursday”
n=6? T

F write “Friday”
T
n=7?
F write “Saturday”

write “Invalid input”

Stop
CABSMJ-1001 [2024-25]

Why is ‘break’ used at the end of every case?


switch (expr)
 When switch statement encounters a { const1:
matching case, it executes all the set of statements-1;
cases below the matching case till the break;
end of the switch statement. const2:
set of statements-2;
 To avoid this, break is used at the end
break;
of every case so that: :
 when the matching case is constn:
executed, set of statements-n;
 the program control is transferred break;
to the statement following the default:
switch statement. set of statements-d;
}
 The break statement is optional. statement following switch;
CABSMJ-1001 [2024-25]
/* Example – if we don’t use break at the end of every case */
#include<stdio.h>
main()
{ int n;
printf("Enter an integer (range: 1-7): ");
scanf("%d",&n);
switch (n)
{ case 1: printf("Sunday\n");
case 2: printf("Monday\n");
case 3: printf("Tuesday\n"); Output
case 4: printf("Wednesday\n"); Enter an integer (range: 1-7): 3
case 5: printf("Thursday\n"); Tuesday
case 6: printf("Friday\n"); Wednesday
case 7: printf("Saturday\n"); Thursday
default: Friday
printf("Invalid input\n"); Saturday
} Invlaid input
}
CABSMJ-1001 [2024-25]

/* Predict the output of the following program */


#include<stdio.h>
main()
{ int x = 2;
switch (x)
{ case 1:
case 2:
case 3: printf("x>=1 and x<=3"); Executes if
break; x = 1 or 2 or 3
case 4:
case 5:
case 6: printf("x>=4 and x<=6"); Executes if
break; x = 4 or 5 or 6
default:
printf("x<1 or x>6"); Output
} x>=1 and x<=3
}
CABSMJ-1001 [2024-25]
......
goto label1;
(e). goto statement and Label
......
......
 The goto statement is used to transfer the label1:
control of the program to the specified labeled ......
statement in the same function. ......
 It provides an unconditional jump to the specified labeled
statement.
 When the goto statement is encountered, the control of the
program jumps to label: and starts executing the code.
Label:
 A label is simply an identifier (just like a variable name) followed
by a colon (:) that is applied to a statement.
 A statement label is meaningful only to a goto statement; in any
other context, a labeled statement is executed without regard to
the label.
CABSMJ-1001 [2024-25]

Prob:

Write a C program to perform simple arithmetic calculations.


The program should read two numbers and an arithmetic
operator ( +, -, *, / or ^ ) to be performed on them.
CABSMJ-1001 [2024-25]
/* arithcalc.c */
#include<stdio.h> Output:
#include<math.h> Enter the two numbers: 10 20
main() Enter the operator (+ - * / ^): *
{ double a, b, res=0.0;
char op;
printf("Enter the two numbers: ");
scanf("%lf %lf",&a,&b);
fflush(stdin); /* used to clear the stdin stream/buffer */
printf("Enter the operator (+ - * / ^): ");
scanf("%c",&op);
switch (op)
{ case '+': res = a + b;
break;
case '-': res = a - b;
break;
Contd...
CABSMJ-1001 [2024-25]

case '*': res = a * b;


break;
case '/': res = a / b;
break;
case '^': res = pow(a,b);
break;
default:
printf("Operator should be (+ - * / ^)");
goto end;
}
printf("Result = %lf\n",res);
end:
printf(""); /* empty string */ Output:
} Enter the two numbers: 10 20
Enter the operator (+ - * / ^): *
Result = 200.000000
CABSMJ-1001 [2024-25]

Note:

 Use of goto statement must be avoided because:


 it makes the flow of operations in the program zig-zag
 making it difficult to understand the program.
/* arithcalc2.c illustrates how to avoid the use of "goto"[2024-25]
CABSMJ-1001 */
#include<stdio.h>
#include<math.h>
main()
{ double a, b, res=0.0;
char op;
int iserror = 0; /* if invalid input, then its value will be 1 */
printf("Enter the two numbers: ");
scanf("%lf %lf",&a,&b);
fflush(stdin);
printf("Enter the operator (+ - * / ^): ");
scanf("%c",&op);
switch (op)
{ case '+': res = a + b;
break;
case '-': res = a - b;
break;
/* Contd… */
case '*': res = a * b; CABSMJ-1001 [2024-25]
break;
case '/': res = a / b;
break;
case '^': res = pow(a,b);
break; Output:
default: Enter the two numbers: 10 20.5
iserror = 1; Enter the operator (+ - * / ^): *
} Result = 205.000000
if (iserror==0)
printf("Result = %lf\n",res);
else
printf("Operator should be (+ - * / ^)");
} Output:
Enter the two numbers: 10 20.5
Enter the operator (+ - * / ^): x
Operator should be (+ - * / ^)
CABSMJ-1001 [2024-25]

Flowchart
CABSMJ-1001 [2024-25]

Nested if-else Statement


 It means using an if statement inside another if-else statement.
 It is used when we want to implement multilayer conditions
(condition inside the condition inside the condition and so on).
 C allows any number of nesting levels.
if (condition1) Inner if else is
Basic syntax of { if (condition2) executed only if
nested if-else: { /*code to be executed */ “condition1” is true
}
else
{ /*code to be executed */
}
}
else
{ /* code to be executed */
}
CABSMJ-1001 [2024-25]

Prob:
Write a C porgram that reads three integer numbers and finds
biggest using nested if-else statement.

How to
F (a>b) ? T
find the
biggest F T
F (b>c) ? T (a>c) ?
using
nested if-
else? bigc bigb bigc biga

write “Biggest=“,big
/* biggest.c illustrates the use of nested if-elseCABSMJ-1001
statement[2024-25]
*/
#include<stdio.h>
main()
{ int a, b, c, big;
printf("Enter 3 integer numbers\n");
scanf("%d %d %d",&a,&b,&c);
if ( a>b )
{ if ( a>c ) Inner if-else statement
big=a;
else
big=c;
}
else
{ if ( b>c )
big=b; Output:
else
Enter 3 integer numbers
big=c;
10 30 20
}
printf("biggest = %d",big);
biggest = 30
}

You might also like