PPS Unit 1
PPS Unit 1
Algoritham
What is an Algorithm?
➢ The word Algorithm means ” A set of finite rules or instructions to be followed in
calculations or other problem-solving operations ”
➢ Or
➢ ” A procedure for solving a mathematical problem in a finite number of steps that
frequently involves recursive operations”.
➢ That can be understood by taking the example of cooking a new recipe. To cook a
new recipe, one reads the instructions and steps and executes them one by one, in the
given sequence. The result thus obtained is the new dish cooked perfectly.
➢ The Algorithm designed are language-independent, i.e. they are just plain instructions
that can be implemented in any language, and yet the output will be the same, as
expected.
Characteristics of an Algorithm
1|Page
➢ Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of
its steps should be clear in all aspects and must lead to only one meaning.
➢ Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined
inputs. It may or may not take input.
➢ Well-Defined Outputs: The algorithm must clearly define what output will be
yielded and it should be well-defined as well. It should take at least 1 output.
➢ Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time.
➢ Feasible: The algorithm must be simple, generic, and practical, such that it can be
executed with the available resources. It must not contain some future technology or
anything.
Properties of Algorithm:
➢ It should terminate after a finite time.
➢ It should produce at least one output.
➢ It should take zero or more input.
➢ It should be deterministic means giving the same output for the same input case.
➢ Every step in the algorithm must be effective i.e. every step should do some work.
Advantages of Algorithms:
➢ It is easy to understand.
➢ An algorithm is a step-wise representation of a solution to a given problem.
➢ In Algorithm the problem is broken down into smaller pieces or steps hence, it is
easier for the programmer to convert it into an actual program.
Disadvantages of Algorithms:
➢ Writing an algorithm takes a long time so it is time-consuming.
➢ Understanding complex logic through algorithms can be very difficult.
➢ Branching and Looping statements are difficult to show in Algorithms(imp).
2|Page
➢ The input to be taken to solve the problem.
➢ The output to be expected when the problem is solved.
➢ The solution to this problem, is within the given constraints.
➢ Then the algorithm is written with the help of the above parameters such that it solves
the problem.
Pseudo code
➢ Pseudo code is a combination of two words: Pseudo and Code. 'Pseudo' means
imitation and 'code' refer to instruction written in the programming language.
➢ Pseudo code is not a real programming code. It is the generic way of describing an
algorithm without using any specific programming language-related
➢ The pseudo code cannot be compiled. It cannot be executed and there are no real
formatting or syntax rules for writing pseudo codes.
➢ It is simply an important step in producing the final code.
Flowchart
What is a Flowchart?
➢ Flowchart is a graphical representation of an algorithm.
➢ Programmers often use it as a program-planning tool to solve a problem.
➢ It makes use of symbols which are connected among them to indicate the flow of
information and processing.
➢ The process of drawing a flowchart for an algorithm is known as “flowcharting”.
3|Page
FLOWCHART SYMBOLS
Name Symbol Purpose
Terminal / The terminator shows where your process begins
Terminator or ends. You can use words like ‘Start’, ‘Begin’,
‘End’ inside the terminator shape to make things
more obvious.
←↑→↓
Flow Lines Denotes the direction of logic flow in the program
4|Page
Circle Connection of flowchart on the same page. Used to
connect different parts of flowchart. Linkup
different parts of a flowchart.
Quadratic equations are the polynomial equations of degree 2 in one variable of type:
f(x) = ax2+ bx + c where a, b, c, ∈ R and a ≠ 0.
A quadratic equation will always have two roots. The nature of roots may be either real or
imaginary.
The term b2 - 4ac is known as the discriminant of a quadratic equation. It tells the nature of
the roots.
If discriminant > 0
If discriminant = 0
If discriminant < 0
5|Page
Algorithm to find all the roots of a quadratic equation:
Step 1. Start
Step 2. Read The Values a,b and c. / Read the coefficients of the equation, a, b and c from the
user.
Step 3. Calculate discriminant = (b * b) – (4 * a * c)
Step 4. If discriminant > 0:
4.1: Calculate root1 = ( -b + sqrt(discriminant)) / (2 * a)
4.2: Calculate root2 = ( -b - sqrt(discriminant)) / (2 * a)
4.3: Display “Roots are real and different”
4.4: Display root1 and root2
Step 5: Else if discriminant = 0:
5.1: Calculate root1 = -b / (2 *a)
5.2: root2 = root1
5.3: Display “Root are real and equal”
5.4: Display root1 and root2
Step 6. Else:
6.1: Calculate real = -b / (2 * a)
6.2:Calculate imaginary = sqrt(-discriminant) / (2 * a)
6.3: Display “Roots are imaginary”
6.4: Display real, “±” , imaginary, “i”
Step 7. Stop
6|Page
Flowchart to find all the roots of a quadratic equation:
7|Page
Q2. Algorithm for finding the minimum and maximum number of a given set.
Step 1: Begin
Step 2: Create an array of given size
Step 3: Store the Elements into the array
Step 4: Initialize max and min variables with element at index 0 and variable ‘i’ with 0.
Step 5: Repeat steps 6 until i<=size -1
Step 6: Compare array[i]>max :
6.1 if it is true then assigned array[i] to max.
Step 7: Compare array[i] < min :
7.1 if it is true then assigned array[i] to min.
Step 8: Display max and min values.
Step 9: Stop
8|Page
9|Page
Q3. Algorithm for finding if a number is prime number or not
Step 1: Start
Step 2: Initialize flag with true and variable i with 2
Step 3: Read a number i.e. n
Step 4: Repeat step5 until i<n
Step 5: If remainder of ‘n’ divided by ‘i’ is zero then gotostep 6 else gotostep7
Step 6: Change flag status to false and goto step 8
Step 7: Increment i by 1 and goto step4.
Step 8: If flag is true then display “n is prime “else display “ n is not prime”
Step 9: Stop
10 | P a g e
11 | P a g e
History of C Language
History of C language is interesting to know. Here we are going to discuss a brief history of
the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
12 | P a g e
Features of C Language
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
13 | P a g e
2) Machine Independent or Portable
Unlike assembly language, c programs can be executed on different machines with some
machine specific changes. Therefore, C is a machine independent language.
C is a structured programming language in the sense that we can break the program into
parts using functions. So, it is easy to understand and modify. Functions also provide code
reusability.
5) Rich Library
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.
10) Extensible
14 | P a g e
Structure of a C program
Section Description
Consists of the description of the program, programmer's name, and
Documentation
creation date. These are generally written in the form of comments.
All header files are included in this section which contains different
Link functions from the libraries. A copy of these header files is inserted into your
code before compilation.
Includes preprocessor directive, which contains symbolic constants.
Definition E.g.: #define allows us to use constants in our code. It replaces all the
constants with its value in the code.
Includes declaration of global variables(There are some variables that are
Global
used in more than one function. Such variables are called global variables),
Declaration
function declarations, static global variables, and functions.
For every C program, the execution starts from the main() function. It is
Main() Function
mandatory to include a main() function in every C program.
15 | P a g e
Section Description
Includes all user-defined functions (functions the user provides). They can
Subprograms contain the inbuilt functions and the function definitions declared in the
Global Declaration section. These are called in the main() function.
C Variables
➢ Variables are containers for storing data values. Or Variable is nothing but name
given to a memory location.
➢ A variable is a data name that may be used to store a data value. Unlike constants that
remain unchanged during the execution of a program. The variable may take different
values at different times during execution.
➢ A variable name can be chosen by the programmer in a meaningful way so as to
reflect its function or nature in the program.
➢ All C variables must be unique names. These unique names are called identifiers.
➢ Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
16 | P a g e
The general rules for naming variables are:
Example
Data Types
➢ A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
➢ A data type specifies how much memory allocated to that data.
➢ A data type defines a set of values and operations that can be performed on Those
values.
• C supports following data types
17 | P a g e
There are the following data types in C language.
The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals/modifiers.
Let's see the basic data types. Its size is given according to 32-bit architecture.
18 | P a g e
long long int %lld, %lli -(263 – 1) to 263 – 1 (It will be added by the 64
C99 standard)
unsigned long %llu 264 – 1 (It will be added by the C99 standard) 64
long int
Syntax-1
data-type var1, var2, …, varN;
var1, var2, …, varN are the names of the variables and they are separated by commas and end
with semicolon.
Eg. int count;
int number, total;
double ratio;
19 | P a g e
Syntax-2
data-type variableName = value;
Example
int myNum = 15; // myNum is 15
myNum = 10; // Now myNum is 10
The printf() and scanf() functions are used for input and output in C language. Both functions
are inbuilt library functions, defined in stdio.h (header file).
printf() function
The printf() function is used for output. It prints the given statement to the console.
Printf("message");
printf("format string",argument_list);
printf("message format string message", argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.
// Create variables
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
➢ To combine both text and a variable, separate them with a comma inside
the printf() function:
Example
int myNum = 5;
printf("My favorite number is: %d", myNum);
20 | P a g e
➢ To print different types in a single printf() function, you can use the following:
Example
int myNum = 5;
char myLetter = 'D';
printf("My number is %d and my letter is %c", myNum, myLetter);
scanf() function
The scanf() function is used for input. It reads the input data from the console.
scanf("format string",argument_list);
`
Example of input and output in C language that prints addition of Two numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int x, y, sum;
sum=x+y;
printf("Sum of two numbers: %d ", sum);
getch();
}
Output
21 | P a g e
C Programming Operators
➢ Operators are used to perform operations on variables and values.
➢ An operator is a symbol that tells the computer to perform certain mathematical or
logical manipulations.
➢ Operand is a data item on witch operation is performed.
➢ An Expression is a combination of operators and operands/values that reduces to
single value.
➢ C language is rich in built-in operators and provides the following types of operators
✓ Arithmetic Operators
i) Binary Arithmetic Operators
ii) Unary Arithmetic Operators
✓ Relational Operators
✓ Logical Operators
✓ Assignment Operators
✓ Conditional Operators
✓ Bitwise Operators
✓ Special / Misc Operators
Arithmetic Operators in C
➢ These operators are used for numerical calculations (or) to perform arithmetic
operations like addition.
➢ C provides 2 types of arithmetic operators
1.Binary
2.Unary
Binary Operators
➢ C provides 5 types of binary operators
➢ Binary Operators performs operations on two operands.
22 | P a g e
➢ Arithmetic Operator involving only integers operands is called “ Integer Arithmetic” .
➢ Arithmetic Operator involving only real operands is called “ Real Arithmetic” .
➢ When one of the operands is real and other is integer then expansion is called as “
Mixed – Mode arithmetic Expression.
➢ The modulo Operator (%) can't be used on floating point data
Unary Operators
➢ Unary Operators performs operations on one operand.
➢ Unary Minus(-) : The unary minus operator “-” negates a value
➢ Unary Increment & Decrement operators
Operator Description Example a=5 output
- Unary Minus (it negates a value_) -a -5
++ Increment (increases integer value by a++, ++a 6
one)
-- Decrement (Decreases integer value a--, --a 4
by 1)
23 | P a g e
second: a= a+1 i.e. z=10 and a=11
Decrement Operator: (- -)
➢ It is used to decrement the values of a variable by 1.
➢ 2 types of decrement operators are available :
a) pre decrement
b) post decrement
a)Pre-Decrement : Decrement operator is placed before the operand in pre-decrement and
the value is first decremented and then operation is performed on it.
Ex: a=10;
z = - - a;
first: a= a-1;
second: z=a ; i.e. a=9 and z=9.
b)Post-Decrement: Decrement operator is placed after the operand in post decrement and the
value is decremented after the operation is performed. i.e. operation is performed first then
value is decremented.
Ex: a=10;
z = a--;
first: z=a;
second: a= a-1; i.e. z=10 and a=9;
Postfix Increment p++ The program uses the current value of p and
Operator increases the value of p by 1.
Postfix Decrement P-- The program uses the current value of p and
Operator decreases the value of p by 1.
24 | P a g e
void main()
{
int a,b,c;
clrscr();
printf("Enter Two Numbers :");
scanf("%d%d",&a,&b);
c = a + b;
printf(" %d + %d then Value of c is %d\n", a,b,c );
c = a - b;
printf("%d - %d then Value of c is %d\n", a,b,c );
c = a * b;
printf("%d * %d then Value of c is %d\n", a,b,c );
c = a / b;
printf("%d / %d then Value of c is %d\n", a,b,c );
c = a % b;
printf("%d %% %d then Value of c is %d\n", a,b,c );
getch();
}
25 | P a g e
b=++a;
printf("a=%d \n",a);
printf("b=%d \n",b);
printf("post increment of a= %d is \n",a);
b=a++;
printf("a=%d \n",a);
printf("b=%d \n",b);
printf("pre decrement of a=%d is \n",a);
b=--a;
printf("a=%d \n",a);
printf("b=%d \n",b);
printf("post decrement of a= %d is \n",a);
b=a--;
printf("a=%d \n",a);
printf("b=%d \n",b);
getch();
}
Relational Operators
➢ The comparisons can be done with relational operators .
➢ C supports six relational operators .
➢ The output of relational expression is either one or zero (i.,e True or False).
➢ The following table shows all the relational operators supported by C.
To check if two operands are equal to each other. == (equal to) 5 == 3 would return to 0
If two operands are equal return 1 otherwise and 4 == 4 would return to
returns 0. 1
To check if two operands are unequal to each != ( not equal to) 8 != 5 would return to 1
other. If two operands are unequal return 1 6 != 6 would return to 0
otherwise returns 0.
To check if the operand value on the left is >(greater than) 5 > 8 would return to 0
comparatively greater than that of the operand 9 > 7 would return to 1
26 | P a g e
value on the right. If it is true it return 1 otherwise
0.
To check if the operand value on the left is < (less than) 2 < 0 would return to 0
comparatively smaller than that of the operand 4 < 8 would return to 1
value on the right. If it is true it return 1 otherwise
0.
To check if the operand value on the left is equal >= 1 >= 5 would return to be 0
to or comparatively greater than that of the (greater than or 4 >= 2 would return to be 1
operand value on the right. If it is true it return 1 equal to)
9 >= 9 would return to be 1
otherwise 0.
To check if the operand value on the left is equal <= 3 <= 6 would return to be 1
to or comparatively smaller than that of the (less than or 7 <= 3 would return to be 0
operand value on the right. If it is true it return 1 equal to)
2 <= 2 would return to be 1
otherwise 0.
Logical Operators
➢ C has three logical operators namely
- Logical AND (&&)
- Logical OR (||)
- Logical NOT(!)
➢ Logical Operators && and || used when we want to test more than one condition
27 | P a g e
➢ Logical expression will yield a value i.e. either one or zero (true or false)
➢ These are used to combine 2 (or) more expressions logically
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
&& Called Logical AND operator. If both the operands are non-zero, then (A && B)
the condition becomes true. is false.
! Called Logical NOT Operator. It is used to reverse the logical state of its !(A &&
operand. If a condition is true, then Logical NOT operator will make it B) is
false. true.
Truth Tables:
28 | P a g e
// Write a C Program that explain about Logical Operators
#include<stdio.h>
#include<conio.h>
void main ( )
{
int a,b;
clrscr();
printf("enter a and b values");
scanf("%d%d",&a,&b);
printf("a=%d,b=%d \n",a,b);
printf ("(a>=b)&&(a>b) is %d \n",(a>=b)&&(a>b));
printf ("(a<b)||(a<=b) is %d \n",(a<b)||(a<=b));
printf ("!(a>b) is %d\n",!(a>b));
getch();
}
Assignment Operators
➢ It is used to assign the result of an expression to a variable.
The following table lists the assignment operators supported by the C language –
+= Add AND assignment operator. It adds the right operand to the left C += A is
operand and assign the result to the left operand. equivalent to C
=C+A
29 | P a g e
*= Multiply AND assignment operator. It multiplies the right operand C *= A is
with the left operand and assigns the result to the left operand. equivalent to C
=C*A
Program
// Writa a program to understand all the assignment operators available in C.
#include <stdio.h>
#include<conio.h>
void main()
{
int a = 21;
int c ;
c = a;
30 | P a g e
clrscr();
printf("= Operator Example, Value of c = %d\n", c );
c += a;
printf("+= Operator Example, Value of c = %d\n", c );
c -= a;
printf("-= Operator Example, Value of c = %d\n", c );
c *= a;
printf("*= Operator Example, Value of c = %d\n", c );
c /= a;
printf(" /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf(" %= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf(" <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf(" >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("&= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf(" ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("|= Operator Example, Value of c = %d\n", c );
getch();
}
When you compile and execute the above program, it produces the following result −
= Operator Example, Value of c = 21
+= Operator Example, Value of c = 42
-= Operator Example, Value of c = 21
*= Operator Example, Value of c = 441
31 | P a g e
/= Operator Example, Value of c = 21
%= Operator Example, Value of c = 11
<<= Operator Example, Value of c = 44
>>= Operator Example, Value of c = 11
&= Operator Example, Value of c = 2
^= Operator Example, Value of c = 0
|= Operator Example, Value of c = 2
Bitwise Operators
➢ We use bitwise operators in c for performing the operations of bit-level on various
operands. It first converts the operators to bit-level, and after that, it performs various
calculations.Used to test the bits , shift the bits to right or left.
➢ C supports six bitwise operator
The truth tables for &, |, and ^ is as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Note:
➢ Bitwise operators may not be applied to float or double.
➢ Unlike other operators, bitwise operators operate on bits (i.e. on binary values of on
operand)
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
32 | P a g e
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60
and variable 'B' holds 13, then −
& (Bitwise AND) The result of the bitwise AND operation is 1 if both (A & B) = 12,
the bits have the value as 1; otherwise, the result is i.e., 0000
always 0. 1100
<< (Left Shift) Bitwise Left Shift Operator. The left operands value is
A << 2 = 240
moved left by the number of bits specified by the right
i.e., 1111
operand and empty bits on right side filled with zero’s.
0000
i.e. n=n<<x = n*(2^x)
>> (Right Shift) Bitwise Right Shift Operator. The left operands value is A >> 2 = 15
moved right by the number of bits specified by the right i.e., 0000
operand. i.e. n=n>>x = n/(2^x) 1111
33 | P a g e
Bitwise Left Shift <<
Example
a = 10 then a<<1=20
Try the following example to understand all the bitwise operators available in C −
Progarm
//Write a program to understand all the bitwise operators available in C.
#include <stdio.h>
#include<conio.h>
void main()
{
34 | P a g e
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
clrscr();
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c );
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c );
35 | P a g e
Conditional Operators(ternary operator )(?:)
➢ A ternary operator pair “ ? : ” is used to construct conditional expressions.
➢ A ternary operator has 3 expressions as follows
Expression 1 ? Expression 2 : Expression 3
➢ Expression 1 is condition, if it evaluates to true, Expression 2 will evaluate , if false
expression 3 evaluates
Example:
a=10 , b=5
x=(a>b)?a:b; then
x =10.
sizeof() Returns the size of a variable. sizeof(a), where a is integer, will return 2.
Progarm
//Write a program to understand all the miscellaneous operators available in C.
#include <stdio.h>
#include<conio.h>
void main()
{
int a = 4;
short b;
double c;
int* ptr;
clrscr();
/* example of sizeof operator */
printf("Line 1 - Size of variable a = %d\n", sizeof(a) );
36 | P a g e
printf("Line 2 - Size of variable b = %d\n", sizeof(b) );
printf("Line 3 - Size of variable c= %d\n", sizeof(c) );
37 | P a g e
Comma operator in C
In C comma (, ) can be used in two contexts:
1) Comma as an operator:
The comma operator (represented by the token, ) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type). The comma operator has the lowest precedence of any C operator
(or)
Eg,
q = (40, 50, 60, 70, 80, 90);
The value of q will be equivalent to 90. It is because the values 40, 50, 60, 70, 80 and
90 are enclosed in the form of braces () and these braces have a higher priority, as compared
to the equal to (=) assignment operator. Thus, when we provide the variable q with multiple
values (using the comma operator and the braces), then the program will consider the right-
most value as the result/output of this expression. Thus, the program variable q will be
assigned with the value of 90.
/* comma as an operator */
int i = (5, 10); /* 10 is assigned to i*/
int j = (f1(), f2()); /* f1() is called (evaluated) first followed by f2().
The returned value of f2() is assigned to j */
2) Comma as a separator:
When we want to declare multiple numbers of variables in any program and provide different
arguments in any function, we use the comma in the form of a separator in the program.
Ex:
int x, y, z;/* comma as a separator */
int a = 1, b = 2;
void fun(x, y);
1. What would be the output obtained out of the program mentioned below?
main()
{
int g = 83;
int h = (g++, ++g);
printf(“%d”, h);
}
Answer : h = 85
38 | P a g e
// PROGRAM 1
#include <stdio.h>
int main()
{
int x = 10;
int y = 15;
clrscr();
printf(“%d”,(x,y));
getch();
return 0;
}
Output: 15
39 | P a g e
Introduction to Expressions
• An expression is sequence of operands and operators that reduces to single value.
• An operand is a data item on which an operation is performed.
• An operator indicates an operation to be performed on data
• Ex:10+5 ,this is an expression whose value is 15
Types of Expression
• Simple Expression: Expression which contain single operator is called as simple
expression
Ex: 11+5; -a
• Complex Expression: Expression which contain more than one operator is called as
complex expression.
Ex:2*3+5-1
Operators Precedence in C
➢ Precedence : The order in which the operators in a complex expression are evaluated
is determined by a set of priorities known as precedence.
i) Left to Right associativity evaluates the expression by starting on left and moving to the right
side of expression.
ii) Right to Left associativity evaluates the expression by starting on right and moving to the
left side of expression.
40 | P a g e
41 | P a g e
Rules for Evaluation of Expression
✓ First, parenthesized sub-expression from left to right are evaluated
✓ If parentheses are nested, the evaluation begins with the innermost sub-expression.
✓ The precedence rule is applied in find the order of operators in evaluating sub expression
✓ The associativity rule is applied when two or more operators have same precedence in sub
expression.
✓ Arithmetic expressions are evaluated from left to right using the rules of precedence
✓ When parenthesis are used, the expression with parenthesis assume highest priority.
Side effect
• A side effect is an action that results from the evaluation of a expression..
Ex: int x=3;
x = x+ 4;
• here initial value of x is 3 and the value of the expression on right side of assignment is 7
(ie 3+4).
• so the final value of x is 7 this is side effect.
Ex 1: evaluate 2+3*4
Since * has high precedence than the + so multiplication is performed first than
followed by addition
i.e. 2+ 12= 14
42 | P a g e
Ex 3: evaluate 3 * 8 / 4 % 4 * 5
• In the given expression all three operators(* / %) are belonging to same precedence and
their associativity is from left to right.
• so given expression should be evaluated from left to right as follows
• ((((3*8)/4)%4)*5)
• (((24/4)%4)*5)
• ((6%4)*5)
• 2*5
• 10
43 | P a g e
• --a*7/2 -6*b // post increment takes place after evaluating expression i.e after these ‘c’
value is 6
• 2*7/2 -6 *b // --a is pre decrement so a is decreased by 1
In the above expression operators * / are having same and higher precedence than’ –‘
and their associativity is left to right so
• (2*7)/2 –6 *b
• 14/2 – 6*b
• 7- 6 *4 // in this expression * has high precedence than – so it is evaluate first
• 7-24
• - 17 Side effects: a=2 ;b=4 and c=6
Program
#include <stdio.h>
#include<conio.h>
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
clrscr();
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = a + (b * c) / d; // 20 + (150/5)
44 | P a g e
printf("Value of a + (b * c) / d is : %d\n" , e );
getc();
return 0;
}
When you compile and execute the above program, it produces the following result −
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
TYPE CONVERSIONS
• Converting one data type into another is the concept of type conversion
• Type conversion is of two types
1. Implicit type conversion / Automatic type conversion
2. Explicit type conversion
45 | P a g e
The sequence of rules that are applied while implicit type conversion is as follows:
• All short and char are automatically converted to int; then
• if one of the operands is long double, the other will be converted to long double and the
result will be long double.
• else , if one of the operands is double, the other will be converted to double and the result
will be double.
• else , if one of the operands is float, the other will be converted to float and the result will
be float
• else , if one of the operands is unsigned long int, the other will be converted to unsigned
long int and the result will be unsigned long int.
• else , if one of the operands is long int, the other will be converted to unsigned int then
a) If unsigned int can be converted to long int, the unsigned int operand will be
converted as such and the result will be long int.
b) Else, both operands will be converted to unsigned long int and the result will be
unsigned long int.
• else , if one of the operands is long int, the other will be converted to long int and the
result will be long int.
• else , if one of the operands is unsigned int, the other will be converted to unsigned int
and the result will be unsigned int.
46 | P a g e
However the following changes are introduced during the final assignment.
• Float to int causes truncation of the fractional part.
• Double to float causes rounding of digits.
• Long int to int causes dropping of the excess higher order bits.
Example for Implicit conversion :
int i,x;
float f;
double d;
long int l;
X=l/i+i-f-d
EXAMPLE PROGRAM
#include<stdio.h>
#include<conio.h>
int main()
{
int x=10;
char y = 'a'; // character c
clrscr();
// y implicitly converted to int. ASCII. value of 'a' is 97
47 | P a g e
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;
• Here the user can type cast the result to make it of a particular data type.
syntax in C:
(data_type) expression
where, data_type is any valid c data type, and expression may be constant, variable or
expression.
Program-1
#include<stdio.h>
#include<conio.h>
#include <stdio.h>
main() {
48 | P a g e
Program-2
#include <stdio.h>
#include<conio.h>
main()
{ int i = 17;
char c = 'c'; /* ascii value is 99 */
int sum;
clrscr();
sum = i + c;
printf("Value of sum : %d\n", sum );
getch();
}
Output:
Value of sum : 116
1. Runtime Errors
C runtime errors are those errors that occur during the execution of a c program and generally
occur due to some illegal operation performed in the program.
Examples
• Dividing a number by zero
• Trying to open a file which is not created
• Lack of free memory space
• When you instruct your computer to find logarithm of a negative number.
• When you instruct your computer to find the square root of a negative integer.
49 | P a g e
2. Compile Errors:
• Compile errors are those errors that occur at the time of compilation of the program.
• C compile errors may be further classified as:
o Syntax Errors
o Semantic Errors
Syntax Errors:
• A collection of rules for writing programs in a programming language is known as syntax.
• When the rules of the c programming language are not followed, the compiler will show
syntax errors.
• A program containing syntax error cannot be compiled successfully.
For example
1. int a,b:
2. A variable is used without declaration.
1. printf(“Hello,world”) – error in syntax (semicolon missing)
Semantic Errors
• Semantic errors are reported by the compiler when the statements written in the c program
are not meaningful to the compiler.
• For example, consider the statement,
• b+c=a;
3.Logical Errors
• Logical errors are the errors in the output of the program.
• The presence of logical errors leads to undesired or incorrect output and are caused due to
error in the logic applied in the program.
• logical errors could not be detected by the compiler, and thus, programmers have to check
the entire coding of a c program line by line.
50 | P a g e
CONDITIONAL BRANCHING / DECISION MEAKING & LOOPS
We have seen that a C program is a set of statements which are normally executive
sequentially in the order in which they are appear. This happens when no options or no
repetitions of certain calculations are necessary.
However, in practice, we have a number of situations where we may have to change
the order of execution of statements based on certain conditions, or repeat a group of
statements until certain specified conditions are met. This involves a kind of decision making
to see whether a particular condition has occurred or not and then direct the computer to
execute such a statement accordingly.
CONDITIONAL BRANCHING/ DECISION MAKING
In C, sequence of statements can be grouped together by placing them in group Called as
statement block
Conditional Statements in C programming are used to make decisions based on the
conditions.
Conditional statements execute sequentially when there is no condition around the
statements.
If you put some condition for a block of statements, the execution flow may change based on
the result evaluated by the condition. This process is called decision making in 'C.'
It is also called as branching as a program decides which statement to execute based on the
result of the evaluated condition.
They are
1. simple – if statement
2. if – else statement
3. nested – if else statement
4. Else – if ladder
5. Switch statement
51 | P a g e
Simple – if statement
• This statement is also called as one way statement.
• ‘if’ keyword is used to execute a set of statements when the logical condition is true.
Syntax :
if (condition)
{
Statement (s)
}
Next_Statement;
Working of ‘simple if’ statement
The statement(s) inside the if block are executed only when condition is true, otherwise not.
• If we want to execute only one statement when condition is true, then braces ({}) can
be removed. In general, we should not omit the braces even if, there is a single
statement to execute.
• When the condition is true the braces ({}) are required to execute more than one
statement.
52 | P a g e
#include <stdio.h>
#include<conio.h>
int main()
{
int x, y;
clrscr();
printf("enter the value of x:");
scanf("%d", &x);
printf("enter the value of y:");
scanf("%d", &y);
if (x>y)
{
printf("x is greater than y\n");
}
if (x<y)
{
printf("x is less than y\n");
}
if (x==y)
{
printf("x is equal to y\n");
}
printf("End of Program");
getch();
return 0;
}
Output:
enter the value of x:20
enter the value of y:20
x is equal to y
53 | P a g e
if-else statement
If-else statement takes care of true as well as false conditions. ‘true block’ is executed, when
the condition is true and ‘false block’ (or) ‘else block’ is executed, when the condition is
false.
Syntax
if (condition)
{
True block statement(s) / Statement2
}else
{
False block statement(s) / Statement1
}
Next_Statement;
Flow Chart:
54 | P a g e
• If condition is false, it enter into else block, which is false block based on
if condition, executes that else block and exist that else block and go to
Next Statement.
#include <stdio.h>
#include<conio.h>
int main()
{
int age;
clrscr();
printf("Enter your age:");
scanf("%d",&age);
if(age >=18)
{
/* This statement will only execute if the above condition (age>=18)
returns true */
printf("You are eligible for voting");
}
else
{
/* This statement will only execute if the condition specified in the "if"
returns false. */
printf("You are not eligible for voting");
}
getch();
return 0;
}
Output:
Enter your age:14
You are not eligible for voting
55 | P a g e
Nested If..else statement
When an if else statement is present inside the body of another “if” or “else”
then this is called nested if else.
56 | P a g e
Flow Chart:
#include <stdio.h>
#include<conio.h>
int main()
{
int var1, var2;
clrscr();
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to var2\n"); //Nested if else
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
57 | P a g e
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
getch();
return 0;
}
Output:
Input the value of var1:12
Input the value of var2:21
var1 is not equal to var2
var2 is greater than var1
58 | P a g e
Syntax of else..if statement:
if (condition1)
{
Stmt1; //These statements would execute if the condition1 is true
}
else if(condition2)
{
Stmt2; //These statements would execute if the condition2 is true
}
else if (condition3)
{
Stmt3; //These statements would execute if the condition3 is true
}
.
.
else
{
Default Stmt; //These statements would execute if all the conditions return
false.
}
Next_Statemet;
Working else-if ladder:
Else if ladder, the conditions are evaluated from top to bottom.
As soon as a true condition is found, the statement associated with it is
executed and the control is transferred to the “Next Statement”.
When all the conditions become false, then the final else containing the
“Default Statement” will be executed and the control is transferred to the “Next
Statement”.
59 | P a g e
Flow Chart:
#include<stdio.h>
#include<conio.h>
void main (){
int a,b,c,d;
clrscr();
printf("Enter the values of a,b,c,d: ");
scanf("%d%d%d%d",&a,&b,&c,&d);
if(a>b && a>c && a>d){
printf("%d is the largest",a);
}else if(b>c && b>a && b>d){
printf("%d is the largest",b);
}else if(c>d && c>a && c>b){
printf("%d is the largest",c);
}else{
printf("%d is the largest",d);
}
60 | P a g e
getch();
}
Output
switch statement
C has a built-in multiway decision statement known as a Switch. It is a
keyword.
It is used to select one among multiple decisions. ‘switch’ successively tests a
value against a list of integers (or) character constant. When a match is found,
the statement (or) statements associated with that value are executed.
Syntax
The syntax is given below −
switch (expression){
case value1 : stmt1;
break;
case value2 : stmt2;
break;
------
default : stmt – x;
}
61 | P a g e
Working of switch statement:
The switch is having “expression”, It must be reduced to Boolean, Integer or
character. Each and every option is known as case(keyword) and case is having
value. The value is any valid Integer constant or integer expression or
Character constant. And must be followed by the colon (:). Each and every case
ends with break (Keyword) statement. The last case is default(keyword) case.
This is also ends with break statement.
The switch statement tests the value of a given variable or expression match
with a list of case values and when a matche is found, a block of statements
associated with that case is executed then the controller goes to the “Next
statement”. If any match is not found, The default statement block is executed
then controller goes to “Next Statement”.
Flow Chart
62 | P a g e
Break statement in Switch Case:
Break statements are useful when you want your program-flow to come out of
the switch body. Whenever a break statement is encountered in the switch body,
the control comes out of the switch case statement.
Why didn’t I use break statement after default?
The control would itself come out of the switch after default so I didn’t use it,
however if you want to use the break after default then you can use it, there is
no harm in doing that.
Write a C program, which takes two integer operands and one operator from the user,
performs the operation and then prints the result. (Consider the operators +,-,*, /, %
and use Switch Statement)
63 | P a g e
/* Write a C program, which takes two integer operands and one operator from
the user, performs the operation and then prints
the result. (Consider the operators +,-,*, /, % and use Switch Statement)*/
#include <stdio.h>
#include<conio.h>
int main()
{
int a,b, r;
char op;
clrscr();
printf("Available Operations.\n");
printf("+ for Addition.\n");
printf("- for Subtraction.\n");
printf("* for Multiplication.\n");
printf("/ for Division.\n");
printf("%% for Modulo Division.\n");
printf("Which Operation?\n");
scanf("%c", &op);
switch(op)
{
case '+': printf("Enter two numbers:\n");
scanf("%d%d",&a, &b);
r = a+b;
printf("%d + %d = %d", a, b, r);
break;
case '-': printf("Enter two numbers:\n");
scanf("%d%d",&a, &b);
r = a-b;
64 | P a g e
printf("%d - %d = %d", a, b, r);
break;
case '*': printf("Enter two numbers:\n");
scanf("%d%d",&a, &b);
r = a*b;
printf("%d * %d = %d", a, b, r);
break;
case '/': printf("Enter two numbers:\n");
scanf("%d%d",&a, &b);
if(b!=0)
{
r = a/b;
printf("%d/%d = %d",a,b,r);
}
else
{
printf("Division not possible.");
}
break;
case '%': printf("Enter two numbers:\n");
scanf("%d%d",&a, &b);
if(b!=0)
{
r = a%b;
printf("%d%%%d = %d",a,b,r);
}
else
65 | P a g e
{ printf("Modulo Division not possible.");
}
break;
default: printf("Invalid Operation.");
break;
}
getch();
return(0);
}
Program: Using Switch statement, write a program that displays the following
menu for the food items available to take order from the customer:
• B= Burger
• F= French Fries
• P= Pizza
• S= Sandwiches
The program inputs the type of food and quantity. It finally displays the total
charges for the order according to following criteria:
• Burger = Rs. 200
• French Fries= Rs. 50
• Pizza= Rs. 500
• Sandwiches= Rs. 150
#include <stdio.h>
#include<conio.h>
int main()
{
int b,f,p,s,Burger,French,Pizza,Sandwiches;
char ch,B,F,P,S;
66 | P a g e
clrscr();
printf(“1=Burger\n2=French Fries\n3=pizza\n4=Sandwiches\n”);
printf(“Enter your order \nplease Enter the choice 1,2,3,4\n”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: printf(“your order is Burger\n”);
printf(“please enter your quantity “);
scanf(“%d”,&b);
Burger=200*b;
printf(“your total charges is: %d”,Burger);
break;
case 2:
printf(“your order is French \n”);
printf(“please enter your quantity “);
scanf(“%d”,&f);
French=50*f;
printf(“your total charges is: %d”,French);
break;
case 3:
printf(“your order is Pizza\n”);
printf(“please enter your quantity “);
scanf(“%d”,&p);
Pizza=500*p;
printf(“your total charges is: %d”,Pizza);
67 | P a g e
break;
case 4:
printf(“your order is Sandwiches\n”);
printf(“please enter your quantity “);
scanf(“%d”,&s);
Sandwiches=150*s;
printf(“your total charges is: %d”,Sandwiches);
break;
default:
printf(“invalid your choice”);
}
getch();
return 0;
}
OUTPUT :
FIRST RUN:
1=Burger
2=French Fries
3=pizza
4=Sandwiches
Enter your order
please Enter the choice 1,2,3,4
4
your order is Sandwiches
please enter your quantity 6
your total charges is: 900
68 | P a g e
SECOND RUN:
1=Burger
2=French Fries
3=pizza
4=Sandwiches
Enter your order
please Enter the choice 1,2,3,4
6
invalid your choice
69 | P a g e
While Loop
• A while loop is the most straightforward looping structure.
• It is an entry-controlled loop.
While loop syntax in C programming language is as follows:
Syntax of While Loop in C:
•
• In while loop, a condition is evaluated before processing a body of the loop.
• If a condition is true then and only then the body of a loop is executed.
• After the body of a loop is executed then control again goes back at the beginning,
and the condition is checked if it is true, the same process is executed until the
condition becomes false.
• Once the condition becomes false, the control goes out of the loop.
FLOW CHART
70 | P a g e
Do-While loop in C
• A do...while loop in C is similar to the while loop except that the condition is always
executed after the body of a loop.
• It is also called an exit-controlled loop.
• In a while loop, the body is executed if and only if the condition is true. In some
cases, we have to execute a body of the loop at least once even if the condition is
false. This type of operation can be achieved by using a do-while loop.
• In the do-while loop, the body of a loop is always executed at least once. After the
body is executed, then it checks the condition.
• If the condition is true, then it will again execute the body of a loop otherwise control
is transferred out of the loop.
71 | P a g e
FLOW CHART
72 | P a g e
FOR LOOP
Far Loop is an another entry control loop.
For loop contain Initialization, condition and increment or decrement in one line.
Syntax:
73 | P a g e
// w a p to to print factorial of a given positive number (for)
#include <stdio.h>
//#include<conio.h>
int main() {
int n,i,fact=1;
//clrscr();
printf("Enter n value :");
scanf("%d",&n);
}
printf("%d",fact);
//getch();
return 0;
}
OUTPUT
Enter n value :5
Factorial of 5 is 120
//printf("%d",res);
if(temp==res)
printf("\n%d is Armstrong",temp);
else
printf("\n%d is NOT Armstrong",temp);
//getch();
return 0;
}
75 | P a g e
Statements in ‘C’ :
A Statement causes an action to be performed by the program.
It translates directly into one or more executable computer instructions.
You may have noticed that we have used a semicolon (;) at the end of the statement in our
programs. Most statements need a semicolon at the end; some do not.
C having 11 types of statements. Those are.
1. NULL 2. EXPRESSION 3. RETURN
4. COMPOUND 5. CONDITIONAL 6. LABELED
7. SWITCH 8. GOTO 9. ITERATIVE
10. BREAK 11. CONTINUE
1. NULL STATEMENT : The null statement is just a semicolon(;) as shown below
Ex: ; // NULL STATEMENT
2.Expression Statement: An expression is turned to a statement by placing a semicolon (;)
after it.
Ex: a=2; a=b=3;
3.Return Statement : A return statement terminates a function. It is a keyword. All
functions, including main, use return statement. When there is no return statement at the
end of the function, the system inserts one with void return value.
Syntax: return Expression; // Return statement
Ex: return 0; return(10+20);
The return statement can return a value to the calling function. In case of main, it returns 0
to the operating system or operating environment. Return value of zero tells the operating
system that the program executed successfully.
4.Compound Statement: Compound statements are unit of code consisting of zero or more
statements. It is also known as a block. The compound statements allow a group of
statements to become one single entity.
5. CONDITIONAL STATEMENT (?:)
6. Goto Statement :
As the name suggests, goto is used to transfer the program control to a predefined
label.
76 | P a g e
The goto statment can be used to repeat some part of the code for a particular
condition. It can also be used to break the multiple loops which can't be done by using
a single break statement.
However, using goto is avoided these days since it makes the program less readable
and complected.
C Suppose the goto statement to jump unconditionally from one point to another in
the subprogram. The goto requires a label In order to identify the place where the
jump is to be made. Hey label is any valid variable name. and must be followed by a
colon(:). But The goto label followed by a semicolon(;). The label: is placed
immediately before the statement where the control is to be transferred.
The label: is placed before the statement goto label; a loop will be formed and some
statement between label: and goto label; will be executed repeatedly. Such a jump is
known as the backward jump.
If the label: is placed after the statement, goto label; Some statement between goto
label; and label: will be skipped. Such a jump is known as a forward jump.
77 | P a g e
getch();
}
7. break Statement: The break is a keyword in C which is used to bring the program control
out of the loop/switch. The break statement is used inside loops or switch statement.
When the loops are nested, the break would only exit from the loop containing it. That is,
the break will exit only a single loop. When the switches are nested, the break would only
exit from the switch containing it. That is, the break will exit only a single switch.
Syntax:
break;
#include<stdio.h>
#include<conio.h>
void main ()
{
int i;
clrscr();
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
getch();
}
OUTPUT
0 1 2 3 4 5 came outside of loop i = 5
78 | P a g e
//break statement in nested loop
#include<stdio.h>
#include<conio.h>
int main()
{
int i=1,j=1;//initializing a local variable
clrscr();
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d\t%d\n",i,j);
if(i==2 && j==2)
{
break;//will break loop of j only
}
}
}//end of for loop
getch();
return 0;
}
OUTPUT:
11
12
13
21
22
31
32
33
79 | P a g e
8 Continue Statement:
‘continue’ is a keyword, by using continue we can skip some statements in a loop body.
Using continue is optional but it should be within the loop body only. The continue
statement tells the compiler, skip the following statements and continue with the next
iteration.
Syntax:
continue;
#include<stdio.h>
#include<conio.h>
int main()
{
int i=1;//initializing a local variable
clrscr();
//starting a loop from 1 to 10
for(i=1;i<=10;i++)
{
if(i==5)
{//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for loop
getch();
return 0;
}
OUTPUT
1
2
3
80 | P a g e
4
6
7
8
9
10
OUTPUT
c1=2.200000 + I2.200000
c2=3.300000 + I3.300000
81 | P a g e
// w a p swap two numbers without using temporary variable
#include <stdio.h>
#include<conio.h>
int main() {
int a,b;
clrscr();
printf("Enter two numbers :");
scanf("%d%d",&a,&b);
printf("\nBefore Swap \n a=%d\tb=%d",a,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter Swap \n a=%d\tb=%d",a,b);
getch();
return 0;
}
OUTPUT
Enter two numbers :50 40
Before Swap
a=50 b=40
After Swap
a=40 b=50
82 | P a g e
// w a p to read u,t,a and find s value by using s=(ut)+1/2(a*t*t)
#include <stdio.h>
#include<conio.h>
int main() {
int u,t,a;
float s;
clrscr();
printf("Enter u,t,a values :");
scanf("%d%d%d",&u,&t,&a);
s=u*t+(0.5*a*t*t);
printf("s=%f",s);
getch();
return 0;
}
OUTPUT
Enter u,t,a values :2 3 1
s=10.500000
83 | P a g e
// w a p to print given integer number is +ve or -ve or zero by using nested if-else statement
#include <stdio.h>
#include<conio.h>
int main() {
int a;
clrscr();
printf("Enter a value :");
scanf("%d",&a);
if(a<=0)
{
if(a==0)
printf("Entered Number is : ZERO");
else
printf("Entered Number is :-ve");
}else
{
printf("Entered Number is :+ve");
}
getch();
return 0;
}
OUTPUT
Enter a value :-10
Entered Number is :-ve
84 | P a g e
// w a p to print given three numbers in desending order (else-if ladder)
#include <stdio.h>
#include<conio.h>
int main()
{
int a,b,c;
clrscr();
printf("Enter Three Numbers :");
scanf("%d%d%d",&a,&b,&c);
printf("Entered Numbers are :%d\t%d\t%d",a,b,c);
printf("\nDesendering Order is :\n");
if((a>b)&&(a>c))
{
if(b>c)
printf("%d\t%d\t%d",a,b,c);
else
printf("%d\t%d\t%d",a,c,b);
}else if((b>a)&&(b>c))
{
if(a>c)
printf("%d\t%d\t%d",b,a,c);
else
printf("%d\t%d\t%d",b,c,a);
}else
{
if(a>b)
printf("%d\t%d\t%d",c,a,b);
else
printf("%d\t%d\t%d",c,b,a);
}
getch();
return 0;
85 | P a g e
}
OUTPUT
Enter Three Numbers :20 15 30
Entered Numbers are :20 15 30
Ascendering Order is :
30 20 15
86 | P a g e
case 6:printf("SIX");
break;
case 7:printf("SEVEN");
break;
case 8:printf("EIGHT");
break;
case 9:printf("NINE");
break;
default : printf("Wrong Choice");
}
getch();
return 0;
}
OUTPUT
Enter a Digit :5
FIVE
87 | P a g e
// w a p to print 1 to 10 (while)
#include <stdio.h>
#include<conio.h>
int main() {
int i;
//clrscr();
i=1;
while(i<=10)
{
printf("%d\t",i);
i++;
}
getch();
return 0;
}
OUTPUT
1 2 3 4 5 6 7 8 9 10
88 | P a g e
// w a p to print even numbers from 1 to given range (while)
#include <stdio.h>
//#include<conio.h>
int main() {
int i,n;
clrscr();
printf("Enter n value :");
scanf("%d",&n);
i=1;
printf("\nEven Numbers Between 1 to %d \n",n);
while(i<=n)
{
if(i%2==0)
printf("%d\t",i);
i++;
}
getch();
return 0;
}
OUTPUT
Enter n value :20
Even Numbers Between 1 to 20
2 4 6 8 10 12 14 16 18 20
89 | P a g e
// w a p to fine sum of individual digits of a positive number (while)
#include <stdio.h>
#include<conio.h>
int main() {
int n,sum=0,temp;
clrscr();
printf("Enter n value :");
scanf("%d",&n);
90 | P a g e
// w a p to print reverse of given number (do-while)
#include <stdio.h>
#include<conio.h>
int main() {
int n,rev=0,temp;
clrscr();
printf("Enter n value :");
scanf("%d",&n);
printf("\nReverse of %d is ",n);
do
{
temp=n%10;
rev=(rev*10)+temp;
n=n/10;
}while(n!=0);
printf("%d",rev);
getch();
return 0;
}
OUTPUT
Enter n value :456
Reverse of 456 is 654
91 | P a g e
// w a p to to read x,n values and print X power n (do-while)
#include <stdio.h>
#include<conio.h>
int main() {
int x,n,res=1;
clrscr();
printf("Enter x and n value :");
scanf("%d%d",&x,&n);
92 | P a g e
COMMAND LINE ARGUMENTS IN C:
The most important function of C is main() function. It is mostly defined with a
return type of int and without parameters :
int main() { /* ... */ }
We can also give command-line arguments in C. Command-line arguments are
given after the name of the program in command-line shell of Operating
Systems.
To pass command line arguments, we typically define main() with two
arguments : first argument is the number of command line arguments and
second is list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
or
int main(int argc, char **argv) { /* ... */ }
argc (ARGument Count) is int and stores number of command-line
arguments passed by the user including the name of the program. So if we pass
a value to a program, value of argc would be 2 (one for argument and one for
program name)
The value of argc should be non negative.
argv(ARGument Vector) is array of character pointers listing all the
arguments.
If argc is greater than zero, the array elements from argv[0] to argv[argc-1]
will contain pointers to strings.
argv[0] is the name of the program , After that till argv[argc-1] every element
is
command -line arguments.
Example:
// Name of program “args.c”
#include <stdio.h>
#include <conio.h>
int main(int argc, char* argv[])
{
93 | P a g e
clrscr();
Printf (“no.of arguments passed through command prompt is %d”,argc);
Printf (“arguments are:\n”);
for (int i = 0; i < argc; ++i)
puts(argv[i]);
getch();
return 0;
}
3. Change directory
Now you need to change the current directory of DOS Shell to
"SOURCES" from "BIN", for this you need to user cd command.
First use cd.. for coming back to Turbo C++ main directory
94 | P a g e
cd..
Now use cd SOURCE to access the SOURCE directory
cd SOURCE
C:\TURBOC3\SOURCE>args.exe hi hello
Here ARGS.EXE is the executable of your program ARGS.C and hi hello
are a command line argument. When you'll hit the enter, it produces the
following result
OUTPUT
no.of arguments passed through command prompt is 3
arguments are:
C:\TURBOC3\SOURCE>args.c
hi
hello
95 | P a g e
Statements in ‘C’ :
A Statement causes an action to be performed by the program.
It translates directly into one or more executable computer instructions.
You may have noticed that we have used a semicolon (;) at the end of the statement in our
programs. Most statements need a semicolon at the end; some do not.
C having 11 types of statements. Those are.
2. NULL 2. EXPRESSION 3. RETURN
5. COMPOUND 5. CONDITIONAL 6. LABELED
7. SWITCH 8. GOTO 9. ITERATIVE
10. BREAK 11. CONTINUE
1. NULL STATEMENT : The null statement is just a semicolon(;) as shown below
Ex: ; // NULL STATEMENT
2.Expression Statement: An expression is turned to a statement by placing a semicolon (;)
after it.
Ex: a=2; a=b=3;
3.Return Statement : A return statement terminates a function. It is a keyword. All
functions, including main, use return statement. When there is no return statement at the
end of the function, the system inserts one with void return value.
Syntax: return Expression; // Return statement
Ex: return 0; return(10+20);
The return statement can return a value to the calling function. In case of main, it returns 0
to the operating system or operating environment. Return value of zero tells the operating
system that the program executed successfully.
4.Compound Statement: Compound statements are unit of code consisting of zero or more
statements. It is also known as a block. The compound statements allow a group of
statements to become one single entity.
5. CONDITIONAL STATEMENT (?:)
6. Goto Statement :
As the name suggests, goto is used to transfer the program control to a predefined
label.
96 | P a g e
The goto statment can be used to repeat some part of the code for a particular
condition. It can also be used to break the multiple loops which can't be done by using
a single break statement.
However, using goto is avoided these days since it makes the program less readable
and complected.
C Suppose the goto statement to jump unconditionally from one point to another in
the subprogram. The goto requires a label In order to identify the place where the
jump is to be made. Hey label is any valid variable name. and must be followed by a
colon(:). But The goto label followed by a semicolon(;). The label: is placed
immediately before the statement where the control is to be transferred.
The label: is placed before the statement goto label; a loop will be formed and some
statement between label: and goto label; will be executed repeatedly. Such a jump is
known as the backward jump.
If the label: is placed after the statement, goto label; Some statement between goto
label; and label: will be skipped. Such a jump is known as a forward jump.
97 | P a g e
getch();
}
7. break Statement: The break is a keyword in C which is used to bring the program control
out of the loop/switch. The break statement is used inside loops or switch statement.
When the loops are nested, the break would only exit from the loop containing it. That is,
the break will exit only a single loop. When the switches are nested, the break would only
exit from the switch containing it. That is, the break will exit only a single switch.
Syntax:
break;
#include<stdio.h>
#include<conio.h>
void main ()
{
int i;
clrscr();
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
getch();
}
OUTPUT
0 1 2 3 4 5 came outside of loop i = 5
98 | P a g e
//break statement in nested loop
#include<stdio.h>
#include<conio.h>
int main()
{
int i=1,j=1;//initializing a local variable
clrscr();
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
printf("%d\t%d\n",i,j);
if(i==2 && j==2)
{
break;//will break loop of j only
}
}
}//end of for loop
getch();
return 0;
}
OUTPUT:
11
12
13
21
22
31
32
33
99 | P a g e
8 Continue Statement:
‘continue’ is a keyword, by using continue we can skip some statements in a loop body.
Using continue is optional but it should be within the loop body only. The continue
statement tells the compiler, skip the following statements and continue with the next
iteration.
Syntax:
continue;
#include<stdio.h>
#include<conio.h>
int main()
{
int i=1;//initializing a local variable
clrscr();
//starting a loop from 1 to 10
for(i=1;i<=10;i++)
{
if(i==5)
{//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for loop
getch();
return 0;
}
OUTPUT
1
2
3
100 | P a g e
4
6
7
8
9
10
101 | P a g e
Storage Classes in C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial
value of a variable. There are four types of storage classes in C
Automatic
External
Static
Register
extern RAM Zero Global Till the end of the main program Maybe
declared anywhere in the program
static RAM Zero Local Till the end of the main program, Retains
value between multiple functions call
Automatic
➢ Automatic variables are allocated memory automatically at runtime.
➢ The visibility of the automatic variables is limited to the block in which
they are defined.
➢ The scope of the automatic variables is limited to the block in which they
are defined.
➢ The automatic variables are initialized to garbage by default.
➢ The memory assigned to automatic variables gets freed upon exiting from
the block.
➢ The keyword used for defining automatic variables is auto.
➢ Every local variable is automatic in C by default.
➢ The "auto" storage class in C is used to declare variables that have a
local scope and are automatically allocated and deallocated on the
102 | P a g e
stack. It is the default storage class for all local variables, meaning
that if no storage class is explicitly specified, a variable is assumed to
have the "auto" storage class.
#include <stdio.h>
int main() {
auto int x = 5; // variable defined and initialized
printf("x = %d\n", x);
return 0;
}
In this example, x is defined with the same behavior as the previous example,
but the keyword "auto" is not used.
In modern C compilers, the keyword "auto" is mostly used for readability and
documentation purposes, especially when a variable is intended to have a local
scope.
Static
➢ The variables defined as static specifier can hold their value between the
multiple function calls.
➢ Static local variables are visible only to the function or the block in which
they are defined.
➢ A same static variable can be declared many times but can be assigned at
only one time.
➢ Default initial value of the static integral variable is 0 otherwise null.
➢ The visibility of the static global variable is limited to the file in which it
has declared.
➢ The keyword used to define static variable is static.
➢ The "static" storage class in C is used to declare variables or
functions that have a local scope but retain their value between
function calls. It also makes a variable or function available only
within the file it is defined.
103 | P a g e
#include <stdio.h>
void increment() {
static int x = 0; // variable defined and initialized only once
x++;
printf("x = %d\n", x);
}
int main() {
increment(); // prints "x = 1"
increment(); // prints "x = 2"
increment(); // prints "x = 3"
//printf("main x=%d",x); // it gives error
return 0;
}
In the above example, the variable x is declared with the "static" storage class
within the increment() function. The first time the function is called, x is
initialized with a value of 0. Each subsequent call to the function increments x
by 1 and prints its current value, but the value is retained between function calls.
The value of x is not accessible outside the function increment()
It's also possible to use "static" keyword for function, in that case the function
would be only accessible within the file it's defined, making it a "file-scope"
function.
//file1.c
static void foo(){
//...
}
int main(){
foo();
104 | P a g e
return 0; }
//file2.c
int main(){
foo(); // this will cause an error.
return 0;
}
In this example, the function foo() is only accessible from within file1.c and any
attempt to call it from other files will result in a compile-time error.
Register
➢ The variables defined as the register is allocated the memory into the
CPU registers depending upon the size of the memory remaining in the
CPU.
➢ We cannot dereference the register variables, i.e., we can not use
&operator for the register variable.
➢ The access time of the register variables is faster than the automatic
variables.
➢ The initial default value of the register local variables is 0.
➢ The register keyword is used for the variable which should be stored in
the CPU register. However, it is compiler?s choice whether or not; the
variables can be stored in the register.
➢ We can store pointers into the register, i.e., a register can store the
address of a variable.
➢ Static variables can not be stored into the register since we can not use
more than one storage specifier for the same variable.
➢ The "register" storage class in C is used to declare variables that are
stored in a CPU register instead of memory. This can result in faster
access times, as registers are generally faster to access than memory.
However, using the "register" storage class is not a guarantee that
the variable will be stored in a register, as the compiler may choose to
store the variable in memory if there are not enough registers
available.
105 | P a g e
#include <stdio.h>
int main() {
register int x = 5; // variable stored in a register
printf("x = %d\n", x);
return 0;
}
In the above example, the variable x is declared with the "register" storage class.
The compiler may choose to store x in a register for faster access, but this is not
guaranteed.
It's worth noting that in modern computer architectures, compilers are more
sophisticated and able to optimize the code and decide which variable should be
stored in registers and access memory based on the context of the program, so
using the keyword "register" may not have a big impact on performance and
could even lower the performance.
External
➢ The external storage class is used to tell the compiler that the variable
defined as extern is declared with an external linkage elsewhere in the
program.
➢ The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared elsewhere
in the program.
➢ The default initial value of external integral type is 0 otherwise null.
➢ We can only initialize the extern variable globally, i.e., we can not
initialize the external variable within any block or method.
➢ An external variable can be declared many times but can be initialized at
only once.
➢ If a variable is declared as external then the compiler searches for that
variable to be initialized somewhere in the program which may be extern
or static. If it is not, then the compiler will show an error.
106 | P a g e
➢ The "extern" storage class in C is used to declare a variable or
function that is defined in another source file. It tells the compiler
that the variable or function being declared has been defined
elsewhere and should be linked to the definition at runtime.
File1.c:
#include <stdio.h>
int x = 5; // variable defined and initialized
void print_x() {
printf("x = %d", x);
}
File2.c:
#include <stdio.h>
#include “File1.c”
extern int x; // variable declared, but not defined or initialized
extern void print_x(); // function declared, but not defined
int main() {
printf("x = %d\n", x); // prints "x = 5"
print_x(); // prints "x = 5"
return 0;
}
In the above example, the variable x and the function print_x() are defined in
File1.c, but declared using the "extern" storage class in File2.c. When the
program is compiled and run, the definition of x and print_x() from File1.c is
linked to the declarations in File2.c, allowing them to be used in the main
function.
107 | P a g e
#include<stdio.h>
//#include<conio.h>
//int x=20; // if u declare “x” Here, need not use keyword “extern” in program
int main()
{
extern int x;
{
int x=30;
printf("block-1 x= %d\n",x);
}
printf("outside block x= %d\n",x);
getch();
return(0);
}
int x = 20;
OUTPUT
block-1 x= 30
outside block x= 20
108 | P a g e