POP Module 1 & Module 2 Notes
POP Module 1 & Module 2 Notes
MODULE 01
INRODUCTION TO C
1.1 Introduction
Computers have become the basic necessity of any organization with serious
objectives. They have made great inroads in everyone’s everyday life and thinking. They are
used in engineering simulations, teaching, satellite control weather forecasting, etc. Literally,
there is no field left without the use of computers. Types of computers, characteristics, details
about software, input and output devices and role of computers in network is dealt in this
particular topic.
Engine made by Babbage. A programming language (Ada) has been named after
her. In 1847-49, Babbage designed his second version of Difference Engine but he could not
complete it. The same machine was conceived in 1991 by the Science Museum in Kensington,
England, and it worked!
In 185, George Bool developed Boolean Logic, which is a system for symbolic and
logical reasoning and the basis for computer design. In 1890, computations for the US Census
were carried out by Herman Hollerith’s punched card machine. Hollerith started Tabulating
Company, which eventually became IBM.
Before the 20th century, all the machines were mechanical. With the advent of
vacuum tubes, the electronics era of computers started. In 1944, Harvard Mark I, the first large
scale, automatic, general purpose, electromechanical calculator driven by a paper tape
containing the instructions was constructed. In the second version of this machine, Grace
Hopper, found the first computer bug, a bug beaten to death in the jaws of a relay, which she
glued into the logbook. The logbook is now in the National Museum of American History of
the Smithsonian.
The first electronic computer, ENIAC (Electronic Numerical Integrator And
Computer) was built in 1946. It was programmed through rewiring between the various
components. After this, many machines like EDVAC, IBM 701, 704 were built and some of
them were commercially successful at that time because they used transistors in place of
vacuum tubes thereby increasing the reliability and performance.
Digital Computers:
➢ Class of devices capable of solving problems by processing information
in discrete forms. It operates on data, including magnitudes, letters and
symbols that are expressed in binary code, i.e., using only the two digits 0
and 1.
➢ By counting, comparing and manipulating these digits or their combinations
according to a set of instructions held in its memory, a digital computer can
perform such tasks as to control industrial processes and regulate the
operations of machines; analyze and organize vast amounts of business
data; and simulate the behavior of dynamic systems (e.g., global weather
patterns and chemical reactions) in scientific research.
Functional Elements:
A typical digital computer system has four basic functional elements:
(1) input-output equipment, (2) main memory, (3) control unit, and (4) arithmetic
logic unit.
➢ Any of a number of devices is used to enter data and program instructions
into a computer and to gain access to the results of the processing operation.
Common input devices include keyboards and optical scanners; output
devices include printers and monitors.
➢ The information received by a computer from its input unit is stored in the
main memory or, if not for immediate use, in an auxiliary storage device.
➢ The control unit selects and calls up instructions from the memory in
appropriate sequence and relays the proper commands to the appropriate unit.
➢ It also synchronizes the varied operating speeds of the input and output
devices to that of the arithmetic logic unit (ALU) so as to ensure the proper
movement of data through the entire computer system.
➢ The ALU performs the arithmetic and logic algorithms selected to process the
incoming data at extremely high speeds—in many cases in nanoseconds
(billionths of a second).
➢ The main memory, control unit and ALU, together make up the Central
Processing Unit (CPU) of most digital computer systems, while the input-
output devices and auxiliary storage units constitute peripheral equipment.
Analog Computers
➢ An analog computer is a computer which is used to process analog data.
Analog computers store data in a continuous form of physical quantities
and perform calculations with the help of measures.
➢ It is quite different from the digital computer, which makes use of symbolic
numbers to represent results. Analog computers are excellent for situations
which require data to be measured directly without converting into
numerals or codes. Analog computers, although available and used in
industrial and scientific applications like control systems and aircraft, have
been largely replaced by digital computers due to the wide range of
complexities involved.
➢ Analog computers were the earliest computer machines developed and were
among the most complicated machines for analog computation and process
control. Analog data is not discrete, but rather is of a continuous nature.
➢ Examples of such data are pressure, temperature, voltage, speed and weight.
An analog computer makes use of continuous values and not discrete
values. Because of this, processes with an analog computer cannot be
repeated for exact equivalent results.
➢ Unlike digital computers, analog computers are immune to quantization
noise. Some of the common computing elements found in analog computers
are function generators, integrators, comparators and multipliers. Depending
on the application, other specialized components can also be used.
Programming on an analog computer involves
➢ Real-time operation and simultaneous computation are possible with the
help of analog computers. Analog computers can also provide the insight of
the problems and errors in case of analog issues for users.
Hybrid Computer
➢ A hybrid is a combination of digital and analog computers. It combines the
best features of both types of computers, i.e., it has the speed of analog
computer and the memory and accuracy of digital computer.
➢ Hybrid computers are used mainly in specialized applications where both
kinds of data need to be processed. they help the user to process both
continuous and discrete data.
➢ For example, a petrol pump contains a processor that converts fuel flow
measurements into quantity and price values.
➢ In hospital Intensive Care Unit (ICU), an analog device is used which
measures patient’s blood pressure and temperature, etc., which are then
converted and displayed in the form of digits. Hybrid computers, for
example, are used for scientific calculations, in defense and radar systems.
➢ Supercomputer,
➢ Mainframe,
➢ Minicomputer and
➢ Microcomputer
Supercomputer
➢ The most powerful computers in terms of performance and
data processing are the Supercomputers.
➢ These are specialized and task specific computers used by
large organizations.
➢ These computers are used for research and exploration
purposes, like NASA uses supercomputers for launching
space shuttles, controlling them and for space exploration
purpose.
➢ The supercomputers are very expensive and very large in
size. It can be accommodated in large air-conditioned
rooms, some super computers can span an entire building.
Applications of Supercomputer
➢ Used to forecast the weather and global climates
➢ Used in military research and defence systems
➢ In automobile, aircraft and space craft designing
➢ In encrypting and decoding sensitive intelligence information
➢ Used in seismography, plasma and nuclear research
➢ Protein folding analysis
➢ Study of DNA structure and gene engineering
➢ Digital film rendering
Mainframe Computer
➢ Although Mainframes are not as powerful as supercomputers, but certainly they are
quite expensive nonetheless, and many large firms and government organizations
uses mainframes to run their business operations.
➢ The Mainframe computers can be accommodated in large air- conditioned rooms
because of its size. Supercomputers are the fastest computers with large data storage
capacity.
➢ Mainframes can also process and store large amount of data. Banks educational
institutions and insurance companies use mainframe computers to store data about
their customers, students and insurance policy holders.
Minicomputer
➢ Minicomputers are used by small businesses and firms. Minicomputers are
also called as “Mid- range Computers”.
➢ These are small machines and can be accommodated on a disk with not as
processing and data storage capabilities as supercomputers and mainframes.
These computers are not designed for a single user.
➢ Individual departments of a large company or organizations use
Minicomputers for specific purposes. For example, a production department
can use Minicomputers for monitoring certain production process.
Popular Minicomputers
➢ K-202
➢ Texas Instrument TI-990
➢ SDS-92
➢ IBM Mid-range Computers
CPU
MemoryUnit
InputUnit OutputUnit
ControlUnit
Arithmeticand
Logic Unit
➢ Input device accepts the coded information as source program i.e. high-level
language. This is either stored in the memory or immediately used by the
processor to perform the desired operations.
➢ Finally, the results are sent to the outside world through output device. All of
these actions are coordinated by the control unit.
➢ Memory unit: - Its function into store programs and data. It is basically to two types
1. Primary memory 2. Secondary memory 1. Primary memory: - Is the one
exclusively associated with the processor and operates at the electronics speeds
programs must be stored in this memory while they are being executed.
➢ The memory contains a large number of semiconductors storage cells. Each ALU
Processor Control Unit www.edutechlearners.com 3 of 268 COMPUTER
ORGANIZATION capable of storing one bit of information. These are processed in
a group of fixed sites called word.
o Arithmetic logic unit (ALU):- Most of the computer operators are executed
in ALU of the processor like addition, subtraction, division, multiplication,
etc. the operands are brought into the ALU from memory and stored in high
speed storage elements called register.
o The control and the ALU are may times faster than other devices connected
to a computer system.
➢ Output unit:- These actually are the counterparts of input unit. Its basic function is
to send the processed results to the outside world.
➢ The CPU has an internal bus for communication with the Combina-
Output
internal cache memory, called the backside bus. Input tional
Logic
➢ The main bus for data transfer to and from the CPU,
memory, chipset, and AGP socket is called the front-side Main
Memor
y
bus.
➢ The CPU contains internal memory units, which are called registers. These
registers contain data, instructions, counters and addresses used in the ALU’s
information processing.
➢ These consist of separate physical CPUs located side by side on the same board or
on separate boards. Each CPU has an independent interface, separate cache, and
individual paths to the system front-side bus.
➢ Multiple processors are ideal for intensive parallel tasks requiring multitasking.
Multicore CPUs are also common, in which a single chip contains multiple CPUs.
Overview of C
INTRODUCTION
➢ A program is a set of instructions for a computer to perform a specified task. C is
a high-level language.
Preprocessor directives
Comment lines
Global Declarations
void main()
{
declaration section
statements
input statement
operational statements
output statements
}
Preprocessor Directives
➢ The preprocessor accepts the source program and prepare the source program for
compilation.
➢ The #include directive instructs the preprocessor to include the specified file-contents in
the beginning of the program.
#include<stdio.h>
Global Declarations
Variables which are declared globally can be used by or accessible from any function
present in a program.
main()
➢ Function is a set of statements which performs a specific task.
➢ Every C program should have a function called as main().
➢ This the first function to be executed always.
➢ The statements enclosed within left and right brace is called body of the
function.
Executable Section
This contains the instructions given to the computer to perform a specific task.
The task may be to display a message, read data, Comments are portions of the code
ignored by the compiler. The comments allow the user to make simple notes in the
source-code.
Before you play the game, you should learn rules of the game. So that you can play better and
win easily. In the same way, to write C programs, you should learn rules of C language.
Step 2: Then, you should learn how to group alphabets in particular sequence to form a meaningful
word. In the same way, in C language, you should learn tokens (i.e. words).
Step 3: Then, you should learn how to group the words in particular sequence to form a meaningful
sentence. In the same way, in C language, you should learn instruction (i.e. sentence).
Step 4: Then, you should learn how to group the sentences in particular sequence to form a
meaningful paragraph. In the same way, in C language, you should learn program (i.e.
paragraph).
CHARACTER SET
➢ Character-set refers to the set of alphabets, letters and some special characters that are
valid in C language.
➢ There are 256 characters in a Character set.
KEYWORDS
A token which has predefined meaning in C language is called a keyword.
➢ Keywords are tokens which are used for their intended purpose only.
➢ Keywords are the instructions given to the Compiler.
➢ Each keyword has fixed meaning and that cannot be changed by user. Hence, they are also
called reserved-words.
➢ There are 32 keywords.
int, float, char, double, void, case, switch, if, else, elseif, return, auto, register, static,
const, for, while, do-while, default etc.
1. num
Valid identifier
2. a_one
valid identifier as first character begins with letter
3. 2sum
Invalid Identifier because first character begins with digit
4. $sum
Invalid because no extra symbols are allowed other than under score
5. for
Invalid as for is a keyword
6. area length
Invalid because no spaces are allowed
Header Files
They have an extension '.h'. They contain the C function declarations and macro definitions
that are shared between various source files.
Advantages of header files:
At times the programmer may want to use the same subroutines for different programs. To do
this, he would just compile the code of the subroutine once and link to the resulting object file in
any file in which the functionalities of this subroutine are required.
At times the programmer may want to change or add the subroutines and reflect those changes in
all the programs. For doing this, he will have to only change the source file for the subroutines,
recompile the source code and then recompile and re-link the program.
This tells us that including a header file will make it easier at all levels of the program. If we need
to modify anything then changes are made only in the subroutines after which all the changes will
be reflected.
Object files
➢ They are the files that are generated by the compiler as the source code file is
processed.
➢ These files generally contain the binary code of the function definitions.
➢ The object file is used by the linker for producing an executable file for
combining the object files together. It has a ‘. o' extension.
Executable file
This file is generated by the linker.
Various object files are linked by the linker for producing a binary file which will be executed
directly. They have an '.exe' extension.
➢ A compiler that supports the source programming language reads the files, analyzes
the code, and translates it into a format suitable for the target platform.
➢ Compilers that translate source code to machine code target specific operating
systems and computer architectures.
➢ This type of output is sometimes referred to as object code (which is not related
to object-oriented programming).
➢ For example, a compiler might output machine code for the Linux x64 platform or
Linux ARM 64-bit platform
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\? Question mark
Example:
#include<stdio.h>
void main()
{
printf(“Welcome to C \n”);
printf (“Hello\tWorld\n”);
}
Output:
Welcome to C
Hello World
Data Types
C supports 5 primary data types:
1) int
An int is a keyword which is used to define integers.
Using int keyword, the programmer can inform the compiler that the data
associated with this keyword should be treated as integer.
2) float
A float is a keyword which is used to define floating point numbers.
3) double
A double is a keyword used to define long floating point numbers.
4) char
A char is a keyword which is used to define single character.
5) void
void is an empty data type. Since no value is associated with this data type, it does
not occupy any space in the memory.
This is normally used in functions to indicate that the function does not return any
value.
VARIABLES
A variable is an identifier whose value can be changed during execution of the program.
In other words, a variable is a name given to a memory-location where the data can be
stored. Using the variable-name, the data can be stored in a memory-location and
accessed or manipulated
The first character must be a letter or an underscore, and then followed by any
number of digits, letters and underscores.
Keywords cannot be used as a variable.
No extra symbols and spaces are allowed (other than letters, digits and underscore)
Variable should not have two consecutive underscores.
Length of a variable can be up to a maximum of 31 characters
Examples:
Valid variables:
A11
Aaa
A_5
abcd principle_amount,
sum_of_digits
Invalid variables:
3fact //violates rule 1
sum= sum-of-digits 62$ //violates rule 3
for int if //violates rule 2
Declaration of Variable
➢ The declaration tells the complier
➢ what is the name of the variable used
➢ what type of date is held by the variable
Datatype v1,v2..
int a,b;
char ch1, ch2;
CONSTANTS
A constant is an identifier whose value remains fixed throughout the execution of the
program.
• The constantscannot be modified in the program.
For example: 1, 3.14512,’a’
1) Integer Constant
• An integer is a whole number without any fraction part. It consists of sequence of
digits.
Octal constants (0 1 2 3 4 5 6 7) : combination of digits with 0-7 with prefix 0 is called Octal
constant.
For ex: 021, 077, 033
Hexadecimal constants: (0 1 2 3 4 5 6 7 8 9 A B C D E F)
Combination of digits with 0-9 and then followed with A-F.
It must begin with 0x.
For ex: 0x7f, 0x2a, 0x521
Fractional Form
A floating-point number represented using fractional form has an integer part followed
by a dot and a fractional part.
For ex: 0.5, -0.99
3. Character Constant
➢ A symbol enclosed within a pair of single quotes (' ‘) is called a character constant.
➢ Each character is associated with a unique value called an ASCII (American
Standard Code for Information Interchange) code.
➢ For ex: '9', 'a', '\n'
4. String Constant
A sequence of characters enclosed within a pair of double quotes(“) is called a string
constant.
The string always ends with NULL (denoted by \0) character.
For ex: "9" "a" "hello" "\n”
An escape sequence character begins with a backslash and is followed by one character.
A backslash (\) along with some characters give rise to special print effects by
changing (escaping) the meaning of some characters.
INPUT/OUTPUT STATEMENTS
• stdin: This file is used to receive the input (usually is keyborad file, but can also
take input from the disk file).
• stdout: This file is used to send or direct the output (usually is a monitor file, but
can also send the output to a disk file or any other device).
• stderr: This file is used to display or store error messages.
Input and Output statement are used to read and write the data in C programming. These
are embedded in stdio.h (standard Input/Output header file).
Input means to provide the program with some data to be used in the program and
Output means to display data on screen or write the data to a printer or a file.C
programming language provides many built-in functions to read any given input and to
display data on screen when there is a need to output the result.
There are mainly two of Input/Output functions are used for this purpose. These are
discussed as:
• getchar()
• putchar()
• gets()
• puts()
• getch()
• getche()
getchar()
This function is an Input function. It is used for reading a single character from the
keyboard. It is a buffered function. Buffered functions get the input from the keyboard and
store it in the memory buffer temporally until you press the Enter key.
v = getchar();
char n;
n = getchar();
/*To read a single character from the keyboard using the getchar() function*/
#include <stdio.h>
main()
{
char n;
n = getchar();
}
putchar()
This function is an output function. It is used to display a single character on the screen.
The general syntax is as:
putchar(v);
char n;
putchar(n);
A simple program is written as below, which will read a single character using getchar()
function and display inputted data using putchar() function:
This function is an input function. It is used to read a string from the keyboard. It is also a
buffered function. It will read a string when you type the string from the keyboard and
press the Enter key from the keyboard. It will mark null character (‘\0’) in the memory at
the end of the string when you press the enter key. The general syntax is as:
gets(v);
char n[20];
gets(n);
main()
{
char n[20];
gets(n);
}
puts()
This is an output function. It is used to display a string inputted by gets() function. It is also
used to display a text (message) on the screen for program simplicity. This function
appends a newline (“\n”) character to the output.
puts(v);
or
puts("text line");
getch()
This is also an input function. This is used to read a single character from the keyboard like
getchar() function. But getchar() function is a buffered is function, getchar() function is a
non-buffered function. The character data read by this function is directly assigned to a
variable rather it goes to the memory buffer, the character data is directly assigned to a
variable without the need to press the Enter key.
Another use of this function is to maintain the output on the screen till you have not press
the Enter Key. The general syntax is as:
v = getch();
getche()
All are same as getch(0 function execpt it is an echoed function. It means when you type
the character data from the keyboard it will visible on the screen. The general syntax is as:
v = getche();
Formatted I/O functions which refers to an Input or Ouput data that has been arranged in a
particular format. There are mainly two formatted I/O functions discussed as follows:
• scanf()
• printf()
scanf()
The scanf() function is an input function. It used to read the mixed type of data from
keyboard. You can read integer, float and character data by using its control codes or
format codes. The general syntax is as:
scanf("control strings",arg1,arg2,..............argn);
or
scanf("control strings",&v1,&v2,&v3,................&vn);
Where arg1,arg2,……….argn are the arguments for reading and v1,v2,v3,……..vn all are
the variables.
%s To read a string
%[^] To read string of words which are not from the defined range
Example Program:
/*Program to illustrate the use of formatted code by using the formatted scanf()
function */
#include <stdio.h>
main()
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
}
printf()
This ia an output function. It is used to display a text message and to display the mixed
type (int, float, char) of data on screen. The general syntax is as:
printf("control strings",&v1,&v2,&v3,................&vn);
or
printf("Message line or text line");
The control strings use some printf() format codes or format specifiers or conversion
characters. These all are discussed in the below table as:
%s To read a string
Example Program:
/*Below the program which show the use of printf() function*/
#include <stdio.h>
main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch();
}
QUESTION BANK
1. Define Computer. Explain the organization of basic computer model with a neat
diagram.
7. Define the variable, Explain the rules to declare a variable with an example.
8. Write a c program
v. Area of Triagle
x. Subtraction of 2 numbers
MODULE 02
OPERATORS IN C, TYPE CONVERSION AND
TYPECASTING. DECISION CONTROL AND LOOPING
STATEMENTS
2.1 Operators in C & Type conversion and typecasting
OPERATOR
• An operator can be any symbol like + - * / that specifies what operation need to be
performed on the data.
• For ex:
+ indicates add operation
* indicates multiplication operation
Operand
• An operand can be a constant or a variable.
Expression
• An expression is combination of operands and operator that reduces to a single value.
• For ex:
Consider the following expression a+b here a and b are operands while + is an operator
Types of Expressions:
1. ARITHMETIC OPERATORS
• These operators are used to perform arithmetic operations such as addition,
subtraction, multiplication, division and modulos.
• There are 5 arithmetic operators:
Operator Meaning of Operator
+ addition
- subtraction
* multiplication
/ division
% modulos
#include<stdio.h>
void main()
{
int a,b,sum,sub,mul,div,mod;
sum=a+b;
sub=a-b;
mul=a*b;
div=a/b;
mod=a%b;
printf("sum=%d\n sub=%d\n mul=%d\n div=%d\n mod=%d\n”,sum,sub,mul,div,mod);
}
Output:
a=3 b=2
a+b=5
a-b=1
2. INCREMENT OPERATOR
• ++ is an increment operator.
• As the name indicates, increment means increase, i.e. this operator is used to
increase the value of a variable by 1.
• For example:
If a=5
then a++ or ++a; // a becomes 6
• The increment operator is classified into 2 categories:
1. Post increment Ex: a++
2. Pre increment Ex: ++a
• As the name indicates, post-increment means first use
the value of variable and then increase the value of
variable by 1.
• As the name indicates, pre-increment means first increase the
value of variable by 1 and then use the updated value of variable.
• For ex:
If a is 5,
then z= a++; sets z to 5
but z = ++a; sets z to 6
3. DECREMENT OPERATOR
• -- is a decrement operator.
• As the name indicates, decrement means decrease, i.e. this operator is used to
decrease the value of a variable by 1.
• For example:
If a=5
then a-- or --a; // a becomes 4
• Similar to increment operator, the decrement operator is classified into 2 categories:
1. Post decrement: means first use the value of variable
and then decrease the value of variable by 1. Ex:
a--
2. Pre decrement: means first decrease the value of variable by 1
and then use the updated value of variable. Ex: --a
4. ASSIGNMENT OPERATOR
The most common assignment operator is =.
This operator assigns the value in right side to the left side.
The syntax is shown below:
variable=expression;
For ex:
c=5; //5 is assigned to c
b=c; //value
of c is
assigned to b
5=c; //
Error! 5 is a
constant.
The operators such as +=,*= are called shorthand assignment operators.
For ex,
a=a+10: can be written as a+=10;
In the same way, we have:
Operator Example Same as
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a%=b a=a/b
%= a=a%b
5. RELATIONAL OPERATORS
Relational operators are used to find the relationship between two operands.
The output of relational expression is either true(1) or false(0).
For example
a>b //If a is greater than b, then a>b returns 1 else a>b returns 0.
The 2 operands may be constants, variables or expressions.
There are 6 relational operators:
Operator Meaning of Operator Example
> Greater than a>b returns true (1)
< Less than a<b returns false (0)
>= Greater than or equal to a>=b returns true (1)
<= Less than or equal to a<=b return false (0)
== Equal to Not a==b returns false (0)
!= equal to a!=b returns true(1)
6. LOGICAL OPERATORS
These operators are used to perform logical operations like negation, conjunction and
disjunction.
The output of logical expression is either true(1) or false(0).
There are 3 logical operators:
7. CONDITIONAL OPERATOR
The conditional operator is also called ternary operator it takes three operands.
Conditional operators are used for decision making in C.
The syntax is shown below:
(exp1)? exp2: exp3;
where exp1 is an expression evaluated to true or false;
If exp1 is evaluated to true, exp2 is executed;
If exp1 is evaluated to false, exp3 is executed.
Example: Program to find largest of 2 numbers using conditional operator.
#include<stdio.h> void main()
{
int a,b, max ;
printf(“ enter 2 distinct numbers \n”); scanf(“%d %d”, &a, &b);
max=(a>b)? a : b;
printf(“ largest number =%d ”, max);
}
Output:
enter 2 distinct numbers 3 4
largest number = 4
8. BITWISE OPERATORS
These operators are used to perform logical operation (and, or, not) on individual
bits of a binary number. There are 6 bitwise operators:
Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Truth Table
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1
1 0 0 1 1 0
1 1 1 1 0
Ex for ~ (bitwise complement) Ex for & (bitwise AND)
a = 13 0000 1101 a = 13 0000 1101
~a= 1111 0010 b=6 0000 0110
a&b 0000 0100
Ex for || (bitwise OR) Ex for ^ (bitwise xor)
a = 13 0000 1101 a = 13 0000 1101
b=6 0000 0110 b=6 0000 0110
a|b 0000 1111 a^b 0000 1011
The operator that is used to shift the data by a specified number of bit positions towards
left or right is called shift operator. b=a >> num; where a is value to be shifted num is
number of bits to be shifted
Ex for <<(left shift): Ex for >>(right shift):
a = 13 0000 1101 a = 13 0000 1101
b=a<<1 0001 1010 b=a>>1 0000 0110
#include<stdio.h>
void main()
{
int x=5, y=4;
x=x>>1;
y=y<<2;
printf(“Rightshift x=%d\n”,x);
printf(“Leftshift y=%d\n”,y);
}
9. Special Operators
Special operators in C are used to perform special functions such as combining multiple
expressions into a single expression using comma operator,getting size of data type using
sizeof() operator.
➢ Comma Operator:
It combines multiple expressions into a single expression.
The value of right most expression is assigned to left variable.
Example.
a=(c=2,b=3);
a=b=3
a=3
➢ sizeof( ) operator:
It is used to determine size of the operand based on its data type.
Example:
float x=3.142;
int y;
y=sizeof(x); // size of float is 4 bytes.
#include<stdio.h>
void main( )
{
int a=10;
float b=3.142;
char c=’a’;
double d=1.234;
printf(“size of integer is: %d bytes”,sizeof(a)); // int is 2 bytes
printf(“size of float is: %d bytes”,sizeof(b)); // float is 4 bytes
printf(“size of char is: %d bytes”,sizeof(c)); //char is 1 byte
printf(“size of double is: %d bytes”,sizeof(d)); //double is 8 bytes
}
1. IMPLICIT CONVERSION
• If a compiler converts one type of data into another type of data automatically,
it is known as implicit conversions.
• There is no data loss in implicit conversion.
• The conversion always takes place from lower rank to higher rank.
For ex:
int a = 22, b=11;
float c = a; //c becomes 21.000000
float d=b/c=11/22.000000=11.000000/22.000000=0.500000
• If one operand type is same as other operand type, no conversion takes
place and type of result remains same as the operands
i.e. int+int=int
float+float=float
Conversion rules are as follows:
→ If either operand is long double, convert the other to long double.
→ Otherwise, if either operand is double, convert the other to double.
→ Otherwise, if either operand is float, convert the other to float.
→ Otherwise, convert char and short to int.
→ Then, if either operand is long, convert the other to long.
Example: Program to illustrate implicit conversion.
}
Output:
a=65
2. EXPLICIT CONVERSION
• When the data of one type is converted explicitly to another type with the
help of some pre-defined functions, it is called as explicit conversion.
• There may be data loss in this process because the conversion is forceful.
The syntax is shown below:
data_type1
var1;
data_type2 v2= (data_type2) v1;
where v1 can be expression or variable
For ex:
float b=11.000000; int c = 22;
float d=b/(float)c=11.000000/22.000000=0.500000
Precedence Table
i) if statement
ii) if else statement
iii) nested if statement
iv) else-if ladder/cascaded if statement
v) switch statement
Branching Statements:
The statements that transfer the control from one place to other place in the program with or
without any condition are called branch statements.
They are classified into 2 types:
1. Conditional control statements
2. Unconditional control statements
i. if statement
ii. if-else statement
iii. nested if statement
iv. else-if ladder
v. switch statement
1) simple if (one-way Selection)
• It is basically a “one-way” decision statement.
• This is used when we have only one alternative.
Syntax:
if(expression/condition)
{
statement(s);
}
Firstly, the expression is evaluated to true or false. If the expression/condition is evaluated to
true, then statement is executed. If the expression is evaluated to false, then statement is
skipped.
#include<stdio.h>void main()
{
int num;
printf(“Enter number\n”) ;
scanf(“%d”, &num);
if(num%2==0)
printf(“Num is even number”);
else
printf(“Num is odd number”);
}
Program to check whether a person is eligible for voting based on his age.
#include<stdio.h>void main()
{
int age;
printf(“enter age of a person\n”);
scanf(“%d”,&age);
if(age>=18)
printf(“eligible\n”);
else
printf(“not eligible\n”);
}
3) Nested if STATEMENT
• An if-else statement with in another if-else statement is called nested if statement.
• This is used when an action has to be performed based on many decisions. Hence, it is
called as
Example: Program to print the largest of the 3 numbers using nested-if statements.
#include<stdio.h>void main()
{
int a,b,c;
printf(“Enter Three Values: \n”); scanf(“%d %d %d ”, &a, &b, &c); if(a>b)
{
if(a>c)
printf(“ a is largest”);
else
printf(“ c is largest”);
}
else
{
if(b>c)
printf(“ b is largest”);
else
printf(“ c is largest”);
}
}
Output:
Enter Three Values: 7 8 6
Largest Value is: 8
Syntax:
if(exp1/condition1)
statement1;
else if(exp2/condition2)
statement2;
else if(exp3/condition3)
statement3;
else if(exp4/condition4)
statement4;
else
statement-n;
If all the expressions are evaluated to false, the last statement-n is executed.
Flow diagram
Example: Program to illustrate the use of else if ladder statement. (Type of Triangle)
#include<stdio.h>
void main ()
{
int a,b,c;
printf(“Enter 3 sides \n:”) ;
scanf(“%d%d%d”, &a,&b,&c);
if((a==b)&&(b==c)&&(a==c))
printf ("Equilateral triangle");
else if((a==b)||(b==c)||(a==c))
printf ("Isosceles triangle\n");
else
printf(“Scalene triangle\n”);
}
Output:
Enter 3 sides:
333
Equilateral Traingle
Program to display a grade of a student based on his percentage (using else if ladder)
#include<stdio.h>void main()
{
float percentage;
printf(“enter percentage:\n);
scanf(“%f”,&percentage);
if( percentage>=70)
printf(“FCD\n”);
else if (percentage<70 && percentage>=60)
printf(“First class”);
else if(percentage<60 && percentage>=35)
printf(“Second Class”);
else
printf(“Fail”);
}
Output:
Enter your choice: a
It is a vowel
Looping:
• Loops refer to repetitive execution of same set of instructions for a given number of
times until a result is obtained.
• A set of statements may have to be repeatedly executed for a specified number of
times or till a condition is satisfied are called looping statements or loop constructs.
• There are 3 types of loops in C programming/Loop Constructs:
1) for loop
2) while loop
3) do-while loop
1) for loop
• It repeats given true block of statements repeatedly till the expression is true.
Whenever the given condition becomes false then the loop gets terminated.
Syntax:
for(expr1;expr2;expr3)
{
statement(s);
}
statement-X;
OR
for(initialization; condition; updating-expression)
{
statement(s);
}
statement-X;
2) while loop
• A while loop statement can be used to execute a set of statements repeatedly as long
as a given condition is true.
Syntax :
while(condition)
{
statement(s);
}
statement-X;
OR
while(expression)
{
statement(s);
}
statement-X;
3) do-while loop
• When we do not know exactly how many times a set of statements have to be
repeated, do-while statement can be used.
Syntax :
do
{
statement(s);
} while(condition);
statement-X;
• Firstly, the body of the loop is executed .i.e. the body of the loop is executed at least
once.
• Then, the expression is evaluated to true or false.
• If the expression is evaluated to true, the body of the loop (i.e. statement) is executed
• After executing the body of the loop, the expression is again evaluated to true or false.
This cycle continues until expression becomes false.
Example: Program to illustrate do-while Loop
#include<stdio.h>
void main()
{
int i;
i=1;
do
{
printf(“%d\n”,i);
i++;
} while(i<=100);
}
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i; int i;
i=1; i=1;
while(i<=100) do
{ {
printf(“%d\n”,i); printf(“%d\n”,i);
i++; i++;
} } while(i<=100);
} }
2) continue
• During execution of a loop, it may be necessary to skip a part of the loop based on some
condition.
Syntax:
for(expr1;expr2;expr3)
{
statement(s);
if(condition)
continue;
statements;
}
statement-X;
Example: Program to illustrate continue statement
#include<stdio.h>
void main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
continue;
printf(“%d\n”,i);
}
}
Output:
1245
3) goto
• goto statement can be used to branch unconditionally from one point to another in the
program. It transfers the program execution flow from one point of the program to another
point.
• goto requires a label in order to identify the place where the branch is to be made.
• A label is any valid variable name and must be followed by a colon(:)
• The label is placed immediately before the statement where the control is to be transferred.
Syntax:
4. return statement
• It terminates the execution of a function and returns control to the calling function. It
returns a value to the calling function.
Syntax:
return expression;
Example:
return 0;
Differences between break and continue statements
1. When break is executed the statements 1. When continue statements are executed
following break are skipped and causes the statements following continue are
the loop to be terminated skipped and causes the loop to be
continued with the next iteration.
2. It can be used in switch statement to 2. It cannot be used inside a switch
transfer the control outside the switch. statement.
3. Syntax: 3. Syntax:
for(exp1;exp2;exp3;) for(exp1;exp2;exp3;)
{ {
if(condition); if(condition);
break; continue;
statements; statements;
} }
statement-X; statement-X;
4. Example: 4. Example:
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
int i; int i;
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ {
if(i==3) if(i==3)
break; continue;
printf(“%d\n”,i); printf(“%d\n”,i);
} }
} }
Output: Output:
12 1245
Nested Loops:
A loop enclosed within another loop is called nesting of loops. A for statement can be inside
a for/while/do-while.
• Example:
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
statements;
}
statements;
}
• The outer most loop is executed many times. Each time the control enters inside the
innermost loop.
• The index value of each loop must be different.
• The inner loop must be completely enclosed within the outer loop.
• Program to print the values in right triangle form:
#include<stdio.h>
void main()
{
int i,j,n;
printf(“enter the value of n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf(“%d”,i);
}
printf(“\n”);
}
}
#include<stdio.h>
void main()
{
int i,j,n;
printf(“enter the value of n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf(“* “);
}
printf(“\n”);
}
}
#include<stdio.h>
void main()
{
int i,j,n;
printf(“enter the value of n\n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf(“ %d “, j);
}
printf(“\n”);
}
}
• In Pascal’s triangle all the numbers outside the triangle are “0”s.
• To build the triangle start with a “1” at the top then continue putting the numbers
• So each new number added below the top “1” is just the sum of two numbers above,
except for the edge which are all “1”s.Thus, the left and right edges of pascal’s
0 row=1
1 row=(0+1),(1+0)=1,1
2 row=(0+1),(1+1)(1+0)=1,2,1
3 row=(0+1),(1+2),(2+1),(1+0)=1,3,3,1
4 row=(0+1),(1+3),(3+3),(3+1),(1+0)=1,4,6,4,1
5 row=(0+1),(1+4),(4+6),(6+4),(4+1),(1+0)=1,5,10,10,5,1
• The sum of all elements of a row is twice the sum of all the elements of its preceding
row.
Example:
Sum of first row=1
Sum of second row is 1+1=2
Sum of third row is 1+2+1=4
Sum of fourth row is 1+3+3+1= 8
Sum of fifth row is 1+4+6+4+1=16
Sum of sixth row is 1+5+10+10+5+1=32 and so on….
Programming Examples:
1. Write a C program to find the factorial of a given number
#include<stdio.h>
void main()
{
int i,n,fact=1;
printf(“enter n:\n”);
scanf(“%d”,&n);
for(i=1; i<=n; i++)
{
fact=fact*i;
}
printf(“factorial=%d\n”,fact);
}
6. Write a C program to compute GCD of a given number using Ternary and for loop
#include<stdio.h>
void main()
{
int i,gcd,x,y;
printf(“enter the values of x and y:\n”);
scanf(“%d%d”,&x,&y);
for(i=x;i>=1;i--)
{
(x%i==0 && y%i==0)?(gcd=i): (gcd=1);
if(gcd==i)
break;
}
printf(“GCD of %d and %d is %d\n”,x,y,gcd);
}
QUESTION BANK
Q. No Questions
MODULE-III
FUNCTIONS AND ARRAYS
FUNCTION IN C
• A function is a collection of statements that performs a specific task.
• Functions are very useful to read, write, debug and modify complex programs. A
function can also be referred as a method or a sub-routine or a procedure.
• One reason to use functions is that they break a program into small, manageable units.
Each unit is called module which performs a specific task.
• Another reason to use function is that they simplify programs.
• Every C program has at least one function main( ).Without main() function, there is
technically no C program.
TYPES OF C FUNCTIONS
• There are 2 types of functions in C programming:
1. Library Functions/built-in functions/pre-defined functions
2. User defined functions
1. Library Function
• Libraryfunctionsarethein-builtfunctioninCcompiler.
• Functions which are defined in C library are called library functions or built-in functions.
• These functions are also called as pre-defined functions.
• For example:
→main() //The execution of every C program starts from this main() function
→printf() //printf() is used for displaying output inC
→scanf() //scanf() is used for reading/taking input inC
#include<stdio.h>
#include<math.h>
void main()
{
int n;
float x;
printf(“enter number:\n”);
scanf(“%d”,&n);
x=sqrt(n);
printf(“square root=%f\n”,x);
}
ARRAYS
BASIC CONCEPT OF ARRAYS
• Consider a situation, where we need to store 5 integer numbers.
• If we use simple variable and data type concepts, then we need 5 variables of int data
type and program will be something as follows:
#include<stdio.h>void main()
{
int a,b,c,d,e;
a=10;
b=20;
c=30;
d=40;
e=50;
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d\n",c);
printf("d=%d\n",d);
printf("e=%d\n",e);
}
Output:
a=10
b=20
c=30
d=40
e=50
• It was simple, because we had to store just 5 integer numbers. Now let's assume we
have to store 5000integernumbers,so what is next? Are we going to use 5000
variables?
The main disadvantage of using above simple program are:
➢ Difficult to declare more number of variables.
➢ Difficult to read and write a program. It is difficult to print the data stored in
more number of variables.
➢ Very difficult to process large amount of data.
➢ Length of a program increases as the number of variable increases.
Representation of an array:
array[0] array[1] array[2] ………… array[n-1]
Examples:
➢ Array of 5 integers:
➢ Array of 5 characters:
• The array is identified by name a i.e, any element in the array can be accessed using
the common name.
• The element can be accessed using the subscript 0 ( also called index 0 ) along with
name of array
• Index: An index is also called the subscript is the position of an element in the array.
• Using the index, we can access the elements.
CLASSIFICATION/TYPES OF ARRAYS:
data_typearray_name[array_size];
example:
int a[5];
• Since sizeof(int) is 2 bytes. 2*5=10 bytes. 10 memory locations are reserved for an
array of 5 integers.
example:
float b[5];
Since sizeof(float) is 4 bytes. 4*5=20 bytes. 20 memory locations are reserved for an
array of 5 floating point numbers.
example:
char c[5];
Since sizeof(char) is 1 bytes. 1*5=5 bytes. 5 memory locations are reserved for an array
of 5 characters.
Syntax:
data_type
array_name[array_size]={v1,v2,...,vn};
example:
int a[5]={10,20,30,40,50};
Arrays can be initialized at the time of declaration when their initial values are known
in advance. During compilation 5 contiguous memory locations are reserved by the
compiler for the variable a. The size is 2 bytes then 10 memory locations will be
allocated for variable a.
Example:
int a[5]={10,20,30,40,50};
If the number of values to be initialized is less than the size of array, then the elements
are initialized in the order from 0th location. The remaining locations will be
initialized to zero automatically.
Example:
int a[5]={10,20};
10 20 0 0 0
a[0] a[1] a[2] a[3] a[4]
In this method even if the size is not specified the array size will be set to the total
number of initial values specified. Since the number of elements is 5 , totally 5*2=10
bytes are reserved.
Example:
int a[]={10,20,30,40,50};
Sequence of characters enclosed within a double quotes is a string. The string always
ends with NULL character ‘\0’.
Example:
char c[]=”COMPUTER”;
C 0 M P U T E R \0
Size of array is 9 bytes ( i.e String length+1 byte for null character)
• The elements 10,20,30,40 and 50 can be inserted into array at positions 0,1,2,3,4,5, as
shown below.
➢ But we can copy all individual elements of one array a into other array b.
Example:
b[0]=a[0]; // b[0] is assigned the value of a[0]
b[1]=a[1]; // b[1] is assigned the value of a[1]
b[2]=a[2]; // b[2] is assigned the value of a[2]
b[3]=a[3]; // b[3] is assigned the value of a[3]
b[4]=a[4]; // b[4] is assigned the value of a[4]
b[i]=a[i];
i=0 to 4
➢ b[i]=a[i] can be executed for all values of i=0 to 4 using for loop.
Example:
for(i=0;i<=4;i++)
{
b[i]=a[i];
}
or
for(i=0;i<5;i++)
{
b[i]=a[i];
}
6. Reading/Writing ID Arrays:
• How to read the data from keyboard and how to display data items stored in the array?
We can easily read, write or process the array elements using loop constructs (for,
while and do-while).
• We can read ‘n’ array elements from keyboard using scanf().
Example:
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
• Similarly to display ‘n’ elements stored in the array replace scanf() by printf()
statement.
Example:
for(i=0;i<n;i++)
{
printf(“%d”,a[i]);
Question Bank
1. Define function. List application of function or advantages of functions
2. Write a C Program to swap two numbers using functions.
3. Explain general categories of functions
4. Explain different parameter passing techniques
5. List and explain various categories of user-defined functions.
6. Compare and contract actual and formal parameters
7. Write a c program to find factorial of n
8. Write a c program for calculating nCr using functions
9. Write a C Program for a sequential search
10. Write a C Program for binary search
11. What are the applications of 1-d array
12. Write a C Program to sort n number of elements in an array using bubble sort
13. Write a C Program to print even and odd number in array of an n elements
14. Illustrate the declaration of 2-D array with suitable examples
15. Write a C Program to print transpose of the given matrix of order m X n
16. Write a C Program to print principle diagonal elements of given matric a of order pXq
17. Write a C Program to add two matrix a and b . Print matrix a matrix b and resultant matrix
18. Write a C Program to subtract two matrix a and b . Print matrix a matrix b and resultant
matrix
19. Write a C Program to multiply two matrix a and b . Print matrix a matrix b and resultant
matrix