0% found this document useful (0 votes)
8 views44 pages

Physics PII Unit IV Computer Programming Complete Notes

The document provides an overview of algorithms and flowcharts, defining algorithms as step-by-step procedures for solving problems and flowcharts as graphical representations of these algorithms. It outlines the steps to design an algorithm, the advantages of flowcharts, and various symbols used in flowcharts. Additionally, it includes examples of algorithms and flowcharts for common programming tasks.

Uploaded by

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

Physics PII Unit IV Computer Programming Complete Notes

The document provides an overview of algorithms and flowcharts, defining algorithms as step-by-step procedures for solving problems and flowcharts as graphical representations of these algorithms. It outlines the steps to design an algorithm, the advantages of flowcharts, and various symbols used in flowcharts. Additionally, it includes examples of algorithms and flowcharts for common programming tasks.

Uploaded by

M.D. Kakhandaki
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link].

VI Semester
Physics, Paper – II
Unit- IV: Computer Programming

What is Algorithm?
Definition:
Algorithm is used to solution of a problem step by step procedure using simple english language. It is the
part of software designing. An algorithm defines as the step by step procedure or method that can be
carried out for solvingprogramming problems. An algorithm tells computer that how to solve problem
systematically to get desired output. Mainly we follow following steps to design an algorithm.

Step 1 - START
It represents beginning of the algorithm.

Step 2 - DECLARE
The variables used in algorithm are declared in this step.

Step 3 - INPUT
Here we input the values

Step 4 - FORMULA
The required result is generated in this step.

Step 5 - OUTPUT
It displays the output or result.

Step 6 - STOP
It is an end of Algorithm

FLOW CHART
Flow chart is a graphical(pictorial) representation of algorithm. It is used to represent algorithm steps into
graphical format. It also gives us an idea to organize the sequence of steps or events necessary to solve a
problem with the computer. In other words flow charts are symbolic diagrams of operations and the sequence,
data flow, control flow and processing logic in information processing. These charts are used to understand any
working sequence of the program.

What are the Advantages(uses) of FLOW CHART?


Ans:Advantages of flowchart:-
1. It provides an easy way of communication because any other person besides the programmer can
understand the way they are represented.
2. It represents the data flow.
3. It provides a clear overview of the entire program and problem and solution.
4. It checks the accuracy in logic flow.
5. It documents the steps followed in an algorithm.
6. It provides the facility for coding.
7. It provides the way of modification of running program.
8. They shows all major elements and their relationship
Basic Flowchart Symbols

There are various flowchart shapes used for drawing different types of flowcharts. Each flowchart symbol has
its own meaning and context where it is used appropriately.

Process/Operation Symbols

Process Symbol Also known as action symbol.


Represents a step in your process.

Sub Process Symbol Represents a sequence of actions


that perform specific tasks within a
larger and more complicated
process, routine, or module.
Delay Symbol Represents a delay in the process.
In Process Mapping, delays are
often important as they may result
in adding to the cost of the product
or simply delaying its production.
Preparation Symbol Indicates the set-up to another step
in the same process

Manual Operation Symbol Represents a process step that


should be performed manually, not
automatically.

Parallel Mode Symbol Also called "Concurren opeartion".


Indicateds two or more
simultaneous operations or process
steps.

Data and Information Storage Symbols

Stored Data Symbol Also known as data storage


symbol. Use this symbol to
indicates where data get stored.

Database Symbol Represents data/information stored


in the storage device that allows for
searching and sorting by users.

Internal Storage Symbol Usually used in the software design


flowcharts and indicates that
data/information is stored in
memory during a program.
Branch and Control of Flow Symbols

Start/End Symbol Indicates the start/end of a process

Arrows and Connecting Lines Use this symbol to connect


different elements and show the
relationships between the shapes.

Decision Symbol Indicates a point where the


outcome of a decision dictates the
next step. There can be multiple
outcomes, but often there are just
two - yes and no.
Yes/No Decision Point Indicates a sequence in the process
at which the end-user chooses an
option, i.e., a "yes-no," or "true-
false" response, and then branches
to different parts of the flowchart.
On-Page Reference Use this symbol to connect separate
processes on the same page of your
flowchart.

Off-Page Reference Also known as off-page connector


or link symbol. Use this symbol to
connect separate processes across
different pages with the page
number written on or within the
shape.
Merge Symbol Indicates that multiple processes or
pathes are combined into one.

Extract Symbol Indicates that multiple processes or


pathes are combined into one.
Or Symbol

Or Symbol Indicates that the process flow


diverges for more than 2 branches.

Summing Junction Symbol Indicates that multiple branches


converge into a single process.

Control Transfer Symbol Indicates a process step that must


go to one step other than the typical
next step, when specific conditions
are met.
Input and Output Symbols

Data(Input/Output) Symbol Indicates that information is


coming into the process from
outside, or leaving the process.

Document Symbol Represents the data that can be read


by people, such as a printed
document or report.

Multi-Documents Symbol Represents the data that can be read


by people, such as a printed
document or report.

