0% found this document useful (0 votes)
25 views33 pages

Pseudocode

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

Pseudocode

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

Pseudocode

Pseudocode (pronounced SOO-doh-kohd) is a detailed yet readable description


of what a computer program or algorithm must do, expressed in a formally-styled
natural language rather than in a programming language.

Pseudocode (derived from pseudo and code) is a compact and informal high-
level description of a computer programming algorithm that uses the structural
conventions of programming languages, but omits detailed subroutines, variable
declarations or language-specific syntax. The programming language is improved with
natural language descriptions of the details and with compact mathematical notation.
The purpose of using pseudo code as compare the programming language syntax is
that it is easier for humans to read. Pseudocode may therefore vary widely in style,
from a near-exact imitation of a real programming language or may be differ from real
programming language syntax. Flowcharts can be thought of as a graphical form of
pseudo code.

Examples of pseudocode –

if credit card number is valid


execute transaction based on number and order
else
show a generic failure message
end if

Pseudocode is a kind of structured english for describing algorithms. It allows


the designer to focus on the logic of the algorithm without being unfocused by details
of language syntax. It describe the entire logic of the algorithm so that implementation
becomes easy. Each textbook and each individual designer may have their own
personal style of pseudocode.

Pseudocode is an artificial and informal language that helps programmers


develop algorithms. Pseudocode is a "text-based" detail design tool. An algorithm is a
procedure for solving a problem in terms of the actions to be executed and the order
in which those actions are to be executed. An algorithm is merely the sequence of
steps taken to solve a problem.

Algorithm
An algorithm is a formula or set of steps for solving a particular problem. An
algorithm is a set of rules must be unambiguous and have a clear stopping point.
Algorithms can be expressed in any natural languages like Hindi, English, French etc.

An algorithm (pronounced AL-go-rith-um) is a procedure or formula for solving


a problem. The word derives from the name of the mathematician, Mohammed ibn-
Musa al-Khwarizmi, who was part of the royal court in Baghdad and who lived from
about 780 to 850.
A computer program can be viewed as an elaborate algorithm. In mathematics
and computer science, an algorithm usually means a small procedure that solves a
recurrent problem. Inventing elegant algorithms -- algorithms that are simple and
require the fewest steps possible -- is one of the principal challenges in programming.

In mathematics, computing, linguistics, and related disciplines, an algorithm is


a definite list of well-defined instructions for completing a task; that given an initial
state, will proceed through a well-defined series of successive states, eventually
terminating in an end-state. The concept of an algorithm originated as a means of
recording procedures for solving mathematical problems such as finding the common
divisor of two numbers or multiplying two numbers.

The concept of algorithm is also used to define the notion of logic. That notion
is central for explaining how formal systems come into being starting from a small set
of axioms and rules. In logic, Different algorithms may complete the same task with a
different set of instructions in less or more time, space, or effort than others.

Cooking recipe is also algorithm that explains systematic process & steps for Food
preparation.

Flowchart
The flowchart is a means of visually presenting the flow of data through an
information processing systems, the operations performed within the system and the
sequence in which they are performed.

As we know a designer draws a blueprint before starting construction on a


building. Similarly, a programmer prefers to draw a flowchart prior to writing a
computer program. As in the case of the drawing of a blueprint, the flowchart is
drawn according to defined rules and using standard flowchart symbols prescribed by
the American National Standard Institute.
Flowcharts Understanding and Communicating. How a Process Works (Also
called Process Maps and process Flow Diagrams)
A flowchart is a diagrammatic representation that illustrates the sequence of
operations to be performed to get the solution of a problem. Once the flowchart id
drawn, it becomes easy to write the program in any high level language.
Flowcharts facilitate communication between programmers and busines people.
These flowcharts play a vital role in the programming of a problem and are quite
helpful in understanding the logic of complicated and lengthy problems.
A flowchart can be used for-

 Defining and analyzing processes;


 Build a step-by-step picture of the process for analysis, discussion, or
communication purpose.
Guidelines For Drawing A Flowchart
Flowcharts are usually drawn using some standard symbols; however, some
special symbols can also be developed when required. Some standard symbols, which
are frequently required for flowcharting many computer programs are shown in
following figure-

Start or end of the program

Computational steps or processing function of a program

Input or output operation

Decision making and branching

Connector or joining of two parts of program

Magnetic Tape

Magnetic Disk

Off-page connector

Flow line

Annotation

Display

In drawing a proper flowchart, all necessary requirements should be listed out in
logical order.
The flowchart should be clear, neat and easy to follow. There should not be any
room for ambiguity in understanding the flowchart.
The usual direction of the flow of a procedure or system is from left to right or top
to bottom.
Within each symbol, write down what the symbol represents. This could be the
start or finish of the process, the action to be taken, or the decision to be made.
Only one flow line should come out from a process symbol.
Only one flow line should enter a decision symbol, but two or three flow lines,
one for each possible answer, should leave the decision symbol.
Only one flow line is used in conjunction with terminal symbol.
Decision Table
A Decision Table is a matrix of rows and columns that shows condition & actions.

Decision Table and Decision Tree are use to express relationship between Condition
and related actions. These tools are use during System Development Life Cycle
[SDLC].

Decision Rules, include in a decision table, state what action\procedure to follow


when certain condition exist. This method is used after 1950, when General Electric
for analysis of business functions develops it.

A Decision Table is made up of four sections –

1. Condition Statements
2. Condition Entries
3. Action Statements
4. Action Entries

Condition Statements
Condition Statements identifies the relevant condition.

Condition Entries
Condition Entries tells what a value to be applies for a particular condition.

Action Statements
Action Statements list the set of all steps\actions that can be taken when a certain
condition occurs.

Action Entries
Action Entries shows what specific action/ step in the set to take when selected
condition is true.

Sometime it is also mention with table when to use this table or to distinguish this
table from other tables.

ConditionDecision Rules

Condition StatementsCondition Entries

Action Statements Action Entries

Example Decision Table Format


Types of Decision Table

 Limited Entry Form


 Extended Entry Form
 Mixed Entry Form
 Else Form

Each decision corresponds to a variable, relation or predicate whose possible


values are listed among the condition alternatives. Each action is a function or
operation to perform, and the entries specify whether (or in what order) the action is
to be performed for the set of condition alternatives.

Example -

ConditionDecision Rules

[Condition Statements][Condition Entries]


1234
Cond1: Marks >= 60%YNNN
Cond2: Marks >= 50%NYNN
Cond3: Marks >= 40%NNNN

[Action Statements] [Action Entries]


Act1:Pass - 1st DivisionX---
Act2:Pass – 2nd Division-X--
Act3:Pass – 3rd Division--X-
Act4:ELSE Fail---X

In above example decision table have four parts i.e. Condition Statements,
Action Statements, Condition Entries and Action Entries. Action taken is depends on
condition statements and condition entries, if condition statement is yes [Y] then
associated action statement executes denoted by X sign.

Programming Language
A formal language in which computer programs are written. The definition of a
particular language consists of both syntax (how the various symbols of the language
may be combined) and semantics (the meaning of the language constructs).

An artificial language that enables people to instruct machines. Computer


commands that form procedures by which software programmers design and
implement computer software programs. A program is a sequence of instructions that
are executed by a CPU. While simple processors execute instructions one after the
other.

The language a programmer uses to create an application will depend on the desired
properties of the program. Some programming languages lend themselves to
mathematical and analytical functions while others are better suited for creating
business or data processing applications.

Features of C Programming Language –

 C is High Level Programming Language.


 C is Functional Language i.e. near about every instruction is in Form of
Function.
 C is case sensitive Programming Language i.e. it differentiate between upper
case [Capital Letter] & Lower Case [Small Letter] alpha bate.
 In C every instructions given in lowercase.
 Every C Program have at least one function i.e. main C).
 Program execution start from main C) function.
 C is structured Programming Language.
 C is code Block Programming Language.
 Initially, C was used for system programming i.e. for complier, Interpreters,
operating systems etc.
 C Programming Language allows the manipulation of bits, bytes and
addresses.

Data Type
A data type defines a set of values that a variable can store along with a set of
operation that can be performed on that variable. A variable is named location in main
memory that is used for holding a value that may be modify by the program.

There are four basic data type in C Language.

(i) Character type – For Non-Numeric values


a. char [%c]
(ii) Integer type – For integer i. e. value without fractional part values
a. int [%d]
b. unsigned int [%u]
c. long [%ld]
d. unsigned long [%lu]
(iii) Float / Real type – For real number i. e. value with fractional part
values
a. float [%f]
b. double [%lf]
c. long double [%Lf]
(iv) Void type
a. void

The size & range of these data type may vary between processor. The range of
float & double is also depend on method used to represent it.

Different data types are required because program requires to read (Input) &
write (output) different type of values.

int (integer) %i or %d
It is used to accept Positive & Negative Numeric values.
Integer variable does not accept decimal part of value.
Generally Range of int. is from -32768 to + 32767.
Format Specified for int. is %i or %d.
int k, m = 17;

unsigned int %u
It is used to accept Positive Numeric values. Integer variable does not accept
decimal part of value. Generally Range of unsigned int. is from 0 to 65,535
Format specifier for unsigned int is %u
unsigned int k, m = 50000;

Declare two variables k, m of datatype unsigned int and assigning value 50000 to
variable m.

long %ld or %li