Display Symbol Indicates where the information


will be displayed within a process
flow.

Manual Input Symbol Indicates a process step where a


user/operator is prompted to enter
information manually.

Card Symbol Indicates that data is input by using


cards. But this symbol is seldom
used now.

Paper Tape Symbol Indicates that data is stored on page


tapes. But this symbol is also rarely
ever used now.

Data Processing Symbols

Collate Symbol Indicates a process step that


organizes data, information or
materials into a standard format.

Sort Symbol Indicates a process step that


organizes Data, information or
materials into some pre-defined
order.
Algorithm characteristics

1. It should have finite number of steps. No one can be expected to execute infinite number of steps.
2. The steps must be in order and simple
3. Each step should be defined clearly stated i.e. without un-ambiguity (without doubtfulness)
4. Must include all required information
5. Should exhibit at least one output

Algorithm Flowchart Program


An algorithm is defined as A flowchart is pictorial Set of instructions. Instruction is
sequence of steps to solve a (graphical) representation of a command to the computer to
problem (task). an algorithm. do some task.

Algorithm can also be defined as A picture is worth of 1000 Implementation of Algorithm or


a plan to solve a problem and words. We can understand more flowchart
represents its logic. from picture than words.

Different algorithms have different performance characteristics to solve the same problem. Some
algorithms are fast. Some are slow. Some occupy more memory space. Some occupy less memory
space. Some are complex and some algorithms are simple.

Logically algorithm, flowchart and program are the same.

1|Page [Link]/ EngineersTutor [Link]


Examples of Algorithms and Flowcharts (with C code)

1. To find sum of two numbers


Algorithm Flowchart Program

1. Start Start
2. Read a, b
3. c=a+b
4. Print or display c Read a, b
5. Stop

c=a+b

Write c

Stop

2. Finding Area of the square


Algorithm Flowchart Program

Start
1. Start
2. Read length, L
3. area = L*L Read L
4. Print or display area
5. Stop
area = L*L

Write
area

Stop

2|Page [Link]/ EngineersTutor [Link]


3. Finding Area of the rectangle
Algorithm Flowchart Program

Start

1. Start
2. Read side length, a Read a
3. Read side length b
4. area = a*b
5. Print or display area
Read b
6. Stop

area = a*b

Write
area

Stop

4. Area of a triangle where three sides are given


Algorithm Flowchart Program

Start
1. Start
2. Read a, b, c
3. s = (a+b+c)/2
Read a, b, c
4. A=sqrt (s *(s-a)*(s-b)*(s-c))
5. Print or display A
6. Stop
s = (a+b+c)/2
A = sqrt s(s-a)*(s-b)*(s-c)

Write
A

Stop

3|Page [Link]/ EngineersTutor [Link]


5. Find the area & perimeter of a square
Algorithm Flowchart Program

1. Start Start
2. Read length L
3. Area A = L*L
4. Perimeter P = 4*L Read L
5. Print or display A,P
6. Stop
A = L*L
P = 4*L

Write
A, P

Stop

6. Calculating the average for 3 numbers


Algorithm Flowchart Program

1. Start
2. Read 3 numbers A, B, C
3. Calculate the average by
the equation:
Average = (A + B + C)/3
4. Print average
5. Stop

4|Page [Link]/ EngineersTutor [Link]


7. Greatest of two numbers
Algorithm Flowchart Program

1. Start
2. Read A,B
3. If A > B then
Print A is large
else
Print B is large
4. Stop

8. Interchange the value of two numbers


Algorithm Flowchart Program

1. Start
2. Read two values into two variables a, b
3. Declare third variable, c
c=a
a=b
b=c
4. Print or display a, b
5. Stop

5|Page [Link]/ EngineersTutor [Link]


9. Calculate simple interest using the expression (SI=PNR/100)
Algorithm Flowchart Program

Start

1. Start
2. Read P, N, R
3. SI=(PNR)/100 Read P, N, R
4. Print SI
5. Stop
SI = (P*N*R)/100

Write
SI

Stop

10. Convert temperature from Fahrenheit to Celsius


Algorithm Flowchart Program

1. Start
2. Initialize F = 0, C = 0
3. Read F
4. C = (F-32) * 5/9
5. Write C
6. Stop

6|Page [Link]/ EngineersTutor [Link]


11. Draw a flowchart for computing factorial N, where N! = 1 * 2 * 3 * …… N
Algorithm Flowchart Program

Start
1. Start
2. Read N
3. Initialize F =1, i = 1
Read N
4. F = F * i;
5. Increment i by 1
6. Repeat step 4 & 5 until i = N
F=1
7. Print F i=1
8. Stop

F=F*i

i=i+1 No Is
i = N?

Yes

Write F

Stop

7|Page [Link]/ EngineersTutor [Link]


12. Find the Sum of First Five Natural Numbers

Algorithm Flowchart Program

1. Start
2. Initialize count = 0, sum = 0
3. count = count + 1
4. sum = sum + count
5. Repeat steps 3,4 until count > 5
6. Print sum
7. Stop

13. Calculating sum of integers 1 to 100


Algorithm Flowchart Program

1. Start
2. Initialize count i = 1, sum = 0 Start
3. sum = sum + i
4. Increment i by 1
i=1
5. Repeat steps 3 & 4 until i > 100 sum = 0
6. Print sum
7. Stop
sum = sum + i

i=i+1

No Is
i>100?

Yes
Write
sum

Stop

8|Page [Link]/ EngineersTutor [Link]


14. To find the sum of n natural Numbers
Algorithm Flowchart Program

1. Start
2. Read n
3. count=0
4. sum=0
5. count = count + 1
6. sum = sum + count
7. Repeat steps 5 & 6 until
count > n
8. Print sum
9. Stop

9|Page [Link]/ EngineersTutor [Link]


15. Sum of squares of n natural numbers
Algorithm Flowchart Program

Start
1. Start
2. Read n
3. i = 0, sum = 0
Read n
4. i=i+1
5. sum = sum + (i*i)
6. Repeat steps 4 and 5 until i > n
i=0
7. Print sum sum = 0
8. Stop

i=i+1
sum = sum + (i*i)

No Is
i>n

Yes
Write
sum

Stop

10 | P a g e Y o u t u b e . c o m / E n g i n e e r s T u t o r [Link]
16. To find the sum of all even numbers up to ‘n’

Algorithm Flowchart Program

Start
1. Start
2. Read n
3. count=0 READ n
4. sum=0
5. count = count + 2
6. sum = sum + count count = 0
7. Repeat steps 5 & 6 until count ≤ n sum = 0
8. Print sum
9. Stop
count = count+ 2

sum = sum + count

No Is
count ≤ n

Yes
Write
sum

Stop

11 | P a g e Y o u t u b e . c o m / E n g i n e e r s T u t o r [Link]
17. To find Product of numbers up to N

Algorithm Flowchart Program

1. Start Start
2. Read n
3. count i = 1
4. product = 1 READ n
5. product=count*product
6. count = count + 1
7. Repeat steps 5,6 until count ≤ N count i = 1
8. Print product product = 1
9. Stop

count = count + 1
product = product*count

Is
count ≤ n

No

Yes
Write
product

Stop

12 | P a g e Y o u t u b e . c o m / E n g i n e e r s T u t o r [Link]
18. Sum of first 50 odd numbers
Algorithm Flowchart Program

1. Start
2. sum=0, n = 1
3. sum=sum + n
4. n=n+2
5. Repeat steps 4 and 5 until
n ≤ 99
6. Print sum
7. Stop

13 | P a g e Y o u t u b e . c o m / E n g i n e e r s T u t o r [Link]
Basic Structure of C Program

Documentation Section
This section consists of comment lines which include the name of programmer, the author and other details like
time and date of writing the program. Documentation section helps anyone to get an overview of the program.

Link Section
The link section consists of the header files of the functions that are used in the program. It provides instructions
to the compiler to link functions from the system library.

Definition Section
All the symbolic constants are written in definition section. Macros are known as symbolic constants.

Global Declaration Section


The global variables that can be used anywhere in the program are declared in global declaration section. This
section also declares the user defined functions.

main() Function Section


It is necessary have one main() function section in every C program. This section contains two parts, declaration
and executable part. The declaration part declares all the variables that are used in executable part. These two
parts must be written in between the opening and closing braces. Each statement in the declaration and
executable part must end with a semicolon (;). The execution of program starts at opening braces and ends at
closing braces.

Subprogram Section
The subprogram section contains all the user defined functions that are used to perform a specific task. These
user defined functions are called in the main() function.

Comments
Comments are used to clarify something about the program in plain language. It is a way for us to add notes to our
program. There are two types of comments in c:
Single line comment: //This is a comment.
Multi-line comment : /*This is multi-line comment*/
Comments in a C program are not executed and ignored.

Pre-processor commands
In C programming language, preprocessor directive is a step performed before the actual source code
compilation. It is not part of the compilation. Preprocessor directives in C programming language are used to
define and replace tokens in the text and also used to insert the contents of other files into the source file.
When we try to compile a program, preprocessor commands are executed first and then the program gets
compiled.
Every preprocessor command begins with # symbol. We can also create preprocessor commands with
parameters.
Following are the preprocessor commands in C programming language.

#include #include is used to insert specific header file into C program.


#define #define is used to create symbolic constants (known as macros) in C programming language
#undef #undef is used to destroy a macro that was already created using #define
#ifdef #ifdef returns TRUE if the macro is defined and returns FALSE if the macro is not defined.
#ifndef #ifndef returns TRUE if the specified macro is not defined otherwise returns FALSE.
#if #if uses the value of specified macro for conditional compilation
#else #else is an alternative for #if.
#elif #elif is a #else followed by #if in one statement.
#endif #endif is used terminate preprocessor conditional macro.
#error #error is used to print error message on stderr
#pragma #pragma is used to issue a special command to the compiler

Header File
A header file is a file with extension .h which contains C function declarations and macro definitions to be
shared between several source files.

#include <stdio.h>

It tells our program that before its execution, it must include the stdio.h named file in it because we are using
some of the commands or codes from this file.

If our programs needs mathematical operations of high level then we must include #include <math.h>

C Tokens
Every C program is a collection of instructions and every instruction is a collection of some individual units.
Every smallest individual unit of a c program is called token. Every instruction in a c program is a collection of
tokens. Tokens are used to construct c programs and they are said to be the basic building blocks of a c
program.

In a c program tokens may contain the following...


1) Keywords
2) Identifiers
3) Operators
4) Special Symbols
5) Constants
6) Strings
7) Data values

In a C program, a collection of all the keywords, identifiers, operators, special symbols, constants, strings, and
data values are called tokens.
Tokens are the smallest elements of a program, which are meaningful to the compiler.

1) Keywords
Keywords are predefined, reserved words in C and each of which is associated with specific features. These
words help us to use the functionality of C language. They have special meaning to the compilers.

There are total 32 keywords in C.

auto double int struct


break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

2) Identifiers
Each program element in C programming is known as an identifier. They are used for naming of variables,
functions, array etc. These are user-defined names which consist of alphabets, number, underscore ‘_’.
Identifier’s name should not be same or same as keywords. Keywords are not used as identifiers.

Rules for naming C identifiers −


1. It must begin with alphabets or underscore.
2. Only alphabets, numbers, underscore can be used, no other special characters, punctuations are
allowed.
3. It must not contain white-space.
4. It should not be a keyword.
5. It should be up to 31 characters long

C Constants

A constant is a named memory location which holds only one value throughout the program execution.
In C programming language, a constant can be of any data type like integer, floating-point, character, string and
double, etc.,

Integer constants
An integer constant can be a decimal integer or octal integer or hexadecimal integer. A decimal integer value is
specified as direct integer value whereas octal integer value is prefixed with 'o' and hexadecimal value is
prefixed with 'OX'.
An integer constant can also be unsigned type of integer constant or long type of integer constant. Unsigned
integer constant value is suffixed with 'u' and long integer constant value is suffixed with 'l' whereas unsigned
long integer constant value is suffixed with 'ul'.
Example
125 -----> Decimal Integer Constant
O76 -----> Octal Integer Constant
OX3A -----> Hexa Decimal Integer Constant
50u -----> Unsigned Integer Constant
30l -----> Long Integer Constant
100ul -----> Unsigned Long Integer Constant
Floating Point constants
A floating-point constant must contain both integer and decimal parts. Some times it may also contain the
exponent part. When a floating-point constant is represented in exponent form, the value must be suffixed with
'e' or 'E'.
Example
The floating-point value 3.14 is represented as 3E-14 in exponent form.

Character Constants
A character constant is a symbol enclosed in single quotation. A character constant has a maximum length of
one character.

Example
'A'
'2'
'+'
In the C programming language, there are some predefined character constants called escape sequences. Every
escape sequence has its own special functionality and every escape sequence is prefixed with '\' symbol. These
escape sequences are used in output function called 'printf()'.
String Constants
A string constant is a collection of characters, digits, special symbols and escape sequences that are enclosed in
double quotations.

We define string constant in a single line as follows...


"This is c programming notes"

We can define string constant using multiple lines as follows...


" This\
is\
c programming notes "

We can also define string constant by separating it with white space as follows...
"This" "is" " c programming notes "

All the above three defines the same string constant.

Creating constants in C
In a c programming language, constants can be created using two concepts...
1. Using the 'const' keyword
2. Using '#define' preprocessor
1. Using the 'const' keyword
We create a constant of any datatype using 'const' keyword. To create a constant, we prefix the variable
declaration with 'const' keyword.
The general syntax for creating constant using 'const' keyword is as follows...
const datatype constantName ;
OR

const datatype constantName = value ;

C Variables
Variable is a name given to a memory location where we can store different values of the same
datatype during the program execution.
Every variable in c programming language must be declared in the declaration section before it is used.
Every variable must have a datatype that determines the range and type of values be stored and the size of the
memory to be allocated.
Rules
A variable name may contain letters, digits and underscore symbol. The following are the rules to
specify a variable name...
Variable name should not start with a digit.
Keywords should not be used as variable names.
A variable name should not contain any special symbols except underscore(_).
A variable name can be of any length but compiler considers only the first 31 characters of the variable
name.
Declaration of Variable
Declaration of a variable tells the compiler to allocate the required amount of memory with the specified
variable name and allows only specified datatype values into that memory location. In C programming
language, the declaration can be performed either before the function as global variables or inside any
block or function. But it must be at the beginning of block or function.
Declaration Syntax:
datatype variableName;
Example
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the name number and
allows only integer values into that memory location.

Types of Variables in C
1. Local Variable
A variable that is declared and used inside the function or block is called local variable.
It’s scope is limited to function or block. It cannot be used outside the [Link] variables need
to be initialized before use.
Example

#include <stdio.h>
void function()
{
int x = 10; // local variable
}
int main()
{
function();
}
In the above code x can be used only in the scope of function() . Using it in main function
will give error.
2. Global Variable
A variable that is declared outside the function or block is called a global variable.
It is declared at the starting of program. It is available to all the functions.
Example

#include <stdio.h>
int x = 20; //global variable
void function1()
{
printf("%d\n" , x);
}
void function2()
{
printf("%d\n" , x);
}
int main()
{
function1();
function2();
return 0;
}

Output
20
20

In the above code both the functions can use global variable x as we already global variables
are accessible by all the functions.

[Link] Variable
A variable that retains its value between multiple function calls is known as static variable.
It is declared with the static keyword.
Example-

#include <stdio.h>
void function()
{
int x = 20;//local variable
static int y = 30;//static variable
x = x + 10;
y = y + 10;
printf("\n%d,%d",x,y);
}
int main()
{

function();
function();
function();
return 0;
}

Output
30,40
30,50
30,60

In the above example , local variable will always print same value whenever function will be
called whereas static variable will print the incremented value in each function call.

[Link] Variable
All variables in C that are declared inside the block, are automatic variables by default. We
can explicitly declare an automatic variable using auto keyword. Automatic variables are similar as
local variables.
Example

#include <stdio.h>
void function()
{
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
int main()
{

function();
return 0;
}

In the above example both x and y are automatic variables .The only difference is that variable
y is explicitly declared with auto keyword.

[Link] Variable
External variable can be shared between multiple C [Link] can declare external variable
using extern keyword.
Example:
myfile.h
extern int x=10;//external variable (also global)
program1.c
#include "myfile.h"
#include <stdio.h>
void printValue()
{
printf("Global variable: %d", global_variable);
}
In the above example x is an external variable which is used in multiple files

C data types
The formal definition of a data type is as follows...
The Data type is a set of value with predefined characteristics. data types are used to declare variable,
constants, arrays, pointers, and functions.
In the c programming language, data types are classified as follows...
Primary data types (Basic data types OR Predefined data types)
Derived data types (Secondary data types OR User-defined data types)
Enumeration data types
Void data type

Primary data types


The primary data types in the C programming language are the basic data types. All the primary data
types are already defined in the system. Primary data types are also called as Built-In data types. The
following are the primary data types in c programming language...
1. Integer data type
2. Floating Point data type
3. Double data type
4. Character data type
Integer Data type
The integer data type is a set of whole numbers. Every integer value does not have the decimal
value. We use the keyword "int" to represent integer data type in c. We use the keyword int to
declare the variables and to specify the return type of a function. The integer data type is used
with different type modifiers like short, long, signed and unsigned. The following table provides
complete details about the integer data type.

Floating Point data types


Floating-point data types are a set of numbers with the decimal value. Every floating-point value
must contain the decimal value. The floating-point data type has two variants: float and double
We use the keyword "float" to represent floating-point data type and "double" to represent
double data type in c. Both float and double are similar but they differ in the number of decimal
places. The float value contains 6 decimal places whereas double value contains 15 or 19
decimal places. The following table provides complete details about floating-point data types.
Character data type
The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.

Enumerated data type


An enumerated data type is a user-defined data type that consists of integer constants and each integer
constant is given a name. The keyword "enum" is used to define the enumerated data type.

void data type


The void data type means nothing or no value. Generally, the void is used to specify a function which
does not return any value. We also use the void data type to specify empty parameters of a function.

Derived data types


Derived data types are user-defined data types. The derived data types are also called as user-defined
data types or secondary data types. In the c programming language, the derived data types are created
using the following concepts...Arrays,Structures,Unions,Enumeration

Operators in C
An operator is a symbol used to perform arithmetic and logical operations in a program. That means an operator
is a special symbol that tells the compiler to perform mathematical or logical operations. C programming
language supports a rich set of operators that are classified as follows.

Arithmetic Operators
Relational Operators
Logical Operators
Increment & Decrement Operators
Assignment Operators
Bitwise Operators
Conditional Operator
Special Operators

Arithmetic Operators (+, -, *, /, %)

The arithmetic operators are the symbols that are used to perform basic mathematical operations like
addition, subtraction, multiplication, division and percentage modulo. The following table provides
information about arithmetic operators.
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Remainder of the Division 5%2=1
⇒ The addition operator can be used with numerical data types and character data type. When it is used
with numerical values, it performs mathematical addition and when it is used with character data type
values, it performs concatination (appending).

⇒ The remainder of the division operator is used with integer data type only.

Relational Operators (<, >, <=, >=, ==, !=)

The relational operators are the symbols that are used to compare two values. That means the relational
operators are used to check the relationship between two values. Every relational operator has two
results TRUE or FALSE. In simple words, the relational operators are used to define conditions in a
program. The following table provides information about relational operators.

Operator Meaning Example


< Returns TRUE if the first value is smaller than second value otherwise 10 < 5 is FALSE
returns FALSE
> Returns TRUE if the first value is larger than second value otherwise returns 10 > 5 is TRUE
FALSE
<= Returns TRUE if the first value is smaller than or equal to second value 10 <= 5 is FALSE
otherwise returns FALSE
>= Returns TRUE if the first value is larger than or equal to second value 10 >= 5 is TRUE
otherwise returns FALSE
== Returns TRUE if both values are equal otherwise returns FALSE 10 == 5 is FALSE
!= Returns TRUE if both values are not equal otherwise returns FALSE 10 != 5 is TRUE

Logical Operators (&&, ||, !)

The logical operators are the symbols that are used to combine multiple conditions into one condition.
The following table provides information about logical operators.

Operator Meaning Example


&& Logical AND - Returns TRUE if all conditions are TRUE otherwise returns 10 < 5 && 12 >
FALSE 10 is FALSE
|| Logical OR - Returns FALSE if all conditions are FALSE otherwise returns 10 < 5 || 12 > 10
TRUE is TRUE
! Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if it !(10 < 5 && 12 >
is TRUE 10) is TRUE
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE
then complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE
then complete condition becomes TRUE.

Increment & Decrement Operators (++ & --)

The increment and decrement operators are called unary operators because both need only one operand.
The increment operators adds one to the existing value of the operand and the decrement operator
subtracts one from the existing value of the operand. The following table provides information about
increment and decrement operators.

Operator Meaning Example


++ Increment - Adds one to existing value int a = 5;
a++; ⇒ a = 6
-- Decrement - Subtracts one from existing value int a = 5;
a--; ⇒ a = 4

The increment and decrement operators are used infront of the operand (++a) or after the operand (a++).
If it is used infront of the operand, we call it as pre-increment or pre-decrement and if it is used after
the operand, we call it as post-increment or post-decrement.

Pre-Increment or Pre-Decrement

In the case of pre-increment, the value of the variable is increased by one before the expression
evaluation. In the case of pre-decrement, the value of the variable is decreased by one before the
expression evaluation. That means, when we use pre-increment or pre-decrement, first the value
of the variable is incremented or decremented by one, then the modified value is used in the
expression evaluation.
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 5,j;
j = ++i; // Pre-Increment
printf("i = %d, j = %d",i,j);
}
Output:
i = 6, j = 6

Post-Increment or Post-Decrement

In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after the
expression evaluation. That means, when we use post-increment or post-decrement, first the
expression is evaluated with existing value, then the value of the variable is incremented or
decremented by one. Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 5,j;
j = i++; // Post-Increment
printf("i = %d, j = %d",i,j);
}
Output: i = 6, j = 5

Assignment Operators (=, +=, -=, *=, /=, %=)


The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable
(Lvalue). The assignment operator is used in different variants along with arithmetic operators. The
following table describes all the assignment operators in the C programming language.

Operator Meaning Example


= Assign the right-hand side value to left-hand side variable A = 15
+= Add both left and right-hand side values and store the result into left-hand A += 10
side variable ⇒ A = A+10
-= Subtract right-hand side value from left-hand side variable value and store A -= B
the result ⇒ A = A-B
into left-hand side variable
*= Multiply right-hand side value with left-hand side variable value and store A *= B
the result ⇒ A = A*B
into left-hand side variable
/= Divide left-hand side variable value with right-hand side variable value and A /= B
store the result ⇒ A = A/B
into the left-hand side variable
%= Divide left-hand side variable value with right-hand side variable value and A %= B
store the remainder ⇒ A = A%B
into the left-hand side variable

Bitwise Operators (&, |, ^, ~, >>, <<)


The bitwise operators are used to perform bit-level operations in the c programming language. When we
use the bitwise operators, the operations are performed based on the binary values. The following table
describes all the bitwise operators in the C programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).

Operator Meaning Example


& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16 (10000)
| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A|B
⇒ 29 (11101)
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)
~ the result of Bitwise once complement is negation of the bit (Flipping) ~A
⇒ 6 (00110)
<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100 (1100100)
>> the Bitwise right shift operator shifts all the bits to the right by the A >> 2
specified number of positions ⇒ 6 (00110)

Conditional Operator (?:)


The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first we verify a condition, then we perform one
operation out of the two operations based on the condition result. If the condition is TRUE the first
option is performed, if the condition is FALSE the second option is performed. The conditional operator
is used with the following syntax.

Condition ? TRUE Part : FALSE Part;

Example
A = (10<15)?100:200; ⇒ A value is 100

Special Operators (sizeof, pointer, comma, dot, etc.)

The following are the special operators in c programming language.

sizeof operator

This operator is used to find the size of the memory (in bytes) allocated for a variable.
This operator is used with the following syntax.
sizeof(variableName);
Example
sizeof(A); ⇒ the result is 2 if A is an integer

Pointer operator (*)

This operator is used to define pointer variables in c programming language.

Comma operator (,)

This operator is used to separate variables while they are declaring, separate the
expressions in function calls, etc.

Dot operator (.)

This operator is used to access members of structure or union.

Decision Making Statement


Decision-making statements are the statements that are used to verify a given condition and decide
whether a block of statements gets executed or not based on the condition result.
In the c programming language, there are two decision-making statements they are as follows.
1. if statement
2. switch statement

if statement in c
In c, if statement is used to make decisions based on a condition. The if statement verifies the given
condition and decides whether a block of statements are executed or not based on the condition result. In
c, if statement is classified into four types as follows...
a) if statement
b) if-else statement
c) Nested if statement
d) if-else-if statement (if-else ladder)

a) if statement
if statement is used to verify the given condition and executes the block of statements based on the
condition result. The simple if statement evaluates specified condition. If it is TRUE, it executes the
next statement or block of statements. If the condition is FALSE, it skips the execution of the next
statement or block of statements. The general syntax and execution flow of the simple if statement is as
follows.
Simple if statement is used when we have only one option that is executed or skipped based on a
condition.

Example Program | Test whether given number is divisible by 5.

#include<stdio.h>
#include<conio.h>

void main()
{
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5\n") ;
printf("statement does not belong to if!!!") ;
}
Output 1:
Enter any integer number:15
Given number is divisible by 5
statement does not belong to if!!!

Output 2:
Enter any integer number:18
statement does not belong to if!!!

b) if-else statement
The if-else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The if-else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is
FALSE, it executes another block of statements (False block). The general syntax and execution
flow of the if-else statement is as follows.

The if-else statement is used when we have two options and only one option has to be executed
based on a condition result (TRUE or FALSE).

Example Program
Test whether given number is even or odd.
#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ;
}
Output 1:
Enter any integer number: 10
Given number is EVEN

Output 2:
Enter any integer number: 13
Given number is ODD

c) Nested if statement

Writing a if statement inside another if statement is called nested if statement. The general syntax
of the nested if statement is as follows...
The nested if statement can be defined using any combination of simple if & if-else statements.
Example Program |
Test whether given number is even or odd if it is below 100.
#include<stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
Output 1:
Enter any integer number:75
Given number is below 100
And it is ODD
Output 2: Enter any integer number:200
Given number is not below 100

d) if-else-if statement (if-else ladder)

Writing a if statement inside else of an if statement is called if-else-if statement. The general
syntax of the if-else-if statement is as follows...

The if-else-if statement can be defined using any combination of simple if & if-else statements.
Example Program | Find the largest of three numbers.
#include<stdio.h>
#include<conio.h>
void main()
{
int a, b, c ;
clrscr() ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;

if( a>=b && a>=c)


printf("%d is the largest number", a) ;

else if (b>=a && b>=c)


printf("%d is the largest number", b) ;

else
printf("%d is the largest number", c) ;
}
Output:
Enter any three integer numbers: 10 20 30
30 is the largest number

Looping statements in C
The looping statements are used to execute a single statement or block of statements repeatedly until the given
condition is FALSE.

C language provides three looping statements...

1. while statement
2. do-while statement
3. for statement

1. while Statement
The while statement is used to execute a single statement or block of statements repeatedly as long as
the given condition is TRUE. The while statement is also known as Entry control looping statement.
The while statement has the following syntax...

The while statement has the following execution flow diagram...


At first, the given condition is evaluated. If the condition is TRUE, the single statement or block of
statements gets executed. Once the execution gets completed the condition is evaluated again. If it is
TRUE, again the same statements get executed. The same process is repeated until the condition is
evaluated to FALSE. Whenever the condition is evaluated to FALSE, the execution control moves out
of the while block.
Example Program
Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
getch() ;
}
When we use a while statement, we must follow the following.
1. while is a keyword so it must be used only in lower case letters.
2. If the condition contains a variable, it must be assigned a value before it is used.
3. The value of the variable used in condition must be modified according to the
requirement inside the while block.
4. In a while statement, the condition may be a direct integer value, a variable or a
condition.
5. A while statement can be an empty statement.

2. do-while' statement in C
The do-while statement is used to execute a single statement or block of statements repeatedly as
long as given the condition is TRUE. The do-while statement is also known as the Exit control
looping statement. The do-while statement has the following syntax...
The do-while statement has the following execution flow diagram...

At first, the single statement or block of statements which are defined in do block are executed.
After the execution of the do block, the given condition gets evaluated. If the condition is
evaluated to TRUE, the single statement or block of statements of do block are executed again.
Once the execution gets completed again the condition is evaluated. If it is TRUE, again the
same statements are executed. The same process is repeated until the condition is evaluated to
FALSE. Whenever the condition is evaluated to FALSE, the execution control moves out of the
while block.
Example Program
Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>

void main()
{
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;
getch() ;
}
MOST IMPORTANT POINTS TO BE REMEMBERED
1. When we use the do-while statement, we must follow the following...
2. Both do and while are keywords so they must be used only in lower case letters.
3. If the condition contains a variable, it must be assigned a value before it is used.
4. The value of the variable used in the condition must be modified according to the
requirement inside the do block.
5. In a do-while statement, the condition may be a direct integer value, a variable or a
condition.
6. A do-while statement can be an empty statement.
7. In do-while, the block of statements is executed at least once.

3. 'for' statement in C

The for statement is used to execute a single statement or a block of statements repeatedly as long as the
given condition is TRUE. The for statement has the following syntax and execution flow diagram...

At first, the for statement executes initialization followed by condition evaluation. If the

condition is evaluated to TRUE, the single statement or block of statements of for statement are

executed. Once the execution gets completed, the modification statement is executed and again

the condition is evaluated. If it is TRUE, again the same statements are executed. The same

process is repeated until the condition is evaluated to FALSE. Whenever the condition is
evaluated to FALSE, the execution control moves out of the for block.
Example Program
Program to display even numbers upto 10.
#include<stdio.h>
#include<conio.h>
void main()
{
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
for( n = 0 ; n <= 10 ; n++ )
{
if( n%2 == 0)
printf("%d\t", n) ;
}
getch() ;
}

Output:

MOST IMPORTANT POINTS TO BE REMEMBERED


When we use for statement, we must follow the following...
1. for is a keyword so it must be used only in lower case letters.
2. Every for statement must be provided with initialization, condition, and
modification (They can be empty but must be separated with ";")
Ex: for ( ; ; ) or for ( ; condition ; modification ) or for ( ; condition ; )
3. In for statement, the condition may be a direct integer value, a variable or a
condition.
4. The for statement can be an empty statement.

break, continue and goto in C


In c, there are control statements that do not need any condition to control the program execution flow. These

control statements are called as unconditional control statements. C programming language provides the

following unconditional control statements.

1. Break

2. Continue

3. goto
The above three statements do not need any condition to control the program execution flow.

1. break statement
In C, the break statement is used to perform the following two things.
a) break statement is used to terminate the switch case statement
b) break statement is also used to terminate looping statements like while, do-
while and for.
When a break statement is encountered inside the switch case statement, the execution control moves

out of the switch statement directly. For example, consider the following program.
Example Program to perform all arithmetic operations using switch statement.
#include<stdio.h>
#include<conio.h>
void main(){
int number1, number2, result ;
char operator;
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &number1, &number2) ;
printf("Please enter any arithmetic operator: ");
operator = getchar();
switch(operator)
{
case '+': result = number1 + number2 ;
printf("Addition = %d", result) ;
break;
case '-': result = number1 - number2 ;
printf("Subtraction = %d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication = %d", result) ;
break;
case '/': result = number1 / number2 ;
printf("Division = %d", result) ;
break;
case '%': result = number1 % number2 ;
printf("Remainder = %d", result) ;
break;
default: printf("\nWrong selection!!!") ;
}
getch() ;
}

Output:

When the break statement is encountered inside the looping statement, the execution control
moves out of the looping statements. The break statement execution is as shown in the following
figure.

For example, consider the following example program...


Example Program for break statement.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch ;
clrscr() ;
do
{
printf("Enter Y / N : ") ;
scanf("%c", &ch) ;
if(ch == 'Y')
{
printf("Okay!!! Repeat again !!!\n") ;
}
else
{
printf("Okay !!! Breaking the loop !!!") ;
break ;
}
} while( 1 ) ;
getch() ;
}

Output:

2. continue statement

The continue statement is used to move the program execution control to the beginning of the looping

statement. When the continue statement is encountered in a looping statement, the execution control
skips the rest of the statements in the looping block and directly jumps to the beginning of the loop.
The continue statement can be used with looping statements like while, do-while and for.

When we use continue statement with while and do-while statements the execution control directly

jumps to the condition. When we use continue statement with for statement the execution control

directly jumps to the modification portion (increment/decrement/any modification) of the for loop.
The continue statement execution is as shown in the following figure.
Example Program Program to illustrate continue statement.
#include<stdio.h>
#include<conio.h>
void main()
{
int number ;
clrscr() ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{
printf("Entered number is EVEN!!! Try another number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD number!!! Bye!!!") ;
exit(0) ;
}
}
getch() ;
}

Output:
3. goto statement
The goto statement is used to jump from one line to another line in the program. Using goto statement
we can jump from top to bottom or bottom to top. To jump from one line to another line, the goto
statement requires a label. Label is a name given to the instruction or line in the program. When we use
a goto statement in the program, the execution control directly jumps to the line with the specified label.
Example Program for goto statement.
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}

Output:

MOST IMPORTANT POINTS TO BE REMEMBERED

When we use break, continue and goto statements, we must follow the following...

 The break is a keyword so it must be used only in lower case letters.


 The break statement can not be used with if statement.
 The break statement can be used only in switch case and looping statements.
 The break statement can be used with if statement, only if that if statement is written inside the switch
case or looping statements.
 The continue is a keyword so it must be used only in lower case letters.
 The continue statement is used only within looping statements.
 The continue statement can be used with if statement, only if that if statement is written inside the
looping statements.
 The goto is a keyword so it must be used only in lower case letters.
 The goto statement must require a label.
 The goto statement can be used with any statement like if, switch, while, do-while, and for, etc.

You might also like