It is used to accept Positive & Negative Numeric values. long variable does not
accept decimal part of value.
Generally Range of long is from -2,147,483,648 to 2,147,483,647
Format specifier for int. is %ld or %li
long k, m = 175000;
Declare two variables k, m of data-type long and assigning value 175000 to
variable m.

unsigned long %lu


It is used to accept Positive Numeric values.
unsigned long variable does not accept decimal part of value.
Generally Range of unsigned long is from 0 to 4,294,967,295
Format specifier for unsigned int is %lu
unsigned long k, m = 475;
Declare two variables k, m of datatype unsigned long and assigning value 475 to
variable m.

float %f or %g or %e
It also accepts positive & Negative Real type Numeric values.
Float type variable contains value with decimal point.
Format specifier for float is % f.

Normally range of Float is from 3.4 × (10)-38 To 3.4 × (10) + 38


float j = 15.27, k;
Declare two variables j, k of data-type float and assigning value 15.27 to variable
j.

double %lf
double type variable accept Real type Numeric value.
This contain value with decimal point.
Format specifier for double is %lf

Range of double is from 1.7 × (10) - 308 To 1.7 × (10)+ 308


double j = 56.057, k;
Declare two variables j, k of data-type double and assigning value 56.057 to
variable j.

long double %Lf


long double type variable accept Real type Numeric value.
This contain value with decimal point.
Format specifier for double is %Lf
Range of double is from 3.4 × (10) - 4932 To 1.1 × (10)+ 4932

long double j = 1007.038, k;


Declare two variables j, k of data-type long double and assigning value 1007.038
to variable j.
char (Character) %c
Char type variable accepts single Non-Numeric value, Numeric value or any
special character.
Char type variable treat each value as Non Numeric value.
Format Secifier for char is % C.
Char a, n = `A';

Identifiers
Name of variable, constant, function, Labels and various other user define
objects are called identifier.
Following are rules for constructing Identifiers :
(i) Identifier Name must start with alpha bate or underscore sign.
(ii) Identifier Name may contain alpha bate {a to z or A to Z}
Number {0 to 9} and under score sign only.
(iii) Special symbol {Like #, $ etc.} are not allowed in identifer name.
(iv) Maximum 8 character are allowed in identifier name.
(v) Two or more identifier should not have same name.
(vi) Blank space is not allowed within identifier name.

Example
Example of some valid Identifier (Names)-
Count
Abc
xy212
Add11
Sum_13
Example of some Invalid Identifier (Names)-
1New
NM 14
Total $ 43

Variables

A variable is named location in memory that is used for hold a value that may be
modify by program. Variable must be declare before any executable statement.
A data type associate with variable define the set of values that may be store by
that variable and set of operation possible on that variable.
int a, b, c;
float x, z = 10.75;

A variable may be declared on following basic places :


(i) At starting of main ( ) function or any other function defination.
(ii) As a function parameter in header of function.
(iii) Out side of any function i.e. global variable.

Types of Variables –

(i) Local Variables


(ii) Global variables / External.

Constant
Like a variable, a constant is named location in memory that is used to hold
value.
But value of a constant can not be change by program at Run Time.
Constants are also called literals.
For declaration of constant we should use const keyword with datatype and
constant identifier name.
Const int. k = 15;
Const float n = 12.67;
Constant can be divided into two categories-
(i) Primary Constant
(ii) Secondary constant
Const keyword is access modifier that stop to modify value of memory location.
Like variable, constant may be declare at three locations.

Reserve Words

Reserve words are also called keywords. Reserve words are identifiers whose
meaning has already been define C compiler. Reserve words can not be used as
variable or constant name because assigning a new meaning to the reserve word is
not possible.
Reserve words are identifiers whose meaning has already been define C compiler.
So we do not need any header file to use for using keywords in our C program.

There are 32 Reserve words/keywords in C programming Language. 27 keyword


were define by the original version of C and 5 were added by the ANSI C Committee.

Some complier may have some additional keywords also. Following are some
examples of keywords / reserve words available in C programming language –

1) auto 2) static 3) extern 4) register 5) int 6) long 7) float 8) double 9) char 10) void
11) signed 12) do 13) for 14) while 15) if 16) else 17) switch 18) case 19) break
20) continue 21) default 22) goto 23) struct 24) Union 25) return

Various Operators Used in C Programming

Operators

Binary Operators Unary Operators

Arithmetic Operators [*, / , Increment Operators [ + + ]


% ,+ , - ] Pre - Increment Op
Relational Operators Post - Increment Op
[ < , <= , > , >=, == , != ]
Logical Operators [&& , Decrement Operators [ - - ]
||,!] Pre - Decrement Op
Bitwise Operators Post - Decrement Op
[ & , | , ^ , ~ , >> , << ] Unary minus [ - ]
Assignment operators [ = ] Logical Not [ ! ]

C is very rich in built in operators. In any programming language operators are


required to perform different type of operations. On the basis of operands required for
execution of a operator, We can categorize operators in two categories -
(A) Binary operators - When a operator required two operands (on both left & right
side) then it s called Binary Operator.
(B) Unary Operators - When a operator required only one operand (on either side)
then it is called Unary Operators.

Binary operators

Arithmetic Operators

C Programming Language Provide Five arithmetic operators. These are :


%/*
+-
All these operators are Binary operators.
Arithmetic operators can apply to almost any built in data type.
% operator can not be used with float data type.
Arithmetic operators required for performing different arithmetic operations are :

% Modulus operator
/ Division
* Multiplication
+ Addition
- Subtraction [Also known as Unary Minus]

Precedence of Arithmetic Operators-


Highest %/*
Lowest +-

Precedence of % / * operators are equal and + - operators are equal.


Arithmetic operator evaluate from left to right order.

Relational & Logical Operators


Relational & Logical operators are also Binary operators and evaluate from left to
right order on basis of their precedence.
Relational operators refer to the relationship that values can have with one
another. Logical operators refer to the way these relationships can be connected.
Relational & logical operators return Non-zero if define relationship is true and
return zero if define relationship is false.
int a = 10, b = 25;
a<b;
This statement return Non-zero because define relationship is true i.e. a is less
than b.
Both Relational & Logical operator are have lower precedence then the arithmetic
operators.
Relational Operators
Operators Meaning
> is Greater than
>= is Greater than or equal to
< is Less than
<= is less than or equal to
== is equal to
!= is Not equal to
Logical Operators
Operators Meaning
&& And
¦¦ OR
! Not

Precedence of the Relational & Logical Operators-


! Highest
>>=<<=
== !=
&&
|| Lowest

Truth Tables –
Truth Table for && [Logical And]
Condition A Condition B Result
True True True
True False False
False True False
False False False
int a=10, b=24;
( ( a < 15 ) && ( b == 24 ) ) /* True */
Because a < 15 is true and b == 24 true i.e. True && True is True

( ( a < 5 ) && ( b <= 24 ) ) /* False */


Because a < 5 is false and b <= 24 true i.e. False && True is False

Truth Table for || [Logical Or]


Condition A Condition B Result
True True True
True False True
False True True
False False False

float a=10.25, b=24;


( ( a < 15 ) ||( b >= 24 ) ) /* True */
Because a < 15 is true or b >= 24 true i.e. True || True is True

( ( a != 15 ) || ( b != 24 ) ) /* True */
Because a != 15 is true or b != 24 false i.e. True || False is True

Truth Table for ! [Logical Not]


Condition A Result
True False
( ! (True) ) is False
False True
( ! ( False ) ) is True

long k = 10, n=78;


( ! ( k < 20 ) ) /* False */
Because k < 20 is true but ( ! ( True ) ) is False.

( ! ( k > 20 ) ) /* True */
Because k > 20 is false but ( ! ( False ) ) is True.
Relational & Logical Operator always produce value in terms of either Non zero [True]
or zero [false].
int a = 10, b = 20, c = 10;
b>a;
return true because b is greater
then a i.e. 20 > 10,
a < b;
Return True because value of a is Less then value of b.
a = = c;
Return true because value of a is equal to value of C.
a = = b;
Return false because value of a is Not equal to b.
a!=b;
Return True, because value of a is not equal to value of b.
a ! = c ; False
c > = b; false
b > = a; True
b > = c; True.

Bitwise Operator

C Programming Language is a bit oriented language.


Bitwise operators are used to perform setting or shifting the actual bits in a byte
or word.
Bitwise operator can be used with int, long & char types.
Bitwise operator cannot be used with float, double or void data types.
Bitwise operator operates on bit level. Bit level operation are important when
direct hardware interaction is required.
Bit Manipulation operations are very powerful feature of C programming
language.

Bitwise Operator
Operator Meaning
& And
¦ OR
^ Exclusive OR [XOR]
~ Not
>> Right Shift
<< Left Shift.

The bitwise And, or and Not are governed by the truth table.

The Right shift (>>) and left shift (<<) move bit of variable in Right or Left as
specified.
Variable >> No. of bits shifting
variable << No. of bits shifting.
By using right or left shift, bits are shifted off from one end & O [zero] are brought
from other end.

Assignment Operator
Assignment Operator is Binary Operator. Assignment Operator can be used with
any valid expression. Left side part of assignment operator must be variable or pointer
name.
Constant or function name of left side of assignment operator is not allowed.
Right side of assignment operator may be constant, function, value, variable or
expression.

Variable Name = expression;

int k;
k = a + b;
k = 17;
Two terms LValue & RValue are used with assignment operator.
LValue means any object that can be used on left side of assignment operator.
RValue means any object that can be used on right side of assignment operator.

int a, b, c;
a = b = c = 75;

Above is example of multiple assignment that means single value can be assign
to multiple variable within single statement. Assignment operator works from right to
left order.
Unary operators
Increment ( + + ) and Decrement ( – – )

Both Increment & Decrement operators are Unary operators. Increment (++)
operator adds 1 to its operand and Decrement (–) subtracts one from operand.
Unary operator Increment & Decrement have higher precedence then any binary
operator. Increment and Decrement operator may be :
Pre-Fix
OR
Post-Fix

The difference between prefix & postfix operator arise when these are used in
expression. Prefix operators are evaluated before expression evaluation, and Postfix
operator are evaluated after expression evaluation.

int k;
k ++ ; /* Postfix Increment */
++ k ; / * Prefix Increment */
– – k; / * Prefix Decrement */
k – – ; /* Postfix Decrement */

Increment and Decrement operator are shorthand for addition / subtraction 1 to


any variable operand.
int z = 7 ;
Meaning of
z = z + 1;
is same as
z++;
(i) int n = 10, h = 75;
n ++ ;
++ h ;
after execution of this two statement value of n is 11 and value of h is 76.
(ii) int a = 7, b = 18;
– – b;
a––;
After execution of these two statements value of a became 6 And value of b
became 17.
(iii) int j, d = 40;
j = ++ d ; | | Prefix Increment
After this value of d became 41 and J is also 41.
(iv) int a, b = 100;
a = b ++; / * Postfix Increment */

After execution of these value of a is 100 & b is 101. because b is postfix


Increment i.e. b first assigned it's value to a & then performed increment operation.
(v) long a = 12, b = 15, c, d ;
C = – – a; /* Prefix Decrement **/
d = b – – ; /* Postfix Decrement */
After execution of both statements value of both a & c is 11 because prefix
Decrement and value of d is 15 & b is 14 because of postfix decrement operation.
(vi) int a, b, sum :
a = 10;
b = 5;
sum = ++ a * b ++ ;
After execution of statement
sum = 55
a = 11 &
b=6
Because Prefix operator execute before expression execution and after that
postfix operator executes.

Jumping Statement

Jumping Statements are used to transfer execution control to any other point
within the program during execution time. After transferring execution control
program execution flow, resume sequential from that point. In C Programming
followings are jumping statement –
 break
 continue
 goto
 return
break Statement
Break Statement can be used within any loop statement or with Switch-Case
statement.
Keyword break forces to immediate termination of a loop or switch-case
statement. Normal loop/switch termination condition is by passed when break is
used.
Break statement sends execution control outside of loop/switch statement &
resume sequential execution flow after loop/switch-case part.
int k;
For (k = O; k < 75; k++)
{
printf (``\n value = %d'', k);

if (k = = 15)
break;

} /* end of for loop */

Above loop is executed & printed till value of k is 15 and after that if ( ) condition
is true & break executed that causes immediate termination of loop & bypass the
normal termination condition of loop.

continue Statement
Continue is a keyword in C language. Continue statement can be used with :
(i) for loop
(ii) while loop
(iii) do-while loop
When continue statement execute; remaining part of loop is skipped & execution
control pass to starting of loop for next iteration of loop.
void main ( )
{
long k, m = 1;
clrscr ( );
printf (''Program for multiplication '').
printf (''\n for exit press O '');
for (; ;)
{
printf (``\n Enter any positive integer value '');
scanf (``%/d ''value & k);
if (k = = 1)
Continue;
if (k = = O)
break ;
m = m * k;
3 /* end of for loop */
printf (''/n Multiplication = %/d'', m)
getch ( ) ;
} /* end of void main () */

goto Statement

goto is one of the 32 keywords available in C language. goto statement can be


used anywhere in program for transfer execution control within the function.
The goto requires a label for execution. A label is any valid identifier. Label with
goto statement indicates that where to transfer execution control.
goto statement can not transfer execution control outside of a function.
Structured languages like C discourage use of goto statement because goto increase
times & memory complexity of program. Structured languages like C directly support
various loop and conditional statement for control & transfer execution flow.

void main ( )
{
int k = O;
clrscr ( );
indore : /* label indore */
k++ ;
printf (''\n %d = Indore'', k);
if (k = = 10)
exit (0); /* terminate Prog. execution */
goto indore ; /* jump to label indore */
getch ( );
} /*end of join main () */

return Statement
The keyword return is used to return execution control from a function. Return
statement can be categorized as a jump statement because it returns [Jump back]
from a function to point of function calling.
The return statement can be used within Non-void function. In other words
return statement can be used within a function if function data type is not void.
Void function can not be used with return statement. In a non-void function if
return is not used, function returns garbage value.
The return statement can be used anywhere within a non-void function and as
soon as return statement function execution stop & execution control returns to
function calling point.
general form of return statement-
return (value/variable/constant/expression );

We can use as many as required return statement. A return statement can


return only one value.

exit function
exit ( ) is not a kind of jump statement. On execution of exit ( ) statement entire
program execution terminates immediately.
exit ( ), statement returns execution control from program to operating system.
The exit ( ) is library function of C language.
General form of exit ( ) is-
void exit (int return value);
stdlib.h header file is required to includes for exit ( ) function. exit ( ) return O
[Zero] to operating system on normal terminator.

Conditional Statement

if ( ) Condition
if ( ), if ( )- else & Switch are conditional statement. This conditional statement is
also called selection statement. Conditional / Selection statements are used to control
execution flow of program.
Sometimes it is required for execution of a particular statement if certain
condition is true & otherwise another statement execution is required in such case
conditional statements are required.
It is called conditional / selection statement because it depend on condition that
what statement will execute next or selection of execution path is condition based.
Following conditional statements are available in C Language-

(i) if (Condition)
{
Statement 1;
Statement 2;
-------------
-------------
Statement N;
}
(ii) if (Condition)
{
Statement 1;
Statement 2;
-------------
-------------
Statement N;
}
else
{
statement 1;
Statement 2;
-------------
-------------
Statement N;
}

(iii) switch (Conditional)


{
case Condition 1;
statement Block;
break ;

case condition 2;
Statement Block;
break;

case Condition N :
Statement Block;
break ;

default ;
statement Block;

} /* end of switch */

If Conditional expression evaluation is true then related statement is excuted


other wise next statement. Generally Conditional expression consist Relational &
Logical Operators.
Relational & Logical operators return value either true or false.
(1) if (condition)
{
Statement 1;
Statement 2;
----------------
----------------
Statement N;
}
Condition is normally conditional expression, that returns either true of false. if
condition evaluates true then related statement block is executed otherwise skip.
if ( ) condition may contain zero, one or more statements. Normally if ( )
statement is used if there is only one condition to check. The condition is always
enclosed within a pair of parentheses.
Example
(i) int k = 15;

if (k < 10)
{
printf (``\n k is greater then 10'')
printf (``\n value of k = %d'', k);
}
Value k is 15 i.e. k > 10 so condition is true & both statement will execute.
Sequentially.

(ii) if (k > = 10)


{
printf (``\n This will not execute, because condition is false “ );
}
Now condition is false so related statement will not executes.

(iii) int a = 7, b = 15;

if (( a < 10) && (b > = 10)


{
printf (``\n value of a = %d'' a);
printf (``\n Value of b = %d'', b);
}
both condition are true hence total condition generate true value & both
statements will execute that print value of a & b display.

if ( Condition ) - else
if (Condition)
{
Statement 1;
Statement 2;
----------------
----------------
Statement N;
}
else
{
Statement 1;
Statement 2;
----------------
----------------
Statement N;
}
if ( ) else format of conditional statement is used when there are only two
conditions & one of them is true.
In other words we can say when one condition is true that ensure that another
one is false and first one is false that ensure that second is true then we use if () else
format of conditional statement.
Else is always used after if & with else condition is never specified. We can use if
without else but vice versa is not true.
if condition is true then statement related with if will executes and statement
related with else skips.
if condition is false then if statement will skip and Else statement will execute.
In short execution of else depend on if. If is true then else will not execute
otherwise else executes.
else part is optional if & Else is not used then it is a simple if conditional
statement.
Example-

int a = 10, b = 25;

if (a > = b)
{
printf (" Value of a = %d is greater ''; a);
} ( * end of if condition */)
else
{
printf (''\n value of b = %d is greater'', b);
}/* end of else part */

Here are only two conditions either value of a is greater or b. So if else format is
used. In this example condition specified with if is false, so if part is skiped and Else
part will execute.

if ( Condition ) - else if ( Condition ) – else

When there are more then two conditions and only one is true then if- else if-else
format is used.
if (condition)
{
Statement block;
}
else if (condition)
{
Statement block;
}
else if (condition)
{
Statement block;
}
else
{
Statement block;
}
The conditions are evaluated from the top to down approach looking for first true
condition.
If all conditions in ladder are false then else part will execute.
else part is optional to use. If else part is not present and none condition is true
then no statement will execute.
int n = 25;

if (n > = 40)
{
printf (" Value of n = %d'', n);
}
else if (n > = 30)
{
printf (" Value of n = %d'', n);
}
else if (n > = 20)
{
printf (" Value of n = %d'', n);
}
else
{
printf (" Value of n = %d'', n);
}

Conditions are checked in Top to Down way & looking for true condition. This
Condition i.e. (n > = 20) is true so related statement will executes & others are
skipped.
With if (Condition), if (Condition)- else or if (Condition)- else if (Condition)- else
ladder, we can use any loop. Statement, Conditional Statement, Jumping Statement
or I/O Statement as a valid Statement.
Switch Statement
C Programming Language has a built in multiple branch selection statement
called switch statement.
Switch tests for equality condition in top to down approach. When condition is
satisfied associate statements are execute and remain part switch is skipped.
Switch only checks for equality and so no Relational operator be can used with
Switch-case statements.
For multiple conditions even we can use if-else if ( ) - else ladder but increasing
depth of if-else if ( )- else ladder makes it difficult to understand so in place of this we
can use switch statement.
According to standard C specification; switch can have at least 257 case
statement, but if may vary from complier to complier.

switch (expression/Switch Variable)


{
case Constants 1;
Statement block 1;
break;

case constant 2;
Statement block 2;
break;

case constant 3;
Statement block 3;
break;

case constant 4;
statement block 4;
break;

default ;
statement block;
} /* end of switch statement */

The value of expression is tested against the value of the constant in the case
statement. When match is found the statement block associate with case will execute.
If none case statement will execute then default execution is performed. Use of
default is optional.
With case we can only use constant or value, i.e. No variable can be used with
case. Expression must be integer or character Floating point expression is not
allowed. No, two case constant in the same switch can have identical values.
Loop Structure

for Loop

The general form of the for statement is:

for (initialization; Condition; Increment Decrement)

Part I Part II Part III

In for loop two semicolon (;) are compulsory part.

(i) Part I (Initialization part) use to assign value to the loop


control variable.
(ii) Part II (condition) is boolean expression. One value of
boolean expression depends on execution of loop. Loop executed fill boolean
expression return True. on false value loop execution terminate.
(iii) Part III used to Increment / Decrement value of control variable.
Increment/Decrement value of control variable depend on loop requirement.
Part III executed each time the loop executed.

int k;
for (k = 0; k ... = 10; k++)
{
printf (``\n%d-Exam '', k);
}

This loop executed 11 times. On starting, value of k is 0, then condition is


checked and after that part III executed, value, of k increase by one. Loop is
executed till condition (part II) is true.

int z;
for (z = 5; z > 0; z –)
{
printf (``\n%d - DAVV '', z);
}

This loop is executed 5 times & each time loop executes, value of z is decrement
by 1. The for loop may be executed zero times if initial loop condition is false.

for (k = 5; k > 10; k++)


{
printf (``\n This will not execute '');
}
Condition i.e. k > 10 is false, So loop will not executed even once.
While loop
While is second loop structure available in C.

while (Condition)
{
Statement 1 ;
Statement 2;

Statement N;
}

While loop is executed till condition is true. When condition is false while loop
execution is terminated and execution control passes to instruction after code.
While loop checks the condition first, if condition is false then loop executes zero
times.

int k = 1;

While (k >= 10)


{
printf (`\n %d = Exam '', k);
k++;
}

This loop is executed 10 times & when value of k became 11 then condition (k <
= 10) is false and loop execution is terminated.
While loop have only 1 part for condition checking, so assignment of value to
control variable is done before loop execution starts.
Value of control variable is increased/decreased within the while loop body.

Do-While
In for & while loop, condition is checked in starting of loop. In do-while loop
always executes at least once because condition is checked in end of loop.

The general form of do-while is

do
{
statement 1;
Statement 2;
Statement N;
}
while (condition);

The most common use of do-while loop is in menu selection function.

int k = 5;
do
{
printf {``This statement executes only once'');
K++;
}
while (k > 10);

This loop is executed once even though condition is false because do-while
check condition in last of loop.

do-while loop executes till condition is true.

in z = 1;

do
{
printf (``\n %d = Exam '', z);
z ++;
}
while (z > = 10);

This loop execute 10 times till value of z is 10; i.e. condition is true.

(i) Example of for loop-


int k;
For (k = 1; k > = 10; K++)
{
printf (``\n %d = DAVV '', k);
} /* End of for loop */

(ii) Example of while-


int k;
k = 1;
;
while (k ... = 10)
{
printf (``\ %d = DAVV '', k);
k++;
} /* end of while loop */

(iii) Example of do-while-


int k ;
k = 1;
do
{
printf (``\n ' %d = DAVV'', k);
k++;
}
while (k > = 10);
Difference

1. In for loop variable initialization, condition checking and modification of


control variable value is performed in single location i.e.
For (k = 1; k > = 10; K++)
{
=
}
But in while & do-while loop these three activity is performed in different
locations.
(ii) Do-while loop executes at least once even when initial condition is false
because condition checking is performed in end of loop.
But in for loop & while loop if initial condition is false loop is executed zero times.

Pointers

Pointer is variable that hold memory address of variables or any other object like
functions. Pointer is useful for three purposes-
1. For Call by reference [Function Calling] - In call by reference, function is
called by passing address of variable(s) instead of passing value(s) to function called.
Pointer(s) are used in formal parameter list of function called in case of call by reference.
Advantage of call by reference is that more than one function can share same memory
location(s).

2. For Dynamic Memory Allocation – In C programming, we use built-in/library


function calloc( ) / malloc( ) / realloc( ) for dynamic memory allocation purpose.
Pointer(s) are used for holding memory address when memory is allocated dynamically.

For example -
int *p;
p = (int) malloc(sizeof (int)) ; /* Dynamic memory allocation */

In above case pointer p hold address of memory allocated.

int a, b, c; /* Static memory allocation */

Above is example of static memory allocation that is used normally in programs.

3. For Array handling

A Pointer declaration consists of three parts i.e. Data Types, *sign and variable
name. For Example-
int *a, *b;
a & b are pointers that hold address of variable of int type.
int n, m;
a = & n; /* a pointer hold address of n variable */
b = &m; /* b pointer hold address of m variable */
float *x, *z;
float j,k;
x & z are pointers that hold address of float type variable.
x = &j; /* pointer hold address of j variable */
z = &k;/*z pointer hold address of k variable */
Operator & means "address of''
With pointers only addition (+, ++) and subtraction (-, –)
operations are allowed. For example-
x++;
- –b;

/* EXAMPLE FOR POINTER */


long Sum (int *x, int *y);/* Prototype */

void main( )
{
int a, b;
long c;
clrscr ();

printf (''\n Addition of two values, using pointers.......'');

print (''\n Enter first Integer value : '')


scanf (''%d'', &a);

printf (''\n Enter second Integer value : '');


scanf (''%d'', &b);

c = Sum (&a, &b);

printf (''\n Result after addition : %d'', c);

getch ();
} /* end of void main () */

long sum (int *x, int *y)


{
return (*x + *y);
} /*end of void Sum */

ARRAY
An array is a collection of variables of the same type and they are referred
through a common name. A specific array element is accessed by using array name
and Index Value of that particular element.
Index value of array elements always starts from zero, i.e. Index value of first
array element is zero. All array elements are located at continuous memory location.
In C language, array element number and boundary checking is responsibility of
program.
The lowest address corresponds to the first array element and the highest
address of the last array element.
Array may be -
(i) One Dimension Array [1-D Array]
(ii) Two Dimension Array [2-D Array]
(iii) Multi Dimension Array [N-D Array]

Array declaration is required when multiple variable declaration requires those


having the same data type. Like if we want to store marks of 100 students, for such
purpose we require 100 variables and we can do this using array of size 100.
String is a array of character , terminated by Null character.

(1) One Dimension Array -


int a[20]
in above example, a is array name. Size of a is 20 i.e. array a has 20 elements.
Array index value from 0 to 19 i. e. a[0] to a[19] .
a[20] = 100 ; /* Invalid */
above statement is invalid because a array have element Number a [0] to a [19]
and we are trying to assign value 100 to element number 20 thus it is in valid
statement.

(ii) Two Dimension Array- [2-D Array or Two-D Array is simplest form of multi-
dimension Array.
Two Dimension array are stored in row-column matrix format. The generalized
form of 2-D array is -
datatype array name [m] [n] ; /*ArrayName [row][column]*/
Where m is number of Row &
n is number of Column
long k[5] [3] ;
Identifier k is name of 2-D array, having 05 rows & 03 columns. Array k have
total 5 x 3 = 15 elements. Array indexing in 2-D array is also start from 0,0 [zero, zero]
location that is very first element of 2-D array.

No of Row x No. of Column = Total No of elements


Total Element in 2-D array k is - 5 x 3 = 15 total elements.

(iii) Multi-Dimension Array [N-D Array] - More then 2-D array is known as
Multi Dimension Array. it may be 3-D, 4-D, 5-D or so on.
Normally more then 3-D array is not used because that requires more time to
calculate element location in main memory and so required more time to access
element values.
The generalize form of N-D array is- Data-type array name [Siz 1] [Size 2] [Size
3] [Size 4] ........ [Size N] ;
Array indexing always start from 0 index value.

Advantages of array

 Array provides efficient way to handle group of variables.


 We can not resize array during program execution but it is not compulsory
to use all elements belong to the array.
 Array is flexible for manipulation purpose so we can read / write / modify
values from any location within array size.
 Array structure is easy to declare and use.
 In C programming array is useful to handle problems / structure like
graph, list of values, graphics etc.

You might also like