SlideShare a Scribd company logo
1 of 99
Download to read offline
Module – 1: Introduction to computers & c-programming
COMPUTER: A computer is a machine that accepts data as input, processes that data using
programs, and outputs the processed data as information. Many computers can store and retrieve
information using hard drives. Computers can be connected together to form networks, allowing
connected computers to communicate with each other.
GENERATIONS OF COMPUTER: There are six generations of computer system are
present as follows:
a) Zeroth Generation: Man used his fingers, ropes, beads, bones, pebbles and other objects for
counting. Electricity was not yet invented.
b) First Generation(Vacuum Tubes): Used vacuum tubes for computation, magnetic drums
for memory, Took up lot of space, Very expensive , consumed great deal of electricity,
generated a lot of heat, which was often the cause of malfunctions. Input was based on
punched cards and output was obtained on paper.
c) Second Generation(Transistors): Transistors replaced vacuum tubes which are smaller,
faster, cheaper, more energy-efficient and more reliable than their first-generation
predecessors. Still relied on punched cards for input and printouts for output. Generate less
heat and consumed less electricity as compared to First generation computers. Still very
costly. Support assembly language and high level language such as FORTRAN & COBOL.
d) Third Generation(Integrated Circuits): Integrated circuit was used such as Transistors,
resistors, capacitors and diodes were integrated onto a single chip. Computers of this
generation are Smaller, cheaper and energy-efficient & users interacted through keyboards
and monitors. Memory capacity increased and magnetic hard disk was used but Still costly
A.C. needed. Support high-level language such as C, C++ and Java.
e) Fourth Generation(Microprocessor): Microprocessor were used, What in the first
generation filled an entire room could now fit in the palm of the hand. As these small
computers became more powerful, they could be linked together to form networks, which
eventually led to the development of the Internet. Fourth generation computers also saw the
development of GUIs, the mouse and Hand held devices. Finally Computers became easily
available
f) Fifth Generation(Artificial Intelligence): based on artificial intelligence, are still in
development, though there are some applications, such as voice recognition, that are being
used today. The goal of fifth-generation computing is to develop devices that respond to
natural language input and are capable of learning and self-organization.
TYPES OF COMPUTERS: Apart from being classified by generations, computers can also
be categorized by their size:
a) SUPERCOMPUTERS: These are the huge machines having the most powerful and fastest
processors. A supercomputer uses multiple CPUs for parallel data processing, which means
portions of the same program are handled independently by multiple processors. Super
computers are too powerful to be used for transaction processing. They are employed in areas
that require enormous numerical computations like weather forecasting, analysis of
geological data, nuclear stimulation, and space exploration. The cost of supercomputers are
too high, they are mainly used by government agencies.
b) MAIN FRAME COMPUTERS: Before the advent of supercomputers, mainframe
computers were the largest computers available. These are the multiuser machines that can
support hundreds or thousands of users using the feature of “time sharing” supported by
systems like Linux. Today mainframes are employed to handle online transactions(like stock
exchange transactions), The capability to handle large amounts of data makes the mainframe
suitable for use in government, banks, financial institutions and large corporations.
c) MINICOMPUTERS: Minicomputers or midrange computers can be considered as
downsized mainframes since they have essential features of mainframes. Minicomputers can
serve hundreds of users and are small enough to partially occupy a room. But they are not
affordable enough to be used in the home. Minicomputers are used in smaller organizations
or a department of a large one.
d) MICROCOMPUTERS: The microcomputer or personal computers(PC) is a late entrant to
the computer family. This was introduced by Apple and later endorsed by IBM, this
computer is a single-user machine powered by a single chip microprocessor. They are used
both in the standalone mode (at home) and in network (in office). They are used both in the
standalone mode (at home) and in network (in office). All PCs are multimedia ready. They
can handle images, audio and video files.
e) SMART PHONES AND EMBEDDED COMPUTERS: A smartphone is a general purpose
computer that is also capable of making phone calls. It also supports gigabytes of main
memory but doesn‟t have a hard disk for secondary storage. This requirement is met by flash
memory. Smartphones today run a well-developed operating system (Android or iOS) and
can run a wide range of applications. Applications are written in a high-level language like
Objective C for the iPhone and Java for Android phones. Embedded devices is small
computer like system that is part of a larger system which consists of CPU, non-volatile
memory, and input and output facilities.we use such devices in cars, washing machine, MP3
players and cameras.
BITS, BYTES AND WORDS: In everyday life, we use decimal system for computing
where digit can have ten values. A computer understands only two states:
 0
 1
A digit that can have only two states or values is called as binary digit, which is abbreviated as
“bit”. All binary numbers are represented by combining these 0s and 1s.
Example: The number 13 is represented as 1101 in the binary system.
The name “byte” was coined to represent eight bits. The byte is the standard unit of measurement
of computer memory, data storage and transmission speed.
A similar relationship exists for bits also. So the speed of network expressed as 1Mbps(megabits
per second) is same as 1000Kbps.
Even though computer memory is represented in bytes, the CPU handles memory data in larger
units, called “words” , where a word is usually an even multiple of bytes (two bytes, four bytes
etc.,). When we refer to a computer as 32-bit (4 bytes) machine, we mean the size of the size of
its word is 32 bits.
ARCHITECTURE OF COMPUTER (Von Neumann Architecture/Block
Diagram of Computer): Computer is having three basic units such as
 The Central Processing Unit (CPU)
 The Main Memory Unit
 The Input/Output Device
The block diagram of Computer Architecture is as shown below:
a) CPU: It comprises the following components:
 Arithmetic and Logic Unit (ALU) - It carries out all arithmetic tasks. ALU also
compares two numbers and performs “Boolean” operations such as AND, OR, NOT
on them.
 Control Unit (CU) - does not perform any computational tasks. Using signals, the
CU controls the way the data is moved between moved between the various
components of the computer.
 Special-purpose registers - CPU uses a few high-speed “registers”, form of memory
to store the current instruction and its data.
b) PRIMARY MEMORY: Memory is one of the essential resource used by the computer and
its users. We categorize memory into two types:
 Primary memory – All of these memory units are housed on the motherboard of the PC
such as RAM, ROM & Cache memory. Except ROM, all the memory types are volatile
i.e., they loose the contents when power given to computer is taken back.
 Secondary memory - Computer system also supports secondary memory which is also
called as secondary storage or auxiliary memory. These devices are slower than
primary memory but they have larger capacities. Some of the examples include Hard
disc, Pen drive, CD, DVD etc.
c) INPUT/OUTPUT DEVICES: We interact with the operating system for performing the
daily chores like editing, copying and deleting files. Some of the common input devices are
keyboard, Mouse & Scanners etc.
The term output generally refers to the information that can be seen or heard. Some of the
common output devices are Monitor, Printer & Speakers etc.
PORTS AND CONNECTORS: Devices like printers and scanners connect to a computer
through docking points called ports. All ports are connected to mother board but are visible
from outside. They are shaped differently, so it is impossible to use a wrong connector for a port.
• Serial Port: Once used by keyboard, mice and modems serial ports are offered in 9-pins
and 25-pins.
• Parallel Port: It is commonly used by printers if they are not using the USB port and
comes with 25-pins.
• Video Graphics Array (VGA): This 15-pin port allows transfer of analog (continuous)
video data to the monitor.
• RJ45 port: This is used by the Ethernet network.
• PS/2 port: This port has replaced the serial port for connecting the keyboard and mouse.
It has 6 pins but occurs as a pair in two different colors.
• High Definition Media Interface: This is now the industry standard for transferring
audio and video data between computers and HDTVs, projectors and home theatres.
COMPUTERS IN A NETWORK: Most organisations, large or small no longer have
standalone systems. Today, computers cooperate with each other by being connected to a
network. The computer (node) that offers these services would need to be more powerful than
the computer it serves. That‟s how “servers” came to existence as the central node in the
network.
Servers acts as the backbone of the largest network of all- the internet. Network topology is the
arrangement of the elements (links, nodes, etc.) of a communication network.
There are a number of ways of topologies of connecting computers, each having its own merits
and demerits:
 Bus topology uses single cable as a bus to which all computers are connected. The failure
of one node doesn‟t disrupt communication between the remaining nodes.
 Star topology uses central hub to which all nodes are connected. Due to network traffic
through the hub, the entire network fails if the hub fails to work. New nodes can be added
without disrupting the service.
 Ring topology uses closed loop without using a hub. For unidirectional rings, failure of
one node causes the network to shut down.
 Mesh topology uses nodes connected to each other, offering a choice of multiple routes
for data to travel. When node breaks down, the packet simply changes its route. This is
the most expensive of the topologies and found mainly in corporate networks.
Networks are classified based on their size. The three most common types are:
 Local Area Network - LAN is used by small organizations where the area is confined to
one building. They generally use Ethernet technology. Wireless LANs (WLAN) also
known as Wi-Fi (Wireless Fidelity) has become popular. Standard Ethernet speeds are
ruling at 100 Mbps. Wi-Fi networks using 802.11g operate at round 20 Mbps.
 Wide Area Network - WANs extend the range used by LANs. It can connect a number
of cities or establishments in the same city. Because of the large distances, optic fiber
cables, leased telephone lines and radio transmission are used to connect WAN nodes
 Metropolitan Area Network (MAN) - This type is sandwiched between a LAN and
WAN. A MAN is employed for interconnecting in the same city.
The Internet (also called net) is the largest wide area network on the planet. It‟s a collection of
over 50,000 networks that run a special set of network protocols called TCP/IP.
Connecting computers in a network is require additional devices that are not part of the
computer‟s configuration. Some of the devices are:
 Network Interface card (NIC) - Network Interface Card (NIC) or network card that is
presented in the computer. Most of the computers use Ethernet technology, this card is
often called as Ethernet card.
 Hub - accepts network data from a computer and simply broadcasts the data to all nodes.
 Switch - contains a table of MAC addresses of the connected devices. A switch is
efficient and is able to maintain the speed of the network.
 Bridge - maintains a table of MAC addresses of all machines in the segments connected
to it. It connects two networks using the same protocol (say, Ethernet).
 Router - connects two similar or dissimilar networks which may be separated by long
distances. It is part of both networks and thus has two addresses.
SOFTWARE BASICS: Software is a collection of code that drives the computer to perform
related task. Comprises one or more programs supported by libraries & configuration files.
Programs in software use languages like C, C++, java etc.
Computer software can be broadly classified into two types:
 System Software - They are run by computer to manage the hardware connected to it. User
will not have much control over it. Some good examples are OS, Compilers, Device Drivers
etc.
 Application Software - They are used for specific application. Some good examples are
Games, Social media, Anti-virus etc.
BASIC STRUCTURE OF C-PROGRAM
 Documentation section - The documentation section consists of a set of comment lines
giving the name of the program, the author and other details, which the programmer
would like to use later.
 Link section - The link section provides instructions to the compiler to link functions
from the system library.
 Definition section - The definition section defines all symbolic constants.
 Global declaration section - There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all the
user-defined functions.
 main () function section - Every C program must have one main function section. This
section contains two parts; declaration part and executable part. The declaration part
declares all the variables used in the executable part. There must be at least one
statement in the executable part. These two parts must appear between the opening and
closing braces. The program execution begins at the opening brace and ends at the
closing brace. The closing brace of the main function is the logical end of the program.
All statements in the declaration and executable part end with a semicolon.
C-TOKENS: The characters that can be used to form words, numbers & expressions
depend upon the computer on which the program is run. The characters are grouped into the
following categories: Letters(A…Z, a….z), Digits (0…9), Special
characters(%,&,:,;,*,!,#,<,>,?,=,”,/,) & Whitespaces.
The smallest individual units in C program are known as “C Tokens”.
 Keywords - Every word used in a C program is classified as either a keyword or as
an identifier. A keyword in C is a reserved word which has a specific meaning.
Keywords in C cannot be used as identifiers. Keywords serve as the basic building
blocks for program statements
Keywords in C are always in lowercase. ANSI C supports 32 keywords which are
listed below:
 Identifiers - refer to the names of variables, functions and arrays. These are user-
defined names and consist of sequence of letters and digits, with a letter as a first
character. Both uppercase and lowercase letters can be used, although lowercase
letters are generally used. The underscore character is also permitted in identifiers.
There certain rules while writing identifiers. They are as follows:
1) First character must be an alphabet or underscore.
2) Must consist of only letters, digits or underscore.
3) Only first 31 characters are significant.
4) Cannot use a keyword.
5) Must not contain white space.
 Constants in C- Constants are fixed values, which do not change during the
execution of a program. C supports several types of constants, which are as shown
below:
“Integer Constant” refers to a sequence of digits. Generally in programs, the number
systems used are: decimal, octal and hexadecimal. “Real Constants” integer numbers are
not sufficient to represent quantities that vary continuously, such as distances, height,
prices etc. These quantities are represented by numbers containing fractional parts like
25.234. Such numbers are called as real or floating point constants.
 Strings – “Single Character Constants” or character constant contains a single character
enclosed in between single quotes. Some valid examples of character constants are: „f‟,
„A‟, „/‟, ‟;‟, „ „, „4‟. The character constant „4‟ is not equal to the number 4. “String
Literals or String Constants” A sequence of characters that are enclosed between double
quotes is known as a string literal or string constant. The characters in a string literal can
be either letters, digits or special symbols or white spaces. Some valid examples of string
constants are: “hai”, “hEllO”, “hi5”, “Wel come” etc.
VARIABLES IN C: A variable is a placeholder for holding a value in the main memory
(RAM). As the name implies, the value in the variable can change at any point of execution of
the program.
For using variables in our programs, there are essentially two steps:
1) Declare the variable
2) Initialize the variable
 Before using a variable in the program, we have to declare the variable. The syntax for
declaring a variable in a program is as shown below:
datatype variable-name;
 The “type” in the above syntax represents the data type. The “variable-name” is the
identifier. There are certain rules that must be followed while writing the variable name.
 Rules for Variables Name –
 A variable name must always start with an alphabet (letter) or an underscore ( _ ).
 The variable name must not be more than 31 characters. The suggested length of a
variable name is 8 characters.
 C is case sensitive. So, the variable name “average” is different from
“AVERAGE”.
 Keywords must not be used for declaring variables.
 White spaces are not allowed within the variable name.
 Initializing a Variable – After declaring the variable, we can assign a value to the variable.
This process of assigning a value to the variable is known as initialization. Syntax for
initializing a variable is as shown below:
variable-name = value;
The value we assign to the variable depends on the data type of the variable.
int a;
a=10;
The declaration and initialization can be combined into a single line as shown below:
int a=10;
Data Types in C: A data type specifies the type of value that we use in our programs. A data
type is generally specified when declaring variables, arrays, functions etc.
In ANSI C, the data types are divided into three categories. They are:
1) Primitive or Fundamental data types
2) User-defined data types
3) Derived data types
 Primitive or Fundamental data types - The primitive data types in ANSI C are as shown in
the below diagram:
 User-Defined data types - ANSI C allows the users to define identifiers as their own data
types, based on the already existing primitive or fundamental data types. This concept is
known as “type definition” and the data types thus created are known as user-defined data
types.
We can create user-defined data types in two ways:
1) By using the “typedef” keyword
typedef int rollno;
rollno r1, r2;
2) By using the “enum” keyword
enum identifier{value1, value2… valuen};
enum days{sun,mon,….sat}
 Derived data types - The data types which are created using the already existing primitive or
fundamental types are known as derived data types. Examples of derived data types in C are:
Arrays, Functions, Structures, Unions & Pointers.
Defining Constants in C: As the name suggests the name constants is given to such
variables or values in C programming language which cannot be modified once they are defined.
There can be any types of constants like integer, float, octal, hexadecimal, character constants
etc. In C program we can define constants in two ways as shown below:
1) Using #define preprocessor directive
2) Using a const keyword
 #define preprocessor directive - This directive is used to declare constant variable or any
value. We can use this to declare a constant as shown below:
#define identifierName value
identifierName: It is the name given to constant.
value: This refers to any value assigned to identifierName.
Example: #define PI 3.14 #define CLASS_SIZE 62 #define charVal „G‟
 const keyword - Using const keyword to define constants is as simple as defining variables,
the difference is you will have to precede the definition with a const keyword.
const datatype identifierName=value;
datatype: type of data stored in place of value.
identifierName: It is the name given to constant.
value: This refers to any value assigned to identifierName.
Example: const int intVal = 10; const float floatVal = 4.14;
Declaring a variable as volatile: By declaring a variable as volatile, its value may be
changed at any time by some external source.
ex: volatile int date;
The value of data may be altered by some external factors. When we declare a variable as
volatile, the compiler will examine the value of the variable each time it is encountered to see
any external alteration has changed the value.
Overflow and Underflow: Problem of data overflow and underflow occurs when the value
of a variable is either too big or too small for the type to hold. The largest value that a variable
can hold also depends on the machine. An overflow normally results in the largest value,
whereas an underflow results in zero. C does not provide any warning or indication of integer
overflow. It simply gives incorrect results.
Operators & Expressions: An operator is a symbol that tells a computer to perform certain
mathematical or logical operations. Operators are used in programs to manipulate data and
variables. Generally the usage of an operator is as shown below:
Operand1 Op Operand2
Operand1 and operand2 can be either data or variables or expressions. Op is the operator. In C,
based on the number of operands on which an operator can operate, the operators are divided
into three types namely:
1) Unary
2) Binary
3) Ternary
Different Types of Operators: In C, based on the functionality, operators are classified into
8 categories. They are:
1) Arithmetic Operators (+,-,*,/,%)
2) Relational Operators(<,>,==,!=,>=,<=)
3 )Logical Operators(&&,||,!)
4) Assignment Operators(=,+=,-=,*=,/=,%=)
5) Increment and Decrement Operators (++,--)
6) Conditional Operators(?)
7) Bitwise Operators(&,|,^,~,<<,>>)
8) Special Operators(, & sizeof)
 Arithmetic Operators - C provides all the basic arithmetic operators as shown below. The
arithmetic operators can operate on any built-in data type in C.
 Relational Operators - In C, whenever there is a need to compare two values and make a
decision based on the outcome of the comparison, we use relational operators. The relational
operators are generally used in decision making statements like if, else if and in looping
statements like for, while, do while etc. Relational operators always evaluates to 0 (false) or 1
(true).
 Logical Operators - The relational operators are used to compare at most two values i.e.
testing one condition. To test more than one condition, we use logical operators along with
relational operators. The logical operators always evaluates to either 0 or 1 like relational
operators.
 Assignment Operators - The assignment operators are used to assign value of an expression
to a variable. The general assignment operator is = (equal). In C, there are some special
assignment operators known as shorthand operators. The syntax of shorthand operators is as
shown below:
var op=exp;
 Increment/Decrement Operators - The increment and decrement operators provided by C
are used to increment or decrement the operand by a value of one. Both the increment and
decrement operators are unary operators. There are two variations in increment/decrement
operators
1) pre-increment/decrement(++var/--var)
2) post-increment/decrement(var++/var--)
When pre increment is applied, the value of the variable is incremented by one first and then
that value is used for evaluation of the expression. When post increment is applied, the value of
the variable is used in the evaluation of the expression and after the expression is evaluated, the
value of the variable is incremented by a value of one.
 Conditional Operator - The conditional operator “? :” in C, is a ternary operator, which
operates on three operands. This operator is used to construct conditional expressions of the
form:
exp1?exp2:exp3;
In the above syntax, exp1, exp2 and exp3 refer to expressions.It evaluates the exp1 first and then
based on the result of the exp1 it evaluates either exp2 or exp3. If the result of exp1 is true or
non-zero, then exp2 is executed or if the result of exp1 is false or zero, then exp3 is executed.
 Bitwise Operator’s - C supports a set of operators which operate at bit-level. These operators
are known as bitwise operators. The bitwise operators are used for testing a bit, setting a bit,
complementing a bit or for shifting the bits to left or right. The bitwise operators available in
C are as shown below:
 Special Operator’s - C supports some special operators such as comma “,” operator, sizeof
operator, address “&” operator, pointer operator “*” and some others. The comma “,”
operator is used to combine multiple related expressions together. A comma separated list of
expressions is evaluated from left to right and the value of the right most expression is the
value of the combined expression. The sizeof operator computes the size of an expression or
variable or constant or a data type.
The general syntax of sizeof operator is as shown below:
sizeof(operand);
The operand can be either a value or variable or data type or an expression.
Expression evaluation in C: Expressions are evaluated based on operator precedence and
associativity rules when an expression contains more than one operator. Every C operator has a
precedence (priority) associated with it. This precedence is used to determine how an expression
involving more than one operator is evaluated.
The operators at the higher level of precedence are evaluated first. The operators in the same
level of precedence are evaluated from left to right or from right to left, based on
the associativity property of an operator.
In the below table we can look at the precedence levels of operators and also the associativity of
the operators within the same level. Rank 0 indicates the lowest precedence and Rank 14
indicates highest precedence.
Type casting/ conversion: Typecasting is converting one data type into another one. It is
also called as data conversion or type conversion.
'C' programming provides two types of type casting operations:
1) Implicit type casting
2) Explicit type casting
 Implicit type casting – C automatically converts any intermediate values to the proper type
so that the expression can be evaluated without loosing any significance.
 Explicit type casting - There are some scenarios in which we may have to force type
conversion. Suppose we have a variable div that stores the division of two operands which
are declared as an int data type.
(Type_name)expression;
Examples: x = (int)7.5 a = (int)21.3/(int)4.5 b = (double)sum/n y = (int)(a+b)
z = (int)a + b
Type casting or conversion hierarchy:
Mathematical functions:
Example Programs to be prepared from this module:
C Program to compute area of a circle
#include<stdio.h>
void main()
{
float radius, area;
printf("Enter the radius of Circle : n");
scanf("%d", &radius);
area = 3.14 * radius * radius;
printf("Area of Circle : %f", area);
}
C Program to compute simple interest
#include<stdio.h>
void main()
{
int p,n,r,si;
clrscr();
printf("Enter Principle, Rate of interest & Time :n");
scanf("%d%d%d",&p,&r,&n);
si=(p*n*r)/100;
printf("Simple Interest is :%d",si);
}
Module – 2:Branching & Looping Statements
INPUT-OUTPUT FUNCTIONS: There are two types of a console I/O functions:
1) Formatted input-output function
2) Unformatted input-output function
The major difference is that formatted function allows us to format the input from the keyboard
and the output to be displayed on the screen.
1) Unformatted Input-Output Functions: Unformatted input and output functions are
only work with character data type. Unformatted input and output functions do not require
any format specifiers. Because they only work with character data type.
 getchar() function is used to get/read a character from keyboard input.
var_name = getchar();
 putchar() function is used to write a character on standard output/screen.
putchar(var_name);
Example: char x;
x = getchar();
putchar(x);
 gets() function can read a full string even blank spaces presents in a string. But, the scanf()
function leave a string after blank space space is detected. The gets() function is used to get
any string from the user.
gets(var_name);
 puts() function prints the charater array or string on the console. The puts() function is
similar to printf() function, but we cannot print other than characters using puts() function.
puts(var_name);
Example:
char c[25];
printf("Enter your Name : ");
gets(c);
puts(c);
2) Formatted Input-Output Functions: In C programming language the output is
printed using printf() statement.
There are two simple forms of printf() statement:
 That has a literal string, a sequence of characters within quotation marks.
Syntax: printf(“string”);
Example: printf(“GOD”);
 That has literal string, conversion specifier and any or all of the following: variables,
constant and expressions values to be printed.
Syntax: printf (“format specifier / format string”,list of variables);
Example: printf(“%d%f”,x,y);
C provides scanf function in the stdio.h header file. Using this function we can read values from
the keyboard and assign the values to variables. The syntax of scanf function is as shown below:
scanf(“control string”,&var1,&var2……)
The control string specifies the type of value to read from the keyboard and the ampersand
symbol & is an operator to specify the address the variable(s).
Example: scanf(“%d %f %d”, &a, &b, &c);
scanf(“%c”,&h);
scanf(“%s”, name);
scanf(“%d”,&a[i]);
SELECTION OR BRANCHING STATEMENTS: The C statements that transfer the
control from one place to other place in the program with or without any condition are called
branching or selection statements.
The selection / branching statements can be classified into two categories:
1] Conditional Control /Branch Statements: Conditional branching statements that alter the
sequence of execution of the program based on some condition are called Conditional branching
statements/ selection statements /decision statements.
Conditional Control /Branch Statements are as follows: simple if (single selection), if-else (two
way selection), Nested if (multiple if statements), else –if ladder (multi-way selection), switch (
multi-way selection).
2] Unconditional Control /Branch Statement: The statements that alter the sequence of
execution of the program based on some uncondition are called Unconditional branching
statement.
Unconditional Control /Branch Statements are as follows: Goto Statement, break Statement,
continue Statement and return Statement.
CONDITIONAL BRANCHING STATEMENTS:
a) If Statement(Simple If): : It is basically a two way decision statement it is used in
conjunction with an expression. It is used to execute a set of statements if the condition is
true. If the condition is false it skips executing those set of statements.
The syntax and flow chart of if statement is as illustrated below:
Example: Program to determine whether a person is eligible to vote using if.
#include<stdio.h>
void main()
{
int age;
printf(“ Enter the age :”);
scanf(“%d”,&age);
if(age>=18)
{
printf(“You are eligible to vote”);
}
}
b) If-else Statement: : It is an extension of if statement .It is used to execute any one set of
two set of statements at a time. If condition is true it executes one set of statements otherwise
it executes another set of statements.
The syntax and flow chart of if-else statement is as illustrated below:
Example: Program to determine whether a person is eligible to vote using if-else statement.
#include<stdio.h>
void main()
{
int age;
printf("Enter the age");
scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote");
}
else
{
printf("not eligible");
}
}
c) Nested If-else Statement: : When a series of decisions are involved we may have to use
more than one if else statement in nested form. The nested if else statements are multi
decision statements which consist of if else control statement within another if or else control
statement.
The syntax and flow chart of nested if-else statement is as illustrated below:
Example: Program to find the largest of three numbers using Nested if else statement
#include<stdio.h>
void main()
{
int a,b,c ;
printf("Enter the values of a,b and cn");
scanf("%d %d %d",&a,&b,&c);
if (a>b)
{
if (a>c)
printf(" %d is largest n", a);
else
printf("%d is largest n",c);
}
else
{
if(b>c)
printf(" %d is largest n",b);
else
printf("%d is largest n",c);
}
}
d) If-else ladder (Multi-way Selection): In addition to two-way selection, most
programming languages provide another selection concept known as multi way selection.
Multi-way selection chooses among several alternatives.
When an action has to be performed based on many decisions, then this Statement is used when
more than one if-else statements are used in a sequence, it is called as if-else ladder.
 Syntax of if-else ladder:
if( condition-1)
statement-1;
else if( condition-2)
statement-2;
else if( Condition-3)
statement-3;
else if( condition n)
statement-n;
else
default-statement;
Statement-x;
 Disadvantage: difficult to understand and modify when problem is big, which can be
overcome by using switch Statement.
Example: Program to print the grade obtained by the student based on the given table using else-
if ladder.
#include<stdio.h>
void main()
{
int marks;
printf("Enter the marks n");
scanf("%d",&marks);
if(marks>=0 && marks<=39)
printf("Grade Fn");
else if (marks>=40 && marks<=49)
printf("Grade En");
else if (marks>=50 && marks<=59)
printf("Grade Dn");
else if (marks>=60 && marks<=69)
printf(" Grade Cn");
else if(marks>=70 && marks<=79)
printf("Grade Bn");
else if (marks>=80 && marks<=89)
printf("Grade An");
else if (marks>=90 && marks<=100)
printf("Outstandingn");
else
printf("Invalid Entry n");
}
e) Switch Statement (Multi-way Selection): It is a multi-way decision making control
statement used to make a selection between many alternatives. It is also known as switch
case break and default statement.
 Syntax of Switch Statement:
switch (choice/expression)
{
case value1:block1;
break;
case value2: block2;
break;
case value n: blockn;
break;
default : default_block ;
}
next Statement;
The value of choice or expression is always an integer value/Character. If the value of choice or
expression is 1 then block1 statements will get executed. After executing the respective block the
control comes outside the switch statement because of the break statement. If no case values
matches with the value of the choice, then the default block will get executed before exiting
switch statement.
 Switch Statement Rules:
1) A switch statement begins with the switch keyword that followed by a value expression
in the parenthesis( ).
2) It is a combination of multiple case labels that must be separated by the break statement.
3) Every case label contains a constant value that is matched against the value, which is
specified in the switch expression.
4) If the value is matched, the statements of that case label are executed.
5) In addition, we can specify the default label, which is executed when the value specified
in the switch expression, does not match with the given case labels.
Example: Program to simulate simple calculator using switch statement
#include<stdio.h>
void main()
{
float a,b,res;
char op;
printf("Enter an Expressionn");
scanf("%g %c %g",&a,&op,&b);
switch(op)
{
case '+' : res=a+b;
printf("%g %c %g = %g n",a,op,b,res);
break;
case '-' : res=a-b;
printf("%g %c %g = %g n",a,op,b,res);
break;
case '*' : res=a*b;
printf("%g %c %g = %g n",a,op,b,res);
break;
case '/' : if(b==0)
{
printf("Arthimetic Exception: Cannot Divide a number by 0n");
return;
}
else
{
res=a/b;
printf("%g %c %g = %g n",a,op,b,res);
}
break;
case '%' : res= (int)a % (int)b;
printf("%g %c %g = %g n",a,op,b,res);
break;
default : printf("Invaild operatorn");
break;
}
}
UNCONDITIONAL BRANCHING STATEMENTS: The unconditional branching
statements transfer the control from one statement to another statement in the program without
any conditions.
a) Goto Statement: This statement is used to transfer the control from one point to another
point anywhere in the program. The goto requires a label in order to identify the place where
the branch is to be made.
 The general forms of goto statement:
 Example:
#include<stdio.h>
void main()
{
int a=1;
SHOW:
if(a>10)
{
printf("%d",a);
a+=2;
}
goto SHOW;
}
}
b) Break Statement: The break statement is used to break any type of loop as well as
switch statement. Breaking a loop means terminating the loop.
 The general forms of break statement:
break;
 Example:
switch(opr)
{
case '+':
printf("Sum : %f",(a + b));
break;
} control is transferred to the end of block
c) Continue Statement: The continue statement is used to transfer the control to the
beginning of a statement block in a loop. In other words, a break statement breaks the entire
loop, but a continue statement breaks the current iteration. The continue statement breaks the
current execution of a loop condition and then continue the loop with next condition.
 The general forms of continue statement:
continue;
 Example:
#include<stdio.h>
int main()
{
int i=1;
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5)
{
continue;
}
printf("%d n",i);
} //end of for loop
return 0; }
d) Return Statement: It is used to return the control to the calling function with/without a
value. For example, if a function is not returning any value, use the return keyword
return;
If a function is returning a value, then
return value;
 Example:
int sumDigits()
{
int sum = 0;
int digit;
for(digit = 0; digit <= 9; digit++)
{
sum = sum + digit;
}
return sum; //Returning value & control
}
CONDITIONAL BRANCHING STATEMENTS: The statement which is used to
repeat a set of statements repeatedly for a given number of times or until a given condition is
satisfied is called as looping statements. The set or block of statements used for looping is called
loop.
 Way of Looping:
1) Entry Controlled Loop or pretest loop or top test loop
2) Exit Controlled Loop or posttest loop
 The C Language supports the following three looping operations:
1) The while statement
2) The do while statement
3) The for statement
a) While Loop/Statement (Entry Controlled/Pretest loop): The while statement is the
pretest loop. It uses an expression to control the loop. Since it is a pretest loop, it tests the
expressions before every iterations of the loop.
The syntax and flow chart of While loop is as illustrated below:
Example: Program to find the sum of n natural numbers using while loop
#include<stdio.h>
void main()
{
int i,n,sum=0;
printf("Enter the value of nn");
scanf("%d",&n);
i=0;
while(i<=n)
{
sum = sum + i;
i++;
}
printf("The sum of natural numbers = %d n",sum);
}
b) Do-While Loop/Statemen(Exit Controlled Loop/Post-test): It is an exit controlled
loop. It is also known as posttest or bottom test looping statement.
The syntax and flow chart of Do-While looping statement is as illustrated below:
Example: Program to find the sum of n natural numbers using do while
#include<stdio.h>
void main()
{
int i,n,sum=0;
printf("Enter the value of nn");
scanf("%d",&n);
i=0;
do
{
sum = sum + i;
i++;
}
while(i<=n);
printf("The sum of natural numbers = %d n",sum);
}
 Differences between while & do-while looping statements
c) For Loop/Statement(Entry Controlled/Pre-test loop): The for statement is a pretest
loop that uses three expressions.
Syntax:
for (initialization ; test condition ; increment/decrement)
{
body of the loop;
}
The first expression contains any initialization statements, the second contains the limit-test
expression, and the third contains the updating expression.
1) The initialization set the initial value of the loop control variable.
2) The test condition test the value of the loop control variable.
3) The increment/decrement update the loop control variable.
:
Example: Program to print N Natural Numbers
#include<stdio.h>
void main()
{
int i, N;
printf(“Enter the value of N n”);
scanf(“%d”,&N);
for ( i=0 ; i<=N ; i++)
{
printf(“%dn”,i);
}
}
 Nested for-loop: Nested loops consist of an outer loop with one or more inner loops.
for (i=1;i<=100;i++)
{
for(j=1;j<=50;j++)
{
…
}
}
The above loop will run for 100*50 iterations.
PASCAL TRIANGLE: Pascal Triangle is a Triangle form which, each number is the sum
of immediate top row nearby numbers. The Value of edge is always 1.
 C Program to print pascal triangle
#include <stdio.h>
int main()
{
int rows, cal = 1, space, i, j;
printf("Enter number of rows: "); //enter number of rows for generating the pascal triangle
scanf("%d",&rows);
for(i=0; i<rows; i++) // outer loop for displaying rows
{
for(space=1; space <= rows-i; space++) // space
printf(" ");
for(j=0; j <= i; j++) // inner loop for displaying the pascal triangle of numbers
{
if (j==0 || i==0) // either outer loop value or inner-loop value is "0 " it prints 1
cal = 1;
else
cal = cal*(i-j+1)/j; //calculate the coefficient
printf("%d", cal);
}
printf("n");
}
return 0;
}
Computing binomial-coefficient: binomial coefficient is the number of ways of picking
unordered outcomes from possibilities, also known as a combination or combinatorial number.
 C Program to print binomial-coefficients
#include <stdio.h>
#define MAX 10
void main()
{
int n, a, bi_nom;
n=0;
do
{
a=0; bi_nom=1;
while(a<=n)
{
If(a==0||n==0)
{
printf(“%d”, bi_nom);
}
else
{
bi_nom = bi_nom * (n-a+1)/a;
print(“%d”, bi_nom);
}
a=a+1;
}
printf(“n”);
n=n+1;
}
while(n<=MAX);
}
EXAMPLE PROGRAMS TO BE PREPARED FROM THIS MODULE:
 C Program to compute the roots of a quadratic equation by accepting the coefficients.
Print appropriate messages.
#include<stdio.h>
#include<math.h>
void main( )
{
float a,b,c,disc,root1,root2,real,imag;
printf("Enter a,b,c values n");
scanf("%f%f%f",&a,&b,&c);
disc=(b*b)-(4*a*c);
if((a==0) && (b==0))
{
printf("Invalid co-efficients n");
}
else if(a==0)
{
printf("Linear equation n");
root1=-c/b;
printf("Root=%fn",root1);
}
else if(disc==0)
{
printf("The roots are Real and Equal n");
root1=-b/(2*a);
root2=-b/(2*a);
printf("Root1=%f nRoot2=%fn",root1,root2);
} else if(disc>0)
{
printf("The roots are Real and distinct n");
root1=(-b+sqrt(disc))/(2*a);
root2=(-b-sqrt(disc))/(2*a);
printf("Root1=%fnRoot2=%fn",root1,root2);
}
else
{
printf ("The roots are Real and Imaginary n");
real=-b/(2*a);
imag=sqrt(fabs(disc))/(2*a);
printf ("Root1=%f + i %f n”, real, imag);
printf ("Root2=%f - i %f n”, real, imag);
}
}
 C program to find the reverse of a positive integer and check for palindrome or not.
#include<stdio.h>
void main()
{
long int temp,rev=0,i,num,remainder;
printf("Enter the number n");
scanf("%ld",&num);
temp=num;
while(num!=0)
{
remainder=num%10;
num=num/10;
rev=rev*10+remainder;
}
printf ("The reverse of the number is %ldn”, rev);
if(rev==temp)
printf ("%ld is a palindrome n”, temp);
else
printf ("%ld is not a palindrome n”, temp);
}
 An electricity board charges the following rates for the use of electricity: for the first
200 units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs
1 per unit. All users are charged a minimum of Rs. 100 as meter charge. If the total
amount is more than Rs 400, then an additional surcharge of 15% of total amount is
charged. Write a program to read the name of the user, number of units consumed and
print out the charges.
#include<stdio.h>
#include<string.h>
void main()
{
char name[25];
int units;
float charges=0.0;
printf("Enter Customer Name and Number of Units:n");
scanf("%s %d",name,&units);
if(units<=0)
{
printf("Invalid Units,Please enter valid unitsn");
return;
}
else if(units>=0 && units<=200)
charges= 100+ 0.80* units;
else if(units>201 && units<=300)
charges = 100 + 160+ 0.90 * (units-200);
else if(units>300)
charges= 100 + 250+1.0 * (units-300);
printf("Customer Name=%sn",name);
if(charges>400)
{
charges=charges + 0.15*charges;
printf("Total Charges=%fn",charges);
}
else
printf("Total Charges=%fn",charges);
}
Module – 3:Arrays & Strings
ARRAYS: “An array is a sequential collection/group of homogeneous (same type) elements
which are referred by the same name”
The type refers to the data types like int, char, float etc. All the elements/values in the array are
of the same type (data type). We cannot store values of different data types in the same array.
It is normal in programming to work with a list of values or a group of values at once. For such
purposes, variables cannot be used. So, C language provides the construct array for holding
multiple values at once.
TYPES OF ARRAYS:
1) One-dimensional Arrays: To maintain a list of values.
2) Multidimensional Arrays: To maintain a table of values.
ONE-DIMENSIONAL ARRAYS(1-D Array): For maintaining a list of items in C, we
can declare an array with a single subscript (index). Such arrays with only a single subscript are
known as “one dimensional arrays”.
 Common uses of one dimensional arrays are:
1) To maintain a list of numbers.
2) To maintain the list of marks.
3) To maintain a list of student names etc.
a) One-dimensional Array Declaration: For using arrays in C programs, just like we are
declaring variables before using them, we should declare arrays before using them.
Syntax: for declaring a 1-D Array is shown below:
type arrayName [Size];
Example:
int a[10];
In the above example ‟a’ is an integer array, which can hold 10 integer values.
b) One-dimensional Array Initialization: Initialization means assigning values. To assign
values to the elements in the array.
Generally, there are two types of initializing an array:
1) Static Initialization (at compile time).
2) Dynamic Initialization (at run time).
In static initialization, the elements of an array are assigned values when the program is
compiled.
Syntax for static Initialization:
type arrayName[size] = {value1, value2,…valueN};
Examples:
int a[10] = {1,2,3,4,5,6,7,8,9,10};
int a[5]; a[2] = 10;
int a[10] = {1,2,3,4,5}
In dynamic initialization, the values are assigned to the elements of the array during the
execution of the program.
Example: int a[10], i;
for(i = 0; i < 10; i++)
{
scanf(“%d”,&a[i]);
}
In the above example, the user will be storing the values into the array while executing the
program. Until then, garbage values will be stored in the array. If we use braces i.e., { and }, for
initializing the array, the default values for all the elements in the array will be zero.
c) Example Program on One-dimensional Array: C Program to find Sum and Average of n
Number using 1-D Array
#include<stdio.h>
void main()
{
int i, n, Sum=0, num[100];
float Average;
printf("Enter How many Number you want?n");
scanf("%d",&n);
printf("Enter the elements one by onen");
for(i=0;i<n;i++)
{
scanf("%d",&num[i]);
Sum = Sum + num[i];
}
Average = Sum/n;
printf("Sum of the Numbers = %d", Sum);
printf("Average of the %d Numbers = %.2f", Average);
}
TWO-DIMENSIONAL ARRAYS(2-D Array): A two dimensional array is used to store
a table of values which has rows and columns. An array that has two subscripts (index), for
example: a[i][j] is known as a two dimensional.
 Some of the uses/applications of the two dimensional arrays are:
1) To maintain the marks of students.
2) To maintain prices of items etc…
a) Two-dimensional Array Declaration: For using arrays in C programs, just like we are
declaring variables before using them, we should declare arrays before using them.
Syntax: for declaring a 2-D Array is shown below:
type arrayName [rows] [columns];
Example:
int x[3] [3];
In the above example ‟x’ is an integer array, which can hold 9 integer values.
b) Two-dimensional Array Initialization: Initialization means assigning values. To assign
values to the elements in the array.
Generally, there are two types of initializing an array:
1) Static Initialization (at compile time).
2) Dynamic Initialization (at run time).
In static initialization, the elements of an array are assigned values when the program is
compiled.
Syntax for static Initialization:
type arrayName[row] [columns]= {value1, value2,…valueN};
arrayName[row] [coumns] = value;
Examples: a [0] [0] = 1; int a [3] [3] = {1,1,1,2,2,2,3,3,3};
The memory representation of the two dimensional array will be as shown below:
In dynamic initialization, the values are assigned to the elements of the array during the
execution of the program.
Example: int a[3] [3], i, j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”, a[i][j]);
}
}
c) Example Program on Two-dimensional Array: C Program to find Transpose of a matrix
#include <stdio.h>
void main()
{
int a[10][10], t[10][10], m, n, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);
printf("nEnter elements of matrix:n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &a[i][j]);
}
}
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
t[j][i] = a[i][j];
}
}
printf("nTranspose of Matrix:n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("%d ",t[i][j]);
}
}
SEARCHING: The process of finding a particular item in the large amount of data is called
“searching”. The element to be searched is called “key element”.
There are two methods of searching:
1] Linear search. 2] Binary search.
Linear search also called sequential search is a simple searching technique. In this technique we
search for a given key item in linear order i.e. one after the other from first element to last
element. If key item is present, the search is successful, otherwise unsuccessful search.
1] LINEAR SEARCH:
 Algorithm:
Linear_search (list, value)
for each item in the list
if key == value
return successful
else
return unsuccessful
end if
end for
end procedure
 C Program to perform Linear Search:
#include<stdio.h>
void main()
{
int i,n,a[10],key;
printf(“enter array elementsn”);
scanf(“%d”,&n);
printf(“enter array elementsn”);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
}
printf(“enter the key elementn”);
scanf(“%d”,,&key);
for(i=0; i<n;i++)
{
if(key==a[i])
{
printf(“successful searchn”);
exit(0);
} }
printf(“unsuccessful searchn”);
}
2] BINARY SEARCH: This search algorithm works on the principle of divide and conquers.
For this algorithm to work properly, the data should be in the sorted.
There are 3 cases in binary search algorithm
1) Comparing the middle most item of the collection. If a match occurs, then the index of
item is returned.
2) If the middle item is greater than the item, then the item is searched in the sub-array to
the left of the middle item.
3) Otherwise, the item is searched for in the sub-array to the right of the middle item.
This process continues on the sub-array as well until the size of the sub-array reduces to zero.
 C Program to perform Binary Search:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[50],n,i,key,low,mid,high;
printf("enter the number of elementsn");
scanf("%d",&n);
printf("enter the array elementsn");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("enter the key element to be searchedn");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==key)
{
printf("ELEMENT %d FOUND AT POSITION %dn",key,mid+1);
exit(0);
}
else if (a[mid]>key)
high=mid-1;
else
low=mid+1;
}
printf("UNSUCCESSFULL SEARCHn");
return 0;
}
SORTING: A Sorting is used to rearrange a given array or list elements according to a
comparison operator on the elements. The comparison operator is used to decide the new order
of element in the respective list of elements.
There are two methods of sorting:
1] Bubble Sort. 2] Selection Sort.
1] BUBBLE SORT: Bubble sort is a simple sorting algorithm. This sorting algorithm is
comparison-based algorithm in which each pair of adjacent elements is compared and the
elements are swapped if they are not in order.
This algorithm is not suitable for large data sets.
Algorithm: Bubble Sort compares each pair of array element unless the whole array is
completely sorted in an ascending order.
for(i=1; i<n; i++) //for loop for number of passes
{
for(j=0;j<n-i;j++) //for loop for number of comparisons
{
if(a[j]>a[j+1]) //Comparison
{
temp=a[j]; //Swap using temp
a[j]=a[j+1];
a[j+1]=temp;
}
} }
 C Program to perform Bubble sort:
#include<stdio.h>
void main()
{
int a[50],i,j,n,temp;
printf("enter the number of termsn");
scanf("%d",&n);
printf("enter the array elementsn");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("nARRAY ELEMENTS AFTER SORTINGn");
for(i=0;i<n;i++)
{
printf("%dt",a[i]);
}
printf("n");
}
2] SELECTION SORT: The Selection sort algorithm is based on the idea of finding the
minimum or maximum element in an unsorted array and then putting it in its correct position in a
sorted array.
 Algorithm:
Selection_sort (int A[ ], int n)
{
int minimum; // temporary variable to store the position of minimum element
for(int i = 0; i < n-1 ; i++) // reduces the comparison size by one in each iteration.
{
minimum = i ; // assuming the first element to be the minimum.
for(int j = i+1; j < n ; j++ ) // gives the effective size of the unsorted array
{
if(A[ j ] < A[ minimum ]) { //finds the minimum element
minimum = j ;
}
}
swap ( A[ minimum ], A[ i ]) ; // putting minimum element on its proper position.
}
}
 C Program to perform Selection Sort:
#include <stdio.h>
void main()
{
int a[100], n, i, j, minimum,temp;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d integersn", n);
for (i = 0; i< n; i++)
{
scanf("%d", &a[i]);
}
for(int i = 0; i < n-1 ; i++)
{
minimum = i ;
for(int j = i+1; j < n ; j++ )
{
if(a[ j ] < a[ minimum ])
{
minimum = j ;
}
}
if (a[minimum ]!= a[i])
{
temp= a[i];
a[i] = a[minimum];
a[minimum] = temp;
}
}
printf("Sorted list in ascending order:n");
for (i = 0; i < n; i++)
{
printf("%dn", a[i]);
}
}
STRINGS: A string is a sequence of characters terminated with a null character 0. A group of
characters enclosed in double quotes is known as a string constant.
 Some of the examples of string constants are:
1)“hai”
2)“hello world”
3)“My name is NITHIN”
In C programming, there is no predefined data type to declare and use strings. So, we use
character arrays to declare strings in C programs.
Example: char s[5];
a) String Declaration & Initialization: we should declare strings before using them in
the program. Strings are implemented as character arrays.
Syntax: char string_name[size];
Example: char student_name[26];
When the compiler assigns a character string to a character array, it appends a „0‟ to the end of
the array. So, the size of the character array should always be number of characters plus 1.
Character arrays can also be initialized when they are declared. Some of the examples for
initializing the string are as shown below:
1) char name[13] = {„N‟,‟I‟,‟T‟,‟H‟,‟I‟,‟N‟,‟‟,‟K‟,‟U‟,‟M‟,‟A‟,‟R‟,‟0‟};
2) char name[13] = “NITHIN KUMAR”;
If less number of characters are provided than the size of the string, the rest of the characters are
initialized to „0‟.
b) Reading & Writing Strings: There are two ways read & write the strings
1) Formatted input/output – scanf & printf
2) Unformatted input/output – gets & puts
 Syntax for formatted input/output:
1) Read – char str[10];
scanf(“%s”, str);
2) Print – printf(“The string is %s”, str);
 Syntax for unformatted input/output:
1) Read – char str[10];
gets(str); //gets(array_name);
2) Print – printf(“The string is:”);
puts(str); //puts(array_name);
 Example C program to Read & Print Strings:
/*Using scanf & printf*/
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
}
/*Using gets & puts*/
#include <stdio.h>
void main()
{
char name[20];
printf("Enter name: ");
gets(name);
printf("Name: ");
puts(name);
}
STRING-MANIPULATION FUNCTIONS(Built-in String Functions): C provides
predefined functions for performing all operations or manipulations on strings. Most of these
predefined functions are available in string.h header file. The list of predefined functions is
given below:
1) String-concatenate (strcat): The strcat predefined function is used to concatenate/join
two strings together. The syntax of the strcat function is shown below:
strcat(string1,string2);
The strcat function accepts two parameters which are strings. The strcat function takes the
content of string2 and merges it with the content in string1 and the final result will be stored
in string1.
Example:
2) String-length (strlen): The strlen function is used to retrieve the length of a given
string. The return type of this function will be an integer. The syntax of strlen function is as
shown below:
strlen(string);
The function returns the length of the string which will be the number of characters in the string
excluding the „0‟ character.
Example:
3) String-compare (strcmp): The strcmp predefined function is used to compare two
strings. The syntax of strcmp function is as shown below:
strcmp(string1,string2);
After comparison:
1) If the two strings are equal, then the function returns a 0.
2) If 1st
string is greater than 2nd
string returns 1.
3) If 1st
string is lesser than 2nd
string returns –1.
Example:
4) String-copy (strcpy): The strcpy function is used to copy one string into another string.
This function can be used for creating a copy of an existing string. The syntax
of strcpy function is as shown below:
strcpy(string1,string2);
The string in string2 is copied into string1 and the result will be stored in string1
Example:
5) String-reverse (strrev): The strrev function is used to reverse a given string. We can
use this predefined function to check whether a given string is a palindrome or not. The
syntax for using the strrev function is as shown below:
strrev(string);
the strrev function reverses the given string and returns it back. The content of the string also
changes.
Example:
EXAMPLE PROGRAMS TO BE PREPARED FROM THIS MODULE:
 C program to print String Length without Built-in function
#include<stdio.h>
#include<string.h>
int my_strlen(char[]);
void main()
{
int len;
char str1[26]];
printf("Enter String1:");
scanf("%s",str1);
len=my_strlen(str1);
printf("Length of "%s" is %d n",str1,len);
}
int my_strlen(char str1[])
{
int i=0;
while(str1[i] != '0')
i++;
return i;
}
 C program to Compare two String’s without Built-in function
#include<stdio.h>
#include<string.h>
int my_strcmp(char[],char[]);
void main()
{
int comp;
char str1[26], char str2[26];
printf("Enter String1:");
scanf("%s",str1);
printf("Enter String2:");
scanf("%s",str2);
comp=my_strcmp(str1,str2);
if(comp==0)
printf("%s is equal to %sn",str1,str2);
else if(comp>0)
printf("%s is greater than %sn",str1,str2);
else printf("%s is less than %sn",str1,str2);
int my_strcmp(char str1[],char str2[])
{
int i=0;
while(str1[i]==str2[i])
{
if(str1[i]=='0')
break;
i++;
}
return str1[i]-str2[i];
}
 C program to concate two String’s without Built-in function
#include<stdio.h>
#include<string.h>
void my_concat(char[],char[]);
void main()
{
int comp;
char str1[26], char str2[26];
printf("Enter String1:");
scanf("%s",str1);
printf("Enter String2:");
scanf("%s",str2);
my_concat(str1,str2);
void my_concat(char str1[],char str2[])
{
int i=0,j=0;
while(str1[i]!='0')
i++;
while(str2[j]!='0')
{
str1[i++]=str2[j++];
}
str1[i]='0';
printf("Concatenated string is "%s"n",str1);
}
 Program to find sum of n array elements
#include<stdio.h>
void main()
{
int i,n,a[10],sum=0;
printf(“enter number of array elementsn”);
scanf(“%d”,&n);
printf(“enter array elementsn”);
for(i=0; i<n; i++)
{
scanf(“%d”,&a[i]);
}
for(i=0; i<n;i++)
{
sum=sum+ a[i];
} printf(“sum is %dn”,sum):
}
 Program to find largest of n elements stored in an array
#include<stdio.h>
void main()
{
int i,n,a[10],big;
printf(“enter number of array elementsn”);
scanf(“%d”,&n);
printf(“enter array elementsn”);
for(i=0; i<n;i++)
{
scanf(“%d”,&a[i]);
}
big=a[0];
for(i=0; i<n;i++)
{
if(a[i]>big)
big=a[i];
}
printf(“the biggest element in an array is %dn”,big);
}
 Program to perform Matrix Multiplication.
#include<stdio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],m,n,p,q,i,j,k;
printf("Enter the size of first matrix n");
scanf("%d %d",&m,&n);
printf("Enter the size of second matrix n");
scanf("%d %d",&p,&q);
if(n==p)
{
printf("Enter the elements of first matrix n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter the elements of the second matrix n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("The product of two matrix is n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%dt",c[i][j]);
}
printf("n");
}
}
else
printf("Multiplication is not possible n");
}
Module – 4:User Defined Functions & Recursive Functions
FUNCTIONS: “In c, we can divide a large program into the basic building blocks known
as function. The function contains the set of programming statements enclosed by {} that
performs a particular task/job”.
A function can be called multiple times to provide reusability and modularity to the C program.
In other words, we can say that the collection of functions creates a program. The function is also
known as procedure or subroutine in other programming languages.
Example: void hello( )
{
printf("hello nithin");
}
Need of Functions: Until now, in all the C programs that we have written, the program consists
of a main function and inside that we are writing the logic of the program.
The disadvantage of this method is, if the logic/code in the main function becomes huge or
complex, it will become difficult to debug the program or test the program or maintain the
program. So we‟ll break down entire logic into different parts, this type of approach for solving
the given problems is known as Top Down approach.
Advantages of Functions: Functions have many advantages in programming. Almost all the
languages support the concept of functions in some way. Some of the advantages of
writing/using functions are:
 Functions support top-down modular programming.
 By using functions, the length of the source code decreases.
 Writing functions makes it easier to isolate and debug the errors.
 Functions allow us to reuse the code.
TYPES OF FUNCTIONS: Based on the nature of functions, they can be divided into two
categories. They are:
1) In-built functions / Predefined functions / Library functions
2) User defined functions
a) In-built functions / Predefined functions: is a function which is already written by another
developer. The users generally use these library functions in their own programs for
performing the desired task.
The predefined functions are available in the header files. So, the user has to include the
respective header file to use the predefined functions available in it.
Example: the printf function which is available in the <stdio.h> header file is used for
printing information.
Other examples of predefined functions are: scanf, strlen, strcat, sqrt, fabs etc.
b) User defined functions: A user defined function is a function which is declared and defined
by the user himself. While writing programs, if there are no available library functions for
performing a particular task, we write our own function to perform that task.
Example: for user defined function is main function.
BASIC ELEMENTS OF USER DEFINED FUNCTION: For creating user defined
functions in C programs, we have to perform three steps. They are:
a) Function Declaration: Declaring the function (blue-print).
b) Function Definition: Defining the function (logic).
c) Function Calling: use of function in program (calling)
a) FUNCTION DECLARATION: The function declaration is the blue print of the function.
The function declaration can also be called as the function’s prototype.
The function declaration tells the compiler and the user about what is the function‟s name,
inputs and output(s) of the function and the return type of the function.
Syntax: for declaring a function is shown below:
return_type function_name(parameters list);
Example:
int add(int m, int n);
In the above example, add is the name of the function, int is the return type of the function.
In our example, add function has two parameters. The parameters list is optional.
b) FUNCTION DEFINITION: The function definition specifies how the function will be
working i.e the logic of the function will be specified in this step.
Syntax: of function definition is shown below
return_type function_name(parameters list)
{
local variable declaration's;
---
return(expression);
}
Example:
int add(int a, int b)
{
int res;
res = a+b;
return res;
}
c) FUNCTION CALLING: After declaring and defining the functions, we can use the
functions in our program. For using the functions, we must call the function by its name.
Syntax: of function definition is shown below
function_name(parameters list);
Example: add(m,n);
Whenever the compiler comes across a function call, it takes the control of execution to the
first statement in the function‟s definition. After the completion of function i.e., whenever the
compiler comes across the return statement or the closing brace of the function‟s body, the
control will return back to the next statement after the function call.
CATEGORIES OF USER DEFINED FUNCTIONS: A function may or may not
accept any argument. It may or may not return any value. Based on these facts, there are four
different aspects of function calls.
a) function without arguments and without return value
b) function without arguments and with return value
c) function with arguments and without return value
d) function with arguments and with return value
a) Function without arguments and without return value: In this type of functions there are
no parameters/arguments in the function definition and the function does not return any value
back to the calling function.
Generally, these types of functions are used to perform housekeeping tasks such as printing
some characters etc.
Example:
void printstars( ){
int i;
for(i = 0; i < 20; i++)
{
printf(“ * ”);
}
}
In the above example, printstars function does not have any parameters. Its task is to print
20 stars whenever it is called in a program.
b) Function without arguments and with return value: In this type of functions, the function
definition does not contain arguments. But the function returns a value back to the point at
which it was called.
Example:
int readint( )
{
int num;
printf(“Enter a number: “);
scanf(“%d”,&num);
return num;
}
In the above example, readint function has no parameters/arguments. The task of this
function is to read an integer from the keyboard and return back to the point at which the
function was called.
c) Function with arguments and without return value: In this type of functions, the function
definition contains arguments. But the function does not returns a value back to the point at
which it was called.
Example:
void sum(int a, int b)
{
printf("nThe sum is %d",a+b);
}
In the above example, sum function has two parameters/arguments. The task of this function
is to print the sum without using return value.
d) Function with arguments and with return value: In this type of functions, the function
definition consists of parameters/arguments. Also, these functions returns a value back to the
point at which the function was called. These types of functions are the most frequently used
in programming.
Example: int add(int x, int y)
{
int result;
result = x + y;
return result;
}
In the above example, the function add consists of two arguments or parameters x and y. The
function adds both x and y and returns that value stored in the local variable result back to
the point at which the function was called.
PROGRAM TO FIND GCD & LCM USING FUNCTIONS:
NESTED FUNCTION: A function calling another function within its function definition is
known as a nested function.
So, far we are declaring a main function and calling other user-defined functions and predefined
functions like printf, scanf, gets, puts etc., So, main function can be treated as a nested
function.
Example:
void main()
{
func1();
}
void func1()
{
for(i=1;i<10;i++)
{
func2();
}
}
void func2()
{
printf(“%dn”,i);
}
PARAMETERS PASSING IN C FUNCTION: When a function gets executed in the
program, the execution control is transferred from calling-function to called function and
executes function definition, and finally comes back to the calling function.
When the execution control is transferred from calling-function to called-function it may carry
one or number of data values. These data values are called as parameters. In C, there are two
types of parameters and they are as follows:
1) Actual Parameters
2) Formal Parameters
There are two methods to pass parameters from calling function to called function and they are
as follows...
1) Pass by Value
2) Pass by Reference
In C, there are two types of parameters and they are as follows:
There are two methods to pass parameters from calling function to called function:
a) PASS BY VALUE: In call by value parameter passing method, the copy of actual parameter
values are copied to formal parameters and these formal parameters are used in called
function.
The changes made on the formal parameters does not effect the values of actual
parameters. That means, after the execution control comes back to the calling function, the
actual parameter values remains same.
Example:
void swap(int a, int b) // called function
{
int temp;
temp = a;
a = b;
b = temp;
}
b) PASS BY REFERENCE: In Call by Reference parameter passing method, the memory
location address of the actual parameters is copied to formal parameters. This address is used
to access the memory locations of the actual parameters in called function.
Whenever we use these formal parameters in called function, they directly access the
memory locations of actual parameters. So the changes made on the formal parameters
effects the values of actual parameters.
Example:
void swap(int *a, int *b) // called function
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Difference between Pass by Value & Reference:
SCOPE, VISIBILITY & LIFETIME OF VARIABLES (STORAGE CLASSES)
 “auto” This is the default storage class for all the variables declared inside a function or a
block. Hence, the keyword auto is rarely used while writing programs in C language.
Auto variables can be only accessed within the block/function they have been declared and
not outside them (which defines their scope).
example: auto int i=1;
They are assigned a garbage value by default whenever they are declared.
 “extern” extern storage class simply tells us that the variable is defined elsewhere and not
within the same block where it is used.
The main purpose of using extern variables is that they can be accessed between two
different files which are part of a large program.
example: int i=1;--------- extern int i;
a normal global variable can be made extern as well by placing the „extern‟ keyword before
its declaration/definition in any function/block.
 “static” This storage class is used to declare static variables which are popularly used while
writing programs in C language.
Static variables have a property of preserving their value even after they are out of their
scope! Hence, static variables preserve the value of their last use in their scope.
example: static int i=1;
Global static variables can be accessed anywhere in the program. By default, they are
assigned the value 0 by the compiler.
 “register” This storage class declares register variables which have the same functionality as
that of the auto variables.
The only difference is that the compiler tries to store these variables in the register of the
microprocessor if a free register is available. This makes the use of register variables to be
much faster than that of the variables stored in the memory during the runtime of the
program.
example: register int i;
An important and interesting point to be noted here is that we cannot obtain the address of a
register variable using pointers.
RECURSIVE FUNCTION: A function is said to be recursive, if a function calls itself
within the function‟s definition.
When writing recursive functions, proper care must be taken that the recursive calls return a
value back at some point. Otherwise, the function calls itself infinite number of times.
Example:
In the above example, func1 is calling itself in the last line of its definition.
 FACTORIAL OF A NUMBER – Factorial of n is the product of all positive descending
integers. Factorial of n is denoted by n!
Example: 5! = 5*4*3*2*1 = 120
Recursive Function:
5! = 5 * 4! // n * Fact(n-1)
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1 * 0!
0! = 1 //Stop Condition
Program to find factorial of given number using recursion:
#include<stdio.h>
int find_factorial(int);
void main()
{
int num, fact;
printf("nEnter any integer number:");
scanf("%d",&num);
fact =find_factorial(num);
printf("nfactorial of %d is: %d",num, fact);
}
//recursive function definition
int find_factorial(int n)
{
if(n==0)
{
return 1;
}
else{
return(n*find_factorial(n-1));
}
}
 FIBONACCI SERIES – a series of numbers in which each number ( Fibonacci number ) is
the sum of the two preceding numbers.
Example: 0, 1, 1, 2, 3, 5, 8, etc.
The first two numbers of fibonacci series are 0 and 1.
Recursive Function: There are 3 cases in fibonacci series
1) if n = 1 only one digit to be printed i.e “0”.
2) if n = 2 only two digit to be printed i.e “1”.
3) if n > 2 last two digits to be added & printed so “fib(n-1) + fib(n-2)”
Program to find Fibonacci Series using recursion:
#include<stdio.h>
int fib(int);
void main()
{
int n, i = 0, c;
printf(“enter N valuen”);
scanf("%d", &n);
printf("Fibonacci series terms are:n");
for (c = 1; c <= n; c++)
{
printf("%dn", fib(i));
i++;
}
}
int fib(int n)
{
if (n == 0 || n == 1)
return n;
else
return (fib(n-1) + fib(n-2));
}
EXAMPLE PROGRAMS TO BE PREPARED FROM THIS MODULE:
Program to Convert Binary number to Decimal:
#include <stdio.h>
int convert(int);
void main()
{
int dec, bin;
printf("Enter a Binary numbern");
scanf("%d", &bin);
dec = convert(bin);
printf("The Decimal Equivalent of %d is %d n", bin, dec);
}
int convert(int bin)
{
if (bin == 0)
{
return 0;
}
else
{
return (bin % 10 + 2 * convert(bin/10));
}
}
Program to check whether the given number is prime or not:
#include<stdio.h>
int isPrime(int);
void main()
{
int res,num;
printf("Enter the number:");
scanf("%d",&num);
res=isPrime(num);
if(res==0)
printf("%d is not a Prime Numbern",num);
else
printf("%d is a Prime Numbern",num);
}
int isPrime(int num)
{
int i;
if (num==0 || num==1)
return 0;
for (i=2; i<=num/2; i++)
{
if (num %i == 0)
{
return 0;
}
}
return 1;
}
Module – 5:Structures, Pointers & Preprocessor Directives
STRUCTURES: “A structure is a collection of heterogeneous data elements referred by
the same name”.
 Drawback of arrays: arrays can be used to represent a collection of elements of the same
data type like int, float etc. They cannot be used to hold a collection of different types of
elements.
 Syntax of Structure: structures must be first defined first for their later use. The syntax for
defining a structure is as shown below:
struct structure_name
{
datatype var1;
datatype var2;
-------
};
The keyword struct declares a structure. The structure_name represents the name of the
structure. The structure definition is always terminated with a semicolon.
 Example:
struct student
{
int rollno;
char name[26];
int marks;
};
In the above example, student is the name of the structure. The members of the student structure
are: name, rollno and marks. A structure itself does not occupy any memory in the RAM.
Memory is allocated only when we create variables using the structure.
a) Declaring Structure Variables: A structure variable declaration is similar to the declaration
of variables of any other data types.
 Syntax for declaring structure variables:
struct structurename var1, var2, …., varN
 Example:
struct student s1, s2, s3;
We can also combine the structure definition and the declaration of structure variables into a
single line such structures are called “Tagged Structures” as shown below:
struct student
{
int rollno;
char name[26];
int marks;
} s1, s2, s3;
We can use the keyword typedef to define a structure as follows:
typedef struct
{
int rollno;
char name[26];
int marks;
}student;
The name student represents the structure definition associated with it and therefore can be used
to declare structure variables as shown below:
student s1, s2, s3;
b) Accessing Structure Members: We can access and assign values to the members of a
structure in a number of ways. They should be linked to the structure variables in order to
make them meaningful members.
The link between a member and a variable is established using the member operator „.‟ which
is also known as dot operator or period operator.
 Syntax for accessing a structure member:
structure-varaible.membername
 Example:
s1.name
s1.rollno
c) Structure Initialization: The values can be initialized in two ways
1) static initialization
2) dynamic initialization
 Example for static initialization:
struct student
{
int rollno;
char name[26];
int marks;
} ;
struct student s1 = {“01”, “nithin”,”96”};
struct student s2 = {“02”,”gowda”,”56”};
 Example for dynamic initialization:
scanf(“%d”, &s1.rollno);
scanf(“%s”, s1.name);
scanf(“%d”, s1.marks);
ARRAYS OF STRUCTURES: If we want to store details of 100 students it will become
difficult to declare and maintain 100 variables and store the data. Instead, we can declare and
array of structure variables as shown below:
struct student
{
int rollno;
char name[26];
int marks;
} ;
struct student s[100];
In the above example, we are declaring an array „s‟ with 100 elements of the type student which
is a structure.
NESTED STRUCTURES: In C, structures can be nested. A structure can be defined
within in another structure.
 Example of nested structure:
struct student
{
struct name
{
char fname[10];
char lname[10];
};
int rollno;
int marks;
};
In the above example, student is the outer structure and the inner structure name consists of two
members: fname and lname.
 The members of the inner structure can be accessed as shown below:
outer_structure_variable.inner_structure_variable.member_name;
Example: s1.name.fname;
PASSING STRUCTURES TO FUNCTIONS: Functions are the basic building blocks
of a C program. So, it is natural for C language to support passing structures as parameters in
functions.
We can pass the C structures to functions in 3 ways:
1) Passing each individual item of the structure as a function argument.
2) Passing the whole structure as a value.
3) Passing the address of the structure (pass by reference).
Syntax for passing the structure variable as a parameter is shown below:
return-type function-name(struct structname var)
{
----
----
return expression;
}
1] PASSING STRUCTURE TO FUNCTION IN C BY VALUE : the whole structure is
passed to another function by value. It means the whole structure is passed to another function
with all members and their values. So, this structure can be accessed from called function.
Example for pass by value:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record);
void main()
{
struct student record = {“01”, “Nithin”,”69”}
func(record);
}
void func(struct student record)
{
printf(" Id is: %d n", record.id);
printf(" Name is: %s n", record.name);
printf(" Percentage is: %f n", record.percentage);
}
2] PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS : the whole structure is
passed to another function by address. It means only the address of the structure is passed to
another function. The whole structure is not passed to another function with all members.
Example for pass by Address(reference)::
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
void main()
{
struct student record = {“01”, “Nithin”,”69”}
func(&record);
}
void func(struct student record)
{
printf(" Id is: %d n", record->id);
printf(" Name is: %s n", record->name);
printf(" Percentage is: %f n", record->percentage);
}
 C program to read, write & compute average marks of N students using
strurcture
#include<stdio.h>
struct student
{
int roll;
char name[50];
int marks;
};
void main()
{
struct student s[10];
int i,n,sum=0;
float average=0.0;
printf("Enter the number of studentsn");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the roll number:");
scanf("%d",&s[i].roll);
printf("Enter the Name:");
scanf("%s",s[i].name);
printf("Enter Total Marks:");
scanf("%d",&s[i].marks);
}
for(i=0;i<n;i++)
{
sum=sum+s[i].marks;
}
average=(float)sum/n;
printf("Class Average is %gn",average);
printf("Record details of students:n");
for(i=0;i<n;i++)
{
printf("%4d",s[i].roll);
printf("%15s",s[i].name);
printf("%15d",s[i].marks);
if(s[i].marks>=average)
printf("tYes");
else
printf("tNo");
printf("n");
}
}
POINTERS: A pointer is a derived data type in C. It is built from one of the fundamental data
types available in C. Pointers contain memory addresses as their values. Since these memory
addresses are the locations in the computer memory where program instructions and data are
stored.
pointers can be used to access and manipulate data stored in the memory.
 Advantages of Pointers: Pointers are used frequently in C, as they offer a number of
benefits to the programmers. They include the following:
 Pointers are more efficient in handling arrays and data tables.
 Pointers allow C to support dynamic memory management.
 Pointers provide an efficient way for manipulating dynamic data structures such as
structures, linked lists, queues, stacks and trees.
 Pointers increase the execution speed and thus reduce the program execution time.
 Pointers can be used to return multiple values from a function via function arguments.
 Pointers allow passing a function as argument to other functions.
 How a Pointer Works: Whenever we declare a variable in our programs, the system
allocates somewhere in the memory, an appropriate location to hold the value of the variable.
This location will have its own address number. Consider the following example:
The above statement int var creates a location in the memory to hold integer value. That location
will have an address for example assume it is 5000. The statement var = 200 stores the value 200
at the location whose address is 5000. So, in our example, var is the variable name, 200 is the
value stored in var and 5000 is the address of the memory location containing the variable var.
So, we can access the value 200 either by using the variable name var or by using the address of
the memory location which is 5000.‟
a) Pointer Variable, Constants & Values: “The concept of storing memory address in
a variable and accessing the value available at that address is known as a pointer variable.”
Since the pointer is also variable, it will also have a memory address just like any other variable.
 Pointer Constants: The memory addresses within a computer are referred to as pointer
constants.
 Pointer Values: We cannot assign the memory addresses directly to a variable. We can only
get the address of a variable by using the address operator (&). The value thus obtained is
known as pointer value.
 Pointer Variables: Once we obtain the pointer value, we can store it in a variable. Such
variable which stores the memory address is known as a pointer variable.
b) Declaring Pointer Variables: In C, every variable must be declared for its type. Since
pointer variables contain addresses that belong to a specific data type, they must be declared
as pointers before we use them.
 Syntax for declaring a pointer is as shown below:
datatype *pointer-name;
This tells the compiler three things about the variable pointer-name. They are: The asterisk (*)
tells that the variable pointer-name is a pointer variable, pointer-name needs a memory location
and pointer-name points to a variable of type datatype.
 Example:
int *p; float *p; char *ch;
c) Initialization of pointer variables: The process of assigning the address of a variable
to pointer variable is known as initialization.
 Method-1:
int x; //declare a data variable
int *px; //declare a pointer variable
px=&x // copy the address of data variable to pointer variable
 Method-2:
int x; //declare a data variable
int *px=&x; //assign the address of data variable to pointer variable
 Method-3:
int x,*px=&x; //declare data variable and assign address
d) Dereferencing: Dereferencing a pointer means getting the value that is stored in the
memory location pointed by the pointer. The operator * is used to do this, and is called
the dereferencing operator.
Another name for the dereferencing operator is the indirection operator.
 Example:
int quantity, *p, n;
quantity=179;
p=&quantity;
n=*p;
CHAIN OF POINTERS(MULTIPLE INDIRECTIONS): It is possible to make a
pointer to point to another pointer, thus creating a chain of pointers.
A variable that is a pointer to a pointer must be declared using additional indirection operator
symbols in front of the name
Here, the pointer variable p2 contains the address of the pointer variable p1, which points to the
location that contains the desired value.
 Example: int **p2
Consider the following example:
void main()
{
int x,*p1, **p2;
x=100;
p1=&x;
p2=&p1;
printf(“%d”, **p2);
}
RULES OF POINTERS OPERATIONS:
 A pointer variable can be assigned the address of another variable.
 A pointer variable can be assigned the values of another pointer variable.
 A pointer variable can be initialized with NULL or zero value.
 A pointer variable can be pre-fixed or post-fixed with increment or decrement operators.
 An integer value may be added or subtracted from a pointer variable.
 A pointer variable cannot be multiplied by a constant.
 Two pointer variables cannot be added.
 A value cannot be assigned to an arbitrary address(i.e., &x=10; is illegal)
Pointers in Arrays: Consider an 1D-Array
x[5] = {100,101,102,103,104}
 If we declare ptr as an integer pointer, then we can make the pointer ptr to point to the array
x by the following assignment:
ptr=x; this is equivalent to ptr=&x[0];
 We can access every value of x using p++ to move from one element to another
 The address of an element is calculated using its index and the scale factor of the data type
address of x[n] = base address+(n * scale factor of datatype)
 Example: consider 1000 as base address & scale factor of int = 2 bytes
x[3] = 1000+(3*2) = 1006.
While working with 2D arrays, we must use two pointers such that one pointer points index “i”
& another one points index “j”.
ARRAYS OF POINTERS: One of the important uses of pointer is in handling of a table of
strings.
 Consider the following array of strings:
char name[3][25]; //requires 75bytes
 Instead of making each row a fixed number of characters, we can make it a pointer to a string
of varying length.
char *name[3]= {“Mysuru”,“Mandya”,“Hassan”};
Declares name to be an array of three pointers to characters, which requires only 21 bytes,
sufficient to hold all the characters.
 The following statement would print out all the three names:
for(i=0;i<=2;i++)
printf(“%sn”,name[i]);
The character arrays with the rows of varying length are called “ragged arrays” and they are
better handled by pointers.
POINTERS AS FUNCTION ARGUMENTS: When we pass the address of a variable
as an argument the receiving parameter should be pointers. This process of calling a function
using pointers to pass the addresses of variables is known as “Call by reference”.
This method will directly access the memory locations of actual parameters. So the changes
made on the formal parameters effects the values of actual parameters.
 Example:
void swap(int *a, int *b) // called function
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Passing Structures to Functions (using Pointers): Functions are the basic building blocks of a
C program. So, it is natural for C language to support passing structures as parameters in
functions.
 We can pass the C structures to functions using pointers its also called as “Passing the
address of the structure (pass by reference)”.
 Syntax for passing address the structure variable using pointer as a parameter:
return-type function-name(struct structname *var)
{
----
return expression;
}
We can access the members of structure using “arrow () operator or membership operator”.
 Example:
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
void main()
{
struct student record = {“01”, “Nithin”,”69”}
func(&record);
}
void func(struct student record)
{
printf(" Id is: %d n", record->id);
printf(" Name is: %s n", record->name);
printf(" Percentage is: %f n", record->percentage);
}
DRAWBACKS OF POINTERS:
 Uninitialized pointers might cause segmentation fault.
 Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to
memory leak.
 Pointers are slower than normal variables.
 If pointers are updated with incorrect values, it might lead to memory corruption.
 Understanding and using pointers in best way possible requires a lot of time.
PREPROCESSOR DIRECTIVES: C provides many features like structures, unions and
pointers. Another unique feature of the C language is the preprocessor.
 Preprocessor directives are placed in the source program before the main line. Before the
source code passes through the compiler, it is examined by the preprocessor for any
preprocessor directives.
“Preprocessor directives are lines included in a program that begin with the character #, which
make them different from a typical source code text. They are invoked by the compiler to process
some programs before compilation.”
 The preprocessor directives are divided into four categories. They are:
1) Macro Substitution Directive (#define)
2) File Inclusion Directive (#include)
3) Compiler Control Directives (conditional directives)
4) ANSI C directives
MACRO SUBSTITUTION DIRECTIVES: Macro substitution is a process where an
identifier in a program is replaced by a predefined string composed of one or more tokens.
 The preprocessor accomplishes this task under the direction of #define statement. This
statement, usually known as a macro definition
 Syntax: #define identifier string
 Example: #define PI 3.14
There is no space between the # and the word define. Also there should be atleast a single space
between #define, identifier and string. Also, there will be no semi-colon at the end of the
statement.
 There are different forms of macro substitution. The most common are:
1) Simple macro substitution
2) Argumented macro substitution
3) Nested macro substitution
1] Simple macro substitutions: are generally used for declaring constants in a C program. Some
valid examples for simple macro substitution are:
 Example for simple macro: #define PI 3.14 #define size 100
2] Argumented macro substitution: The preprocessor allows us to define more complex and
more useful form of substitutions. The Argumented macro substitution takes the following form:
 Syntax: #define identifier(arg1,arg2…., argn) string
Care should be taken that there is no space between the identifier and the left parentheses.
In the program, the occurrence of a macro with arguments is known as a macro call. When a
macro is called, the preprocessor substitutes the string, replacing the formal parameters with
actual parameters.
 Example for argument macro:
#define CUBE(x) (x*x*x) //Macro definition
volume = CUBE(side) //Macro Call
volume = side*side*side //Execution
3] Nested Macros: We can use one macro inside the definition of another macro. Such macros
are known as nested macros.
 Example for Nested Macros:
#define SQUARE(x) (x*x)
#define CUBE(x) (SQUARE(x)*x)
FILE INCLUSION DIRECTIVES: The external files containing functions or macro
definitions can be linked with our program so that there is no need to write the functions and
macro definitions again.
 This can be achieved by using the #include directive. The syntax for this directive is as
shown below:
#include “filename”
or
#include<filename>
We can use either of the above statements to link our program with other files.
 If the filename is included in double quotes, the file is searched in the local directory. If
the filename is included in angular brackets, then the file is searched in the standard
directories.
COMPILER DIRECTIVES: The following are the compiler control directives used in c
programming:
Directive Purpose
#ifdef Test for a macro definition
#endif Specifies the end of #if
#ifndef Tests whether a macro is not defined
#if Test a compile-time condition
#else Specifies alternative when #if fails
These directives allow the programmer to include the portions of the codes based on the
conditions.
#ifdef and #endif directive:
#ifndef and #else directive: The #ifndef works exactly opposite to that of #ifdef preprocessor
tests whether the identifier has defined substitute text or not.
If identifier is defined then #else block is compiled and executed and the compiler ignores #if
block.
ANSI PREPROCESSOR DIRECTIVES: The ANSI committee has added some more
preprocessor directives to the existing list. They are:
Directive Purpose
#elif Provides alternative test facility
#pragma Specifies compiler instructions
#error
Stops compilation when an error
occurs
#elif directive:”#elif directive”: enables us to establish an “if…else…if” sequence for testing
multiple conditions.
 The syntax is as shown below:
#if expr1
Stmts;
#elif expr2
Stmts;
#elif expr3
Stmts;
#endif
#pragma directive: directive is an implementation oriented directive that allows the user to
specify various instructions to be given to the compiler.
Syntax:
#pragma name
Where name is the name of the pragma we want. For example, under Microsoft C, #pragma
loop_opt(on) causes loop optimization to be performed.
“#error directive”: is used to display user defined message during compilation of the program.
Syntax: #if !defined(identifer)
#error <ERROR MESSAGE>
#endif
Example: #include<stdio.h>
#define B1
void main(){
#if !defined(A)
#error MARCO NOT DEFINED
#else
printf(“macro found”)
#endif
}
 VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru
 VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru

More Related Content

What's hot

Contiguous Memory Allocation-R.D.Sivakumar
Contiguous Memory Allocation-R.D.SivakumarContiguous Memory Allocation-R.D.Sivakumar
Contiguous Memory Allocation-R.D.SivakumarSivakumar R D .
 
Computer Network notes (handwritten) UNIT 1
Computer Network notes (handwritten) UNIT 1Computer Network notes (handwritten) UNIT 1
Computer Network notes (handwritten) UNIT 1NANDINI SHARMA
 
Real Time Operating system (RTOS) - Embedded systems
Real Time Operating system (RTOS) - Embedded systemsReal Time Operating system (RTOS) - Embedded systems
Real Time Operating system (RTOS) - Embedded systemsHariharan Ganesan
 
Asynchronous data transfer
Asynchronous data transferAsynchronous data transfer
Asynchronous data transferpriya Nithya
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEMMansi Tyagi
 
instruction cycle ppt
instruction cycle pptinstruction cycle ppt
instruction cycle pptsheetal singh
 
Operating system concepts (notes)
Operating system concepts (notes)Operating system concepts (notes)
Operating system concepts (notes)Sohaib Danish
 
Register Reference Instructions | Computer Science
Register Reference Instructions | Computer ScienceRegister Reference Instructions | Computer Science
Register Reference Instructions | Computer ScienceTransweb Global Inc
 
Memory allocation (4)
Memory allocation (4)Memory allocation (4)
Memory allocation (4)rockymani
 
Computer organisation -morris mano
Computer organisation  -morris manoComputer organisation  -morris mano
Computer organisation -morris manovishnu murthy
 
Loaders ( system programming )
Loaders ( system programming ) Loaders ( system programming )
Loaders ( system programming ) Adarsh Patel
 

What's hot (20)

Dynamic Memory Allocation in C
Dynamic Memory Allocation in CDynamic Memory Allocation in C
Dynamic Memory Allocation in C
 
Contiguous Memory Allocation-R.D.Sivakumar
Contiguous Memory Allocation-R.D.SivakumarContiguous Memory Allocation-R.D.Sivakumar
Contiguous Memory Allocation-R.D.Sivakumar
 
CS6401 Operating Systems
CS6401 Operating SystemsCS6401 Operating Systems
CS6401 Operating Systems
 
Computer Network notes (handwritten) UNIT 1
Computer Network notes (handwritten) UNIT 1Computer Network notes (handwritten) UNIT 1
Computer Network notes (handwritten) UNIT 1
 
Real Time Operating system (RTOS) - Embedded systems
Real Time Operating system (RTOS) - Embedded systemsReal Time Operating system (RTOS) - Embedded systems
Real Time Operating system (RTOS) - Embedded systems
 
GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORYGE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
 
Asynchronous data transfer
Asynchronous data transferAsynchronous data transfer
Asynchronous data transfer
 
memory hierarchy
memory hierarchymemory hierarchy
memory hierarchy
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
 
Notes of c programming 1st unit BCA I SEM
Notes of c programming  1st unit BCA I SEMNotes of c programming  1st unit BCA I SEM
Notes of c programming 1st unit BCA I SEM
 
instruction cycle ppt
instruction cycle pptinstruction cycle ppt
instruction cycle ppt
 
Paging and segmentation
Paging and segmentationPaging and segmentation
Paging and segmentation
 
Operating system concepts (notes)
Operating system concepts (notes)Operating system concepts (notes)
Operating system concepts (notes)
 
Interrupts
InterruptsInterrupts
Interrupts
 
Register Reference Instructions | Computer Science
Register Reference Instructions | Computer ScienceRegister Reference Instructions | Computer Science
Register Reference Instructions | Computer Science
 
Structure in C
Structure in CStructure in C
Structure in C
 
Memory allocation (4)
Memory allocation (4)Memory allocation (4)
Memory allocation (4)
 
Computer organisation -morris mano
Computer organisation  -morris manoComputer organisation  -morris mano
Computer organisation -morris mano
 
computer Architecture
computer Architecturecomputer Architecture
computer Architecture
 
Loaders ( system programming )
Loaders ( system programming ) Loaders ( system programming )
Loaders ( system programming )
 

Similar to VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru

What is a computer
What is a computerWhat is a computer
What is a computerOfun Emma
 
Computers types
Computers typesComputers types
Computers typesOfun Emma
 
Basic Components of Computer
Basic Components of ComputerBasic Components of Computer
Basic Components of ComputerRajGopalAgrawal
 
Atharva Patil_28_9th lilies_Computer Project2.pptx
Atharva Patil_28_9th lilies_Computer Project2.pptxAtharva Patil_28_9th lilies_Computer Project2.pptx
Atharva Patil_28_9th lilies_Computer Project2.pptxAtharvaPatil48
 
Neetu IT Assignment
Neetu IT AssignmentNeetu IT Assignment
Neetu IT AssignmentNeetu Marwah
 
Computer Science PowerPoint Presentation
Computer Science PowerPoint PresentationComputer Science PowerPoint Presentation
Computer Science PowerPoint PresentationAshna Rajput
 
Advanced Computer Architecture
Advanced Computer ArchitectureAdvanced Computer Architecture
Advanced Computer ArchitectureTodd Turner
 
Information Technology for Managers - Basics
Information Technology for Managers - BasicsInformation Technology for Managers - Basics
Information Technology for Managers - BasicsIsha Joshi
 
The Deal
The DealThe Deal
The Dealadhaval
 
Application of computer in Hospitality
Application of computer in HospitalityApplication of computer in Hospitality
Application of computer in HospitalityPriya Roy
 
Computer concepts- Mohammadali & Tausif
Computer concepts- Mohammadali & TausifComputer concepts- Mohammadali & Tausif
Computer concepts- Mohammadali & Tausiftausif ghodesawar
 
Meeting 1 types of computers ppt
Meeting 1 types of computers pptMeeting 1 types of computers ppt
Meeting 1 types of computers pptjuniato276
 
Tm 1st mod
Tm 1st modTm 1st mod
Tm 1st modRVIM
 

Similar to VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru (20)

What is a computer
What is a computerWhat is a computer
What is a computer
 
Computers types
Computers typesComputers types
Computers types
 
Digital Fluency
Digital FluencyDigital Fluency
Digital Fluency
 
Computers types
Computers typesComputers types
Computers types
 
Basic Components of Computer
Basic Components of ComputerBasic Components of Computer
Basic Components of Computer
 
Atharva Patil_28_9th lilies_Computer Project2.pptx
Atharva Patil_28_9th lilies_Computer Project2.pptxAtharva Patil_28_9th lilies_Computer Project2.pptx
Atharva Patil_28_9th lilies_Computer Project2.pptx
 
Neetu IT Assignment
Neetu IT AssignmentNeetu IT Assignment
Neetu IT Assignment
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
 
Computer Science PowerPoint Presentation
Computer Science PowerPoint PresentationComputer Science PowerPoint Presentation
Computer Science PowerPoint Presentation
 
Advanced Computer Architecture
Advanced Computer ArchitectureAdvanced Computer Architecture
Advanced Computer Architecture
 
Information Technology for Managers - Basics
Information Technology for Managers - BasicsInformation Technology for Managers - Basics
Information Technology for Managers - Basics
 
The Deal
The DealThe Deal
The Deal
 
Day 1
Day   1Day   1
Day 1
 
Application of computer in Hospitality
Application of computer in HospitalityApplication of computer in Hospitality
Application of computer in Hospitality
 
Computer concepts- Mohammadali & Tausif
Computer concepts- Mohammadali & TausifComputer concepts- Mohammadali & Tausif
Computer concepts- Mohammadali & Tausif
 
Meeting 1 types of computers ppt
Meeting 1 types of computers pptMeeting 1 types of computers ppt
Meeting 1 types of computers ppt
 
Classification of computers
Classification of computersClassification of computers
Classification of computers
 
Q1_Module_5_ICT_7.pdf.pdf
Q1_Module_5_ICT_7.pdf.pdfQ1_Module_5_ICT_7.pdf.pdf
Q1_Module_5_ICT_7.pdf.pdf
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Tm 1st mod
Tm 1st modTm 1st mod
Tm 1st mod
 

More from Nithin Kumar,VVCE, Mysuru

VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...Nithin Kumar,VVCE, Mysuru
 
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...Nithin Kumar,VVCE, Mysuru
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
VTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
VTU C-sharp & .net programming notes by Nithin, VVCE, MysuruVTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
VTU C-sharp & .net programming notes by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
VTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
VTU internet of things(IOT) notes by Nithin,VVCE, MysuruVTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
VTU internet of things(IOT) notes by Nithin,VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
Vtu Data Structures Notes CBCS by Nithin, VVCE
Vtu Data Structures Notes CBCS by Nithin, VVCEVtu Data Structures Notes CBCS by Nithin, VVCE
Vtu Data Structures Notes CBCS by Nithin, VVCENithin Kumar,VVCE, Mysuru
 
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCEVTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCENithin Kumar,VVCE, Mysuru
 
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruVtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruNithin Kumar,VVCE, Mysuru
 
VTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
VTU Advanced Algorithms Notes by Nithin, VVCE MysuruVTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
VTU Advanced Algorithms Notes by Nithin, VVCE MysuruNithin Kumar,VVCE, Mysuru
 
VTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
VTU Network management -15cs833 Notes by Nithin, VVCE, MysuruVTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
VTU Network management -15cs833 Notes by Nithin, VVCE, MysuruNithin Kumar,VVCE, Mysuru
 
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruVtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruNithin Kumar,VVCE, Mysuru
 

More from Nithin Kumar,VVCE, Mysuru (13)

VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
 
VTU Data Structures Lab Manual
VTU Data Structures Lab ManualVTU Data Structures Lab Manual
VTU Data Structures Lab Manual
 
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
18CSMP68 VTU Mobile Application Develeopment Lab Manual by Nithin, VVCE, Mysuru
 
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
Vtu research methodology handwritten notes(16phdrm) for PG and PhD by Nithin ...
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
VTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
VTU C-sharp & .net programming notes by Nithin, VVCE, MysuruVTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
VTU C-sharp & .net programming notes by Nithin, VVCE, Mysuru
 
VTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
VTU internet of things(IOT) notes by Nithin,VVCE, MysuruVTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
VTU internet of things(IOT) notes by Nithin,VVCE, Mysuru
 
Vtu Data Structures Notes CBCS by Nithin, VVCE
Vtu Data Structures Notes CBCS by Nithin, VVCEVtu Data Structures Notes CBCS by Nithin, VVCE
Vtu Data Structures Notes CBCS by Nithin, VVCE
 
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCEVTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
VTU Algorithms Notes CBCS (DAA Notes) by Nithin, VVCE
 
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruVtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
 
VTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
VTU Advanced Algorithms Notes by Nithin, VVCE MysuruVTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
VTU Advanced Algorithms Notes by Nithin, VVCE Mysuru
 
VTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
VTU Network management -15cs833 Notes by Nithin, VVCE, MysuruVTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
VTU Network management -15cs833 Notes by Nithin, VVCE, Mysuru
 
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuruVtu Data Mining-15CS651 notes by Nithin vvce,mysuru
Vtu Data Mining-15CS651 notes by Nithin vvce,mysuru
 

Recently uploaded

ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 

Recently uploaded (20)

ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 

VTU C programming(CPS) 18CPS13/23 notes by Nithin,VVCE,Mysuru

  • 1. Module – 1: Introduction to computers & c-programming COMPUTER: A computer is a machine that accepts data as input, processes that data using programs, and outputs the processed data as information. Many computers can store and retrieve information using hard drives. Computers can be connected together to form networks, allowing connected computers to communicate with each other. GENERATIONS OF COMPUTER: There are six generations of computer system are present as follows: a) Zeroth Generation: Man used his fingers, ropes, beads, bones, pebbles and other objects for counting. Electricity was not yet invented. b) First Generation(Vacuum Tubes): Used vacuum tubes for computation, magnetic drums for memory, Took up lot of space, Very expensive , consumed great deal of electricity, generated a lot of heat, which was often the cause of malfunctions. Input was based on punched cards and output was obtained on paper. c) Second Generation(Transistors): Transistors replaced vacuum tubes which are smaller, faster, cheaper, more energy-efficient and more reliable than their first-generation predecessors. Still relied on punched cards for input and printouts for output. Generate less heat and consumed less electricity as compared to First generation computers. Still very costly. Support assembly language and high level language such as FORTRAN & COBOL. d) Third Generation(Integrated Circuits): Integrated circuit was used such as Transistors, resistors, capacitors and diodes were integrated onto a single chip. Computers of this generation are Smaller, cheaper and energy-efficient & users interacted through keyboards and monitors. Memory capacity increased and magnetic hard disk was used but Still costly A.C. needed. Support high-level language such as C, C++ and Java. e) Fourth Generation(Microprocessor): Microprocessor were used, What in the first generation filled an entire room could now fit in the palm of the hand. As these small computers became more powerful, they could be linked together to form networks, which eventually led to the development of the Internet. Fourth generation computers also saw the
  • 2. development of GUIs, the mouse and Hand held devices. Finally Computers became easily available f) Fifth Generation(Artificial Intelligence): based on artificial intelligence, are still in development, though there are some applications, such as voice recognition, that are being used today. The goal of fifth-generation computing is to develop devices that respond to natural language input and are capable of learning and self-organization. TYPES OF COMPUTERS: Apart from being classified by generations, computers can also be categorized by their size: a) SUPERCOMPUTERS: These are the huge machines having the most powerful and fastest processors. A supercomputer uses multiple CPUs for parallel data processing, which means portions of the same program are handled independently by multiple processors. Super computers are too powerful to be used for transaction processing. They are employed in areas that require enormous numerical computations like weather forecasting, analysis of geological data, nuclear stimulation, and space exploration. The cost of supercomputers are too high, they are mainly used by government agencies. b) MAIN FRAME COMPUTERS: Before the advent of supercomputers, mainframe computers were the largest computers available. These are the multiuser machines that can support hundreds or thousands of users using the feature of “time sharing” supported by systems like Linux. Today mainframes are employed to handle online transactions(like stock exchange transactions), The capability to handle large amounts of data makes the mainframe suitable for use in government, banks, financial institutions and large corporations. c) MINICOMPUTERS: Minicomputers or midrange computers can be considered as downsized mainframes since they have essential features of mainframes. Minicomputers can serve hundreds of users and are small enough to partially occupy a room. But they are not affordable enough to be used in the home. Minicomputers are used in smaller organizations or a department of a large one. d) MICROCOMPUTERS: The microcomputer or personal computers(PC) is a late entrant to the computer family. This was introduced by Apple and later endorsed by IBM, this computer is a single-user machine powered by a single chip microprocessor. They are used both in the standalone mode (at home) and in network (in office). They are used both in the standalone mode (at home) and in network (in office). All PCs are multimedia ready. They can handle images, audio and video files. e) SMART PHONES AND EMBEDDED COMPUTERS: A smartphone is a general purpose computer that is also capable of making phone calls. It also supports gigabytes of main memory but doesn‟t have a hard disk for secondary storage. This requirement is met by flash memory. Smartphones today run a well-developed operating system (Android or iOS) and can run a wide range of applications. Applications are written in a high-level language like
  • 3. Objective C for the iPhone and Java for Android phones. Embedded devices is small computer like system that is part of a larger system which consists of CPU, non-volatile memory, and input and output facilities.we use such devices in cars, washing machine, MP3 players and cameras. BITS, BYTES AND WORDS: In everyday life, we use decimal system for computing where digit can have ten values. A computer understands only two states:  0  1 A digit that can have only two states or values is called as binary digit, which is abbreviated as “bit”. All binary numbers are represented by combining these 0s and 1s. Example: The number 13 is represented as 1101 in the binary system. The name “byte” was coined to represent eight bits. The byte is the standard unit of measurement of computer memory, data storage and transmission speed. A similar relationship exists for bits also. So the speed of network expressed as 1Mbps(megabits per second) is same as 1000Kbps. Even though computer memory is represented in bytes, the CPU handles memory data in larger units, called “words” , where a word is usually an even multiple of bytes (two bytes, four bytes etc.,). When we refer to a computer as 32-bit (4 bytes) machine, we mean the size of the size of its word is 32 bits. ARCHITECTURE OF COMPUTER (Von Neumann Architecture/Block Diagram of Computer): Computer is having three basic units such as  The Central Processing Unit (CPU)  The Main Memory Unit  The Input/Output Device The block diagram of Computer Architecture is as shown below:
  • 4. a) CPU: It comprises the following components:  Arithmetic and Logic Unit (ALU) - It carries out all arithmetic tasks. ALU also compares two numbers and performs “Boolean” operations such as AND, OR, NOT on them.  Control Unit (CU) - does not perform any computational tasks. Using signals, the CU controls the way the data is moved between moved between the various components of the computer.  Special-purpose registers - CPU uses a few high-speed “registers”, form of memory to store the current instruction and its data. b) PRIMARY MEMORY: Memory is one of the essential resource used by the computer and its users. We categorize memory into two types:  Primary memory – All of these memory units are housed on the motherboard of the PC such as RAM, ROM & Cache memory. Except ROM, all the memory types are volatile i.e., they loose the contents when power given to computer is taken back.  Secondary memory - Computer system also supports secondary memory which is also called as secondary storage or auxiliary memory. These devices are slower than primary memory but they have larger capacities. Some of the examples include Hard disc, Pen drive, CD, DVD etc. c) INPUT/OUTPUT DEVICES: We interact with the operating system for performing the daily chores like editing, copying and deleting files. Some of the common input devices are keyboard, Mouse & Scanners etc.
  • 5. The term output generally refers to the information that can be seen or heard. Some of the common output devices are Monitor, Printer & Speakers etc. PORTS AND CONNECTORS: Devices like printers and scanners connect to a computer through docking points called ports. All ports are connected to mother board but are visible from outside. They are shaped differently, so it is impossible to use a wrong connector for a port. • Serial Port: Once used by keyboard, mice and modems serial ports are offered in 9-pins and 25-pins. • Parallel Port: It is commonly used by printers if they are not using the USB port and comes with 25-pins. • Video Graphics Array (VGA): This 15-pin port allows transfer of analog (continuous) video data to the monitor. • RJ45 port: This is used by the Ethernet network. • PS/2 port: This port has replaced the serial port for connecting the keyboard and mouse. It has 6 pins but occurs as a pair in two different colors. • High Definition Media Interface: This is now the industry standard for transferring audio and video data between computers and HDTVs, projectors and home theatres. COMPUTERS IN A NETWORK: Most organisations, large or small no longer have standalone systems. Today, computers cooperate with each other by being connected to a network. The computer (node) that offers these services would need to be more powerful than the computer it serves. That‟s how “servers” came to existence as the central node in the network. Servers acts as the backbone of the largest network of all- the internet. Network topology is the arrangement of the elements (links, nodes, etc.) of a communication network. There are a number of ways of topologies of connecting computers, each having its own merits and demerits:
  • 6.  Bus topology uses single cable as a bus to which all computers are connected. The failure of one node doesn‟t disrupt communication between the remaining nodes.  Star topology uses central hub to which all nodes are connected. Due to network traffic through the hub, the entire network fails if the hub fails to work. New nodes can be added without disrupting the service.  Ring topology uses closed loop without using a hub. For unidirectional rings, failure of one node causes the network to shut down.  Mesh topology uses nodes connected to each other, offering a choice of multiple routes for data to travel. When node breaks down, the packet simply changes its route. This is the most expensive of the topologies and found mainly in corporate networks. Networks are classified based on their size. The three most common types are:  Local Area Network - LAN is used by small organizations where the area is confined to one building. They generally use Ethernet technology. Wireless LANs (WLAN) also known as Wi-Fi (Wireless Fidelity) has become popular. Standard Ethernet speeds are ruling at 100 Mbps. Wi-Fi networks using 802.11g operate at round 20 Mbps.  Wide Area Network - WANs extend the range used by LANs. It can connect a number of cities or establishments in the same city. Because of the large distances, optic fiber cables, leased telephone lines and radio transmission are used to connect WAN nodes  Metropolitan Area Network (MAN) - This type is sandwiched between a LAN and WAN. A MAN is employed for interconnecting in the same city. The Internet (also called net) is the largest wide area network on the planet. It‟s a collection of over 50,000 networks that run a special set of network protocols called TCP/IP. Connecting computers in a network is require additional devices that are not part of the computer‟s configuration. Some of the devices are:  Network Interface card (NIC) - Network Interface Card (NIC) or network card that is presented in the computer. Most of the computers use Ethernet technology, this card is often called as Ethernet card.  Hub - accepts network data from a computer and simply broadcasts the data to all nodes.  Switch - contains a table of MAC addresses of the connected devices. A switch is efficient and is able to maintain the speed of the network.  Bridge - maintains a table of MAC addresses of all machines in the segments connected to it. It connects two networks using the same protocol (say, Ethernet).  Router - connects two similar or dissimilar networks which may be separated by long distances. It is part of both networks and thus has two addresses.
  • 7. SOFTWARE BASICS: Software is a collection of code that drives the computer to perform related task. Comprises one or more programs supported by libraries & configuration files. Programs in software use languages like C, C++, java etc. Computer software can be broadly classified into two types:  System Software - They are run by computer to manage the hardware connected to it. User will not have much control over it. Some good examples are OS, Compilers, Device Drivers etc.  Application Software - They are used for specific application. Some good examples are Games, Social media, Anti-virus etc. BASIC STRUCTURE OF C-PROGRAM  Documentation section - The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later.  Link section - The link section provides instructions to the compiler to link functions from the system library.  Definition section - The definition section defines all symbolic constants.  Global declaration section - There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global
  • 8. declaration section that is outside of all the functions. This section also declares all the user-defined functions.  main () function section - Every C program must have one main function section. This section contains two parts; declaration part and executable part. The declaration part declares all the variables used in the executable part. There must be at least one statement in the executable part. These two parts must appear between the opening and closing braces. The program execution begins at the opening brace and ends at the closing brace. The closing brace of the main function is the logical end of the program. All statements in the declaration and executable part end with a semicolon. C-TOKENS: The characters that can be used to form words, numbers & expressions depend upon the computer on which the program is run. The characters are grouped into the following categories: Letters(A…Z, a….z), Digits (0…9), Special characters(%,&,:,;,*,!,#,<,>,?,=,”,/,) & Whitespaces. The smallest individual units in C program are known as “C Tokens”.  Keywords - Every word used in a C program is classified as either a keyword or as an identifier. A keyword in C is a reserved word which has a specific meaning. Keywords in C cannot be used as identifiers. Keywords serve as the basic building blocks for program statements Keywords in C are always in lowercase. ANSI C supports 32 keywords which are listed below:
  • 9.  Identifiers - refer to the names of variables, functions and arrays. These are user- defined names and consist of sequence of letters and digits, with a letter as a first character. Both uppercase and lowercase letters can be used, although lowercase letters are generally used. The underscore character is also permitted in identifiers. There certain rules while writing identifiers. They are as follows: 1) First character must be an alphabet or underscore. 2) Must consist of only letters, digits or underscore. 3) Only first 31 characters are significant. 4) Cannot use a keyword. 5) Must not contain white space.  Constants in C- Constants are fixed values, which do not change during the execution of a program. C supports several types of constants, which are as shown below: “Integer Constant” refers to a sequence of digits. Generally in programs, the number systems used are: decimal, octal and hexadecimal. “Real Constants” integer numbers are not sufficient to represent quantities that vary continuously, such as distances, height, prices etc. These quantities are represented by numbers containing fractional parts like 25.234. Such numbers are called as real or floating point constants.
  • 10.  Strings – “Single Character Constants” or character constant contains a single character enclosed in between single quotes. Some valid examples of character constants are: „f‟, „A‟, „/‟, ‟;‟, „ „, „4‟. The character constant „4‟ is not equal to the number 4. “String Literals or String Constants” A sequence of characters that are enclosed between double quotes is known as a string literal or string constant. The characters in a string literal can be either letters, digits or special symbols or white spaces. Some valid examples of string constants are: “hai”, “hEllO”, “hi5”, “Wel come” etc. VARIABLES IN C: A variable is a placeholder for holding a value in the main memory (RAM). As the name implies, the value in the variable can change at any point of execution of the program. For using variables in our programs, there are essentially two steps: 1) Declare the variable 2) Initialize the variable  Before using a variable in the program, we have to declare the variable. The syntax for declaring a variable in a program is as shown below: datatype variable-name;  The “type” in the above syntax represents the data type. The “variable-name” is the identifier. There are certain rules that must be followed while writing the variable name.  Rules for Variables Name –  A variable name must always start with an alphabet (letter) or an underscore ( _ ).  The variable name must not be more than 31 characters. The suggested length of a variable name is 8 characters.  C is case sensitive. So, the variable name “average” is different from “AVERAGE”.  Keywords must not be used for declaring variables.  White spaces are not allowed within the variable name.  Initializing a Variable – After declaring the variable, we can assign a value to the variable. This process of assigning a value to the variable is known as initialization. Syntax for initializing a variable is as shown below: variable-name = value; The value we assign to the variable depends on the data type of the variable. int a; a=10; The declaration and initialization can be combined into a single line as shown below: int a=10;
  • 11. Data Types in C: A data type specifies the type of value that we use in our programs. A data type is generally specified when declaring variables, arrays, functions etc. In ANSI C, the data types are divided into three categories. They are: 1) Primitive or Fundamental data types 2) User-defined data types 3) Derived data types  Primitive or Fundamental data types - The primitive data types in ANSI C are as shown in the below diagram:
  • 12.  User-Defined data types - ANSI C allows the users to define identifiers as their own data types, based on the already existing primitive or fundamental data types. This concept is known as “type definition” and the data types thus created are known as user-defined data types. We can create user-defined data types in two ways: 1) By using the “typedef” keyword typedef int rollno; rollno r1, r2; 2) By using the “enum” keyword enum identifier{value1, value2… valuen}; enum days{sun,mon,….sat}  Derived data types - The data types which are created using the already existing primitive or fundamental types are known as derived data types. Examples of derived data types in C are: Arrays, Functions, Structures, Unions & Pointers. Defining Constants in C: As the name suggests the name constants is given to such variables or values in C programming language which cannot be modified once they are defined. There can be any types of constants like integer, float, octal, hexadecimal, character constants etc. In C program we can define constants in two ways as shown below: 1) Using #define preprocessor directive 2) Using a const keyword  #define preprocessor directive - This directive is used to declare constant variable or any value. We can use this to declare a constant as shown below: #define identifierName value identifierName: It is the name given to constant. value: This refers to any value assigned to identifierName. Example: #define PI 3.14 #define CLASS_SIZE 62 #define charVal „G‟  const keyword - Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword. const datatype identifierName=value;
  • 13. datatype: type of data stored in place of value. identifierName: It is the name given to constant. value: This refers to any value assigned to identifierName. Example: const int intVal = 10; const float floatVal = 4.14; Declaring a variable as volatile: By declaring a variable as volatile, its value may be changed at any time by some external source. ex: volatile int date; The value of data may be altered by some external factors. When we declare a variable as volatile, the compiler will examine the value of the variable each time it is encountered to see any external alteration has changed the value. Overflow and Underflow: Problem of data overflow and underflow occurs when the value of a variable is either too big or too small for the type to hold. The largest value that a variable can hold also depends on the machine. An overflow normally results in the largest value, whereas an underflow results in zero. C does not provide any warning or indication of integer overflow. It simply gives incorrect results. Operators & Expressions: An operator is a symbol that tells a computer to perform certain mathematical or logical operations. Operators are used in programs to manipulate data and variables. Generally the usage of an operator is as shown below: Operand1 Op Operand2 Operand1 and operand2 can be either data or variables or expressions. Op is the operator. In C, based on the number of operands on which an operator can operate, the operators are divided into three types namely: 1) Unary 2) Binary 3) Ternary Different Types of Operators: In C, based on the functionality, operators are classified into 8 categories. They are: 1) Arithmetic Operators (+,-,*,/,%) 2) Relational Operators(<,>,==,!=,>=,<=)
  • 14. 3 )Logical Operators(&&,||,!) 4) Assignment Operators(=,+=,-=,*=,/=,%=) 5) Increment and Decrement Operators (++,--) 6) Conditional Operators(?) 7) Bitwise Operators(&,|,^,~,<<,>>) 8) Special Operators(, & sizeof)  Arithmetic Operators - C provides all the basic arithmetic operators as shown below. The arithmetic operators can operate on any built-in data type in C.  Relational Operators - In C, whenever there is a need to compare two values and make a decision based on the outcome of the comparison, we use relational operators. The relational operators are generally used in decision making statements like if, else if and in looping statements like for, while, do while etc. Relational operators always evaluates to 0 (false) or 1 (true).  Logical Operators - The relational operators are used to compare at most two values i.e. testing one condition. To test more than one condition, we use logical operators along with
  • 15. relational operators. The logical operators always evaluates to either 0 or 1 like relational operators.  Assignment Operators - The assignment operators are used to assign value of an expression to a variable. The general assignment operator is = (equal). In C, there are some special assignment operators known as shorthand operators. The syntax of shorthand operators is as shown below: var op=exp;  Increment/Decrement Operators - The increment and decrement operators provided by C are used to increment or decrement the operand by a value of one. Both the increment and decrement operators are unary operators. There are two variations in increment/decrement operators 1) pre-increment/decrement(++var/--var) 2) post-increment/decrement(var++/var--) When pre increment is applied, the value of the variable is incremented by one first and then that value is used for evaluation of the expression. When post increment is applied, the value of the variable is used in the evaluation of the expression and after the expression is evaluated, the value of the variable is incremented by a value of one.  Conditional Operator - The conditional operator “? :” in C, is a ternary operator, which operates on three operands. This operator is used to construct conditional expressions of the form: exp1?exp2:exp3;
  • 16. In the above syntax, exp1, exp2 and exp3 refer to expressions.It evaluates the exp1 first and then based on the result of the exp1 it evaluates either exp2 or exp3. If the result of exp1 is true or non-zero, then exp2 is executed or if the result of exp1 is false or zero, then exp3 is executed.  Bitwise Operator’s - C supports a set of operators which operate at bit-level. These operators are known as bitwise operators. The bitwise operators are used for testing a bit, setting a bit, complementing a bit or for shifting the bits to left or right. The bitwise operators available in C are as shown below:  Special Operator’s - C supports some special operators such as comma “,” operator, sizeof operator, address “&” operator, pointer operator “*” and some others. The comma “,” operator is used to combine multiple related expressions together. A comma separated list of expressions is evaluated from left to right and the value of the right most expression is the value of the combined expression. The sizeof operator computes the size of an expression or variable or constant or a data type. The general syntax of sizeof operator is as shown below: sizeof(operand); The operand can be either a value or variable or data type or an expression. Expression evaluation in C: Expressions are evaluated based on operator precedence and associativity rules when an expression contains more than one operator. Every C operator has a precedence (priority) associated with it. This precedence is used to determine how an expression involving more than one operator is evaluated. The operators at the higher level of precedence are evaluated first. The operators in the same level of precedence are evaluated from left to right or from right to left, based on the associativity property of an operator. In the below table we can look at the precedence levels of operators and also the associativity of the operators within the same level. Rank 0 indicates the lowest precedence and Rank 14 indicates highest precedence.
  • 17. Type casting/ conversion: Typecasting is converting one data type into another one. It is also called as data conversion or type conversion. 'C' programming provides two types of type casting operations: 1) Implicit type casting 2) Explicit type casting  Implicit type casting – C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance.  Explicit type casting - There are some scenarios in which we may have to force type conversion. Suppose we have a variable div that stores the division of two operands which are declared as an int data type. (Type_name)expression; Examples: x = (int)7.5 a = (int)21.3/(int)4.5 b = (double)sum/n y = (int)(a+b) z = (int)a + b
  • 18. Type casting or conversion hierarchy: Mathematical functions:
  • 19. Example Programs to be prepared from this module: C Program to compute area of a circle #include<stdio.h> void main() { float radius, area; printf("Enter the radius of Circle : n"); scanf("%d", &radius); area = 3.14 * radius * radius; printf("Area of Circle : %f", area); } C Program to compute simple interest #include<stdio.h> void main() { int p,n,r,si; clrscr(); printf("Enter Principle, Rate of interest & Time :n"); scanf("%d%d%d",&p,&r,&n); si=(p*n*r)/100; printf("Simple Interest is :%d",si); }
  • 20. Module – 2:Branching & Looping Statements INPUT-OUTPUT FUNCTIONS: There are two types of a console I/O functions: 1) Formatted input-output function 2) Unformatted input-output function The major difference is that formatted function allows us to format the input from the keyboard and the output to be displayed on the screen. 1) Unformatted Input-Output Functions: Unformatted input and output functions are only work with character data type. Unformatted input and output functions do not require any format specifiers. Because they only work with character data type.  getchar() function is used to get/read a character from keyboard input. var_name = getchar();  putchar() function is used to write a character on standard output/screen. putchar(var_name); Example: char x; x = getchar(); putchar(x);  gets() function can read a full string even blank spaces presents in a string. But, the scanf() function leave a string after blank space space is detected. The gets() function is used to get any string from the user. gets(var_name);
  • 21.  puts() function prints the charater array or string on the console. The puts() function is similar to printf() function, but we cannot print other than characters using puts() function. puts(var_name); Example: char c[25]; printf("Enter your Name : "); gets(c); puts(c); 2) Formatted Input-Output Functions: In C programming language the output is printed using printf() statement. There are two simple forms of printf() statement:  That has a literal string, a sequence of characters within quotation marks. Syntax: printf(“string”); Example: printf(“GOD”);  That has literal string, conversion specifier and any or all of the following: variables, constant and expressions values to be printed. Syntax: printf (“format specifier / format string”,list of variables); Example: printf(“%d%f”,x,y); C provides scanf function in the stdio.h header file. Using this function we can read values from the keyboard and assign the values to variables. The syntax of scanf function is as shown below: scanf(“control string”,&var1,&var2……) The control string specifies the type of value to read from the keyboard and the ampersand symbol & is an operator to specify the address the variable(s). Example: scanf(“%d %f %d”, &a, &b, &c); scanf(“%c”,&h); scanf(“%s”, name); scanf(“%d”,&a[i]);
  • 22. SELECTION OR BRANCHING STATEMENTS: The C statements that transfer the control from one place to other place in the program with or without any condition are called branching or selection statements. The selection / branching statements can be classified into two categories: 1] Conditional Control /Branch Statements: Conditional branching statements that alter the sequence of execution of the program based on some condition are called Conditional branching statements/ selection statements /decision statements. Conditional Control /Branch Statements are as follows: simple if (single selection), if-else (two way selection), Nested if (multiple if statements), else –if ladder (multi-way selection), switch ( multi-way selection). 2] Unconditional Control /Branch Statement: The statements that alter the sequence of execution of the program based on some uncondition are called Unconditional branching statement. Unconditional Control /Branch Statements are as follows: Goto Statement, break Statement, continue Statement and return Statement. CONDITIONAL BRANCHING STATEMENTS: a) If Statement(Simple If): : It is basically a two way decision statement it is used in conjunction with an expression. It is used to execute a set of statements if the condition is true. If the condition is false it skips executing those set of statements. The syntax and flow chart of if statement is as illustrated below: Example: Program to determine whether a person is eligible to vote using if.
  • 23. #include<stdio.h> void main() { int age; printf(“ Enter the age :”); scanf(“%d”,&age); if(age>=18) { printf(“You are eligible to vote”); } } b) If-else Statement: : It is an extension of if statement .It is used to execute any one set of two set of statements at a time. If condition is true it executes one set of statements otherwise it executes another set of statements. The syntax and flow chart of if-else statement is as illustrated below: Example: Program to determine whether a person is eligible to vote using if-else statement. #include<stdio.h> void main() {
  • 24. int age; printf("Enter the age"); scanf("%d",&age); if(age>=18) { printf("You are eligible to vote"); } else { printf("not eligible"); } } c) Nested If-else Statement: : When a series of decisions are involved we may have to use more than one if else statement in nested form. The nested if else statements are multi decision statements which consist of if else control statement within another if or else control statement. The syntax and flow chart of nested if-else statement is as illustrated below: Example: Program to find the largest of three numbers using Nested if else statement
  • 25. #include<stdio.h> void main() { int a,b,c ; printf("Enter the values of a,b and cn"); scanf("%d %d %d",&a,&b,&c); if (a>b) { if (a>c) printf(" %d is largest n", a); else printf("%d is largest n",c); } else { if(b>c) printf(" %d is largest n",b); else printf("%d is largest n",c); } } d) If-else ladder (Multi-way Selection): In addition to two-way selection, most programming languages provide another selection concept known as multi way selection. Multi-way selection chooses among several alternatives. When an action has to be performed based on many decisions, then this Statement is used when more than one if-else statements are used in a sequence, it is called as if-else ladder.  Syntax of if-else ladder: if( condition-1) statement-1;
  • 26. else if( condition-2) statement-2; else if( Condition-3) statement-3; else if( condition n) statement-n; else default-statement; Statement-x;  Disadvantage: difficult to understand and modify when problem is big, which can be overcome by using switch Statement. Example: Program to print the grade obtained by the student based on the given table using else- if ladder. #include<stdio.h> void main() { int marks; printf("Enter the marks n"); scanf("%d",&marks); if(marks>=0 && marks<=39) printf("Grade Fn"); else if (marks>=40 && marks<=49) printf("Grade En");
  • 27. else if (marks>=50 && marks<=59) printf("Grade Dn"); else if (marks>=60 && marks<=69) printf(" Grade Cn"); else if(marks>=70 && marks<=79) printf("Grade Bn"); else if (marks>=80 && marks<=89) printf("Grade An"); else if (marks>=90 && marks<=100) printf("Outstandingn"); else printf("Invalid Entry n"); } e) Switch Statement (Multi-way Selection): It is a multi-way decision making control statement used to make a selection between many alternatives. It is also known as switch case break and default statement.  Syntax of Switch Statement: switch (choice/expression) { case value1:block1; break; case value2: block2; break; case value n: blockn; break; default : default_block ; } next Statement;
  • 28. The value of choice or expression is always an integer value/Character. If the value of choice or expression is 1 then block1 statements will get executed. After executing the respective block the control comes outside the switch statement because of the break statement. If no case values matches with the value of the choice, then the default block will get executed before exiting switch statement.  Switch Statement Rules: 1) A switch statement begins with the switch keyword that followed by a value expression in the parenthesis( ). 2) It is a combination of multiple case labels that must be separated by the break statement. 3) Every case label contains a constant value that is matched against the value, which is specified in the switch expression. 4) If the value is matched, the statements of that case label are executed. 5) In addition, we can specify the default label, which is executed when the value specified in the switch expression, does not match with the given case labels. Example: Program to simulate simple calculator using switch statement #include<stdio.h> void main() { float a,b,res; char op; printf("Enter an Expressionn"); scanf("%g %c %g",&a,&op,&b); switch(op) { case '+' : res=a+b; printf("%g %c %g = %g n",a,op,b,res); break; case '-' : res=a-b; printf("%g %c %g = %g n",a,op,b,res); break; case '*' : res=a*b; printf("%g %c %g = %g n",a,op,b,res); break; case '/' : if(b==0) { printf("Arthimetic Exception: Cannot Divide a number by 0n"); return; } else { res=a/b; printf("%g %c %g = %g n",a,op,b,res); } break; case '%' : res= (int)a % (int)b;
  • 29. printf("%g %c %g = %g n",a,op,b,res); break; default : printf("Invaild operatorn"); break; } } UNCONDITIONAL BRANCHING STATEMENTS: The unconditional branching statements transfer the control from one statement to another statement in the program without any conditions. a) Goto Statement: This statement is used to transfer the control from one point to another point anywhere in the program. The goto requires a label in order to identify the place where the branch is to be made.  The general forms of goto statement:  Example: #include<stdio.h> void main() { int a=1; SHOW: if(a>10) { printf("%d",a); a+=2; } goto SHOW; } }
  • 30. b) Break Statement: The break statement is used to break any type of loop as well as switch statement. Breaking a loop means terminating the loop.  The general forms of break statement: break;  Example: switch(opr) { case '+': printf("Sum : %f",(a + b)); break; } control is transferred to the end of block c) Continue Statement: The continue statement is used to transfer the control to the beginning of a statement block in a loop. In other words, a break statement breaks the entire loop, but a continue statement breaks the current iteration. The continue statement breaks the current execution of a loop condition and then continue the loop with next condition.  The general forms of continue statement: continue;  Example: #include<stdio.h> int main() { int i=1; //starting a loop from 1 to 10 for(i=1;i<=10;i++){ if(i==5) { continue; } printf("%d n",i); } //end of for loop
  • 31. return 0; } d) Return Statement: It is used to return the control to the calling function with/without a value. For example, if a function is not returning any value, use the return keyword return; If a function is returning a value, then return value;  Example: int sumDigits() { int sum = 0; int digit; for(digit = 0; digit <= 9; digit++) { sum = sum + digit; } return sum; //Returning value & control } CONDITIONAL BRANCHING STATEMENTS: The statement which is used to repeat a set of statements repeatedly for a given number of times or until a given condition is satisfied is called as looping statements. The set or block of statements used for looping is called loop.  Way of Looping: 1) Entry Controlled Loop or pretest loop or top test loop 2) Exit Controlled Loop or posttest loop
  • 32.  The C Language supports the following three looping operations: 1) The while statement 2) The do while statement 3) The for statement a) While Loop/Statement (Entry Controlled/Pretest loop): The while statement is the pretest loop. It uses an expression to control the loop. Since it is a pretest loop, it tests the expressions before every iterations of the loop. The syntax and flow chart of While loop is as illustrated below: Example: Program to find the sum of n natural numbers using while loop #include<stdio.h> void main() { int i,n,sum=0;
  • 33. printf("Enter the value of nn"); scanf("%d",&n); i=0; while(i<=n) { sum = sum + i; i++; } printf("The sum of natural numbers = %d n",sum); } b) Do-While Loop/Statemen(Exit Controlled Loop/Post-test): It is an exit controlled loop. It is also known as posttest or bottom test looping statement. The syntax and flow chart of Do-While looping statement is as illustrated below:
  • 34. Example: Program to find the sum of n natural numbers using do while #include<stdio.h> void main() { int i,n,sum=0; printf("Enter the value of nn"); scanf("%d",&n); i=0; do { sum = sum + i; i++; } while(i<=n); printf("The sum of natural numbers = %d n",sum); }  Differences between while & do-while looping statements
  • 35. c) For Loop/Statement(Entry Controlled/Pre-test loop): The for statement is a pretest loop that uses three expressions. Syntax: for (initialization ; test condition ; increment/decrement) { body of the loop; } The first expression contains any initialization statements, the second contains the limit-test expression, and the third contains the updating expression. 1) The initialization set the initial value of the loop control variable. 2) The test condition test the value of the loop control variable. 3) The increment/decrement update the loop control variable. : Example: Program to print N Natural Numbers #include<stdio.h> void main() { int i, N; printf(“Enter the value of N n”); scanf(“%d”,&N); for ( i=0 ; i<=N ; i++) { printf(“%dn”,i); } }  Nested for-loop: Nested loops consist of an outer loop with one or more inner loops. for (i=1;i<=100;i++) {
  • 36. for(j=1;j<=50;j++) { … } } The above loop will run for 100*50 iterations. PASCAL TRIANGLE: Pascal Triangle is a Triangle form which, each number is the sum of immediate top row nearby numbers. The Value of edge is always 1.  C Program to print pascal triangle #include <stdio.h> int main() { int rows, cal = 1, space, i, j; printf("Enter number of rows: "); //enter number of rows for generating the pascal triangle scanf("%d",&rows); for(i=0; i<rows; i++) // outer loop for displaying rows { for(space=1; space <= rows-i; space++) // space printf(" "); for(j=0; j <= i; j++) // inner loop for displaying the pascal triangle of numbers { if (j==0 || i==0) // either outer loop value or inner-loop value is "0 " it prints 1 cal = 1; else cal = cal*(i-j+1)/j; //calculate the coefficient
  • 37. printf("%d", cal); } printf("n"); } return 0; } Computing binomial-coefficient: binomial coefficient is the number of ways of picking unordered outcomes from possibilities, also known as a combination or combinatorial number.  C Program to print binomial-coefficients #include <stdio.h> #define MAX 10 void main() { int n, a, bi_nom; n=0; do { a=0; bi_nom=1; while(a<=n) { If(a==0||n==0) { printf(“%d”, bi_nom); } else { bi_nom = bi_nom * (n-a+1)/a; print(“%d”, bi_nom);
  • 38. } a=a+1; } printf(“n”); n=n+1; } while(n<=MAX); } EXAMPLE PROGRAMS TO BE PREPARED FROM THIS MODULE:  C Program to compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages. #include<stdio.h> #include<math.h> void main( ) { float a,b,c,disc,root1,root2,real,imag; printf("Enter a,b,c values n"); scanf("%f%f%f",&a,&b,&c); disc=(b*b)-(4*a*c); if((a==0) && (b==0)) { printf("Invalid co-efficients n"); } else if(a==0) { printf("Linear equation n"); root1=-c/b; printf("Root=%fn",root1); } else if(disc==0) { printf("The roots are Real and Equal n"); root1=-b/(2*a); root2=-b/(2*a); printf("Root1=%f nRoot2=%fn",root1,root2); } else if(disc>0) { printf("The roots are Real and distinct n"); root1=(-b+sqrt(disc))/(2*a); root2=(-b-sqrt(disc))/(2*a); printf("Root1=%fnRoot2=%fn",root1,root2);
  • 39. } else { printf ("The roots are Real and Imaginary n"); real=-b/(2*a); imag=sqrt(fabs(disc))/(2*a); printf ("Root1=%f + i %f n”, real, imag); printf ("Root2=%f - i %f n”, real, imag); } }  C program to find the reverse of a positive integer and check for palindrome or not. #include<stdio.h> void main() { long int temp,rev=0,i,num,remainder; printf("Enter the number n"); scanf("%ld",&num); temp=num; while(num!=0) { remainder=num%10; num=num/10; rev=rev*10+remainder; } printf ("The reverse of the number is %ldn”, rev); if(rev==temp) printf ("%ld is a palindrome n”, temp); else printf ("%ld is not a palindrome n”, temp); }  An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per unit. All users are charged a minimum of Rs. 100 as meter charge. If the total amount is more than Rs 400, then an additional surcharge of 15% of total amount is charged. Write a program to read the name of the user, number of units consumed and print out the charges. #include<stdio.h> #include<string.h> void main() { char name[25]; int units;
  • 40. float charges=0.0; printf("Enter Customer Name and Number of Units:n"); scanf("%s %d",name,&units); if(units<=0) { printf("Invalid Units,Please enter valid unitsn"); return; } else if(units>=0 && units<=200) charges= 100+ 0.80* units; else if(units>201 && units<=300) charges = 100 + 160+ 0.90 * (units-200); else if(units>300) charges= 100 + 250+1.0 * (units-300); printf("Customer Name=%sn",name); if(charges>400) { charges=charges + 0.15*charges; printf("Total Charges=%fn",charges); } else printf("Total Charges=%fn",charges); }
  • 41. Module – 3:Arrays & Strings ARRAYS: “An array is a sequential collection/group of homogeneous (same type) elements which are referred by the same name” The type refers to the data types like int, char, float etc. All the elements/values in the array are of the same type (data type). We cannot store values of different data types in the same array. It is normal in programming to work with a list of values or a group of values at once. For such purposes, variables cannot be used. So, C language provides the construct array for holding multiple values at once. TYPES OF ARRAYS: 1) One-dimensional Arrays: To maintain a list of values. 2) Multidimensional Arrays: To maintain a table of values. ONE-DIMENSIONAL ARRAYS(1-D Array): For maintaining a list of items in C, we can declare an array with a single subscript (index). Such arrays with only a single subscript are known as “one dimensional arrays”.  Common uses of one dimensional arrays are: 1) To maintain a list of numbers. 2) To maintain the list of marks. 3) To maintain a list of student names etc. a) One-dimensional Array Declaration: For using arrays in C programs, just like we are declaring variables before using them, we should declare arrays before using them. Syntax: for declaring a 1-D Array is shown below: type arrayName [Size];
  • 42. Example: int a[10]; In the above example ‟a’ is an integer array, which can hold 10 integer values. b) One-dimensional Array Initialization: Initialization means assigning values. To assign values to the elements in the array. Generally, there are two types of initializing an array: 1) Static Initialization (at compile time). 2) Dynamic Initialization (at run time). In static initialization, the elements of an array are assigned values when the program is compiled. Syntax for static Initialization: type arrayName[size] = {value1, value2,…valueN}; Examples: int a[10] = {1,2,3,4,5,6,7,8,9,10}; int a[5]; a[2] = 10; int a[10] = {1,2,3,4,5} In dynamic initialization, the values are assigned to the elements of the array during the execution of the program. Example: int a[10], i; for(i = 0; i < 10; i++) { scanf(“%d”,&a[i]); }
  • 43. In the above example, the user will be storing the values into the array while executing the program. Until then, garbage values will be stored in the array. If we use braces i.e., { and }, for initializing the array, the default values for all the elements in the array will be zero. c) Example Program on One-dimensional Array: C Program to find Sum and Average of n Number using 1-D Array #include<stdio.h> void main() { int i, n, Sum=0, num[100]; float Average; printf("Enter How many Number you want?n"); scanf("%d",&n); printf("Enter the elements one by onen"); for(i=0;i<n;i++) { scanf("%d",&num[i]); Sum = Sum + num[i]; } Average = Sum/n; printf("Sum of the Numbers = %d", Sum); printf("Average of the %d Numbers = %.2f", Average); } TWO-DIMENSIONAL ARRAYS(2-D Array): A two dimensional array is used to store a table of values which has rows and columns. An array that has two subscripts (index), for example: a[i][j] is known as a two dimensional.  Some of the uses/applications of the two dimensional arrays are: 1) To maintain the marks of students. 2) To maintain prices of items etc…
  • 44. a) Two-dimensional Array Declaration: For using arrays in C programs, just like we are declaring variables before using them, we should declare arrays before using them. Syntax: for declaring a 2-D Array is shown below: type arrayName [rows] [columns]; Example: int x[3] [3]; In the above example ‟x’ is an integer array, which can hold 9 integer values. b) Two-dimensional Array Initialization: Initialization means assigning values. To assign values to the elements in the array. Generally, there are two types of initializing an array: 1) Static Initialization (at compile time). 2) Dynamic Initialization (at run time). In static initialization, the elements of an array are assigned values when the program is compiled. Syntax for static Initialization: type arrayName[row] [columns]= {value1, value2,…valueN}; arrayName[row] [coumns] = value; Examples: a [0] [0] = 1; int a [3] [3] = {1,1,1,2,2,2,3,3,3}; The memory representation of the two dimensional array will be as shown below:
  • 45. In dynamic initialization, the values are assigned to the elements of the array during the execution of the program. Example: int a[3] [3], i, j; for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf(“%d”, a[i][j]); } } c) Example Program on Two-dimensional Array: C Program to find Transpose of a matrix #include <stdio.h> void main() { int a[10][10], t[10][10], m, n, i, j; printf("Enter rows and columns of matrix: "); scanf("%d %d", &r, &c); printf("nEnter elements of matrix:n"); for(i=0; i<m; i++) { for(j=0; j<n; j++) {
  • 46. scanf("%d", &a[i][j]); } } for(i=0; i<m; i++) { for(j=0; j<n; j++) { t[j][i] = a[i][j]; } } printf("nTranspose of Matrix:n"); for(i=0; i<m; i++) { for(j=0; j<n; j++) { printf("%d ",t[i][j]); } } SEARCHING: The process of finding a particular item in the large amount of data is called “searching”. The element to be searched is called “key element”. There are two methods of searching: 1] Linear search. 2] Binary search. Linear search also called sequential search is a simple searching technique. In this technique we search for a given key item in linear order i.e. one after the other from first element to last element. If key item is present, the search is successful, otherwise unsuccessful search.
  • 47. 1] LINEAR SEARCH:  Algorithm: Linear_search (list, value) for each item in the list if key == value return successful else return unsuccessful end if end for end procedure  C Program to perform Linear Search: #include<stdio.h> void main() { int i,n,a[10],key; printf(“enter array elementsn”); scanf(“%d”,&n); printf(“enter array elementsn”);
  • 48. for(i=0; i<n; i++) { scanf(“%d”,&a[i]); } printf(“enter the key elementn”); scanf(“%d”,,&key); for(i=0; i<n;i++) { if(key==a[i]) { printf(“successful searchn”); exit(0); } } printf(“unsuccessful searchn”); } 2] BINARY SEARCH: This search algorithm works on the principle of divide and conquers. For this algorithm to work properly, the data should be in the sorted. There are 3 cases in binary search algorithm 1) Comparing the middle most item of the collection. If a match occurs, then the index of item is returned. 2) If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle item. 3) Otherwise, the item is searched for in the sub-array to the right of the middle item. This process continues on the sub-array as well until the size of the sub-array reduces to zero.
  • 49.  C Program to perform Binary Search: #include<stdio.h> #include<stdlib.h> int main() { int a[50],n,i,key,low,mid,high; printf("enter the number of elementsn"); scanf("%d",&n); printf("enter the array elementsn"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("enter the key element to be searchedn"); scanf("%d",&key); low=0; high=n-1; while(low<=high) { mid=(low+high)/2; if(a[mid]==key) { printf("ELEMENT %d FOUND AT POSITION %dn",key,mid+1); exit(0); } else if (a[mid]>key) high=mid-1; else
  • 50. low=mid+1; } printf("UNSUCCESSFULL SEARCHn"); return 0; } SORTING: A Sorting is used to rearrange a given array or list elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of element in the respective list of elements. There are two methods of sorting: 1] Bubble Sort. 2] Selection Sort. 1] BUBBLE SORT: Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order. This algorithm is not suitable for large data sets. Algorithm: Bubble Sort compares each pair of array element unless the whole array is completely sorted in an ascending order. for(i=1; i<n; i++) //for loop for number of passes {
  • 51. for(j=0;j<n-i;j++) //for loop for number of comparisons { if(a[j]>a[j+1]) //Comparison { temp=a[j]; //Swap using temp a[j]=a[j+1]; a[j+1]=temp; } } }  C Program to perform Bubble sort: #include<stdio.h> void main() { int a[50],i,j,n,temp; printf("enter the number of termsn"); scanf("%d",&n); printf("enter the array elementsn"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=1;i<n;i++) { for(j=0;j<n-i;j++) if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1];
  • 52. a[j+1]=temp; } } } printf("nARRAY ELEMENTS AFTER SORTINGn"); for(i=0;i<n;i++) { printf("%dt",a[i]); } printf("n"); } 2] SELECTION SORT: The Selection sort algorithm is based on the idea of finding the minimum or maximum element in an unsorted array and then putting it in its correct position in a sorted array.  Algorithm: Selection_sort (int A[ ], int n) { int minimum; // temporary variable to store the position of minimum element for(int i = 0; i < n-1 ; i++) // reduces the comparison size by one in each iteration.
  • 53. { minimum = i ; // assuming the first element to be the minimum. for(int j = i+1; j < n ; j++ ) // gives the effective size of the unsorted array { if(A[ j ] < A[ minimum ]) { //finds the minimum element minimum = j ; } } swap ( A[ minimum ], A[ i ]) ; // putting minimum element on its proper position. } }  C Program to perform Selection Sort: #include <stdio.h> void main() { int a[100], n, i, j, minimum,temp; printf("Enter number of elementsn"); scanf("%d", &n); printf("Enter %d integersn", n); for (i = 0; i< n; i++) { scanf("%d", &a[i]); } for(int i = 0; i < n-1 ; i++) { minimum = i ; for(int j = i+1; j < n ; j++ ) { if(a[ j ] < a[ minimum ])
  • 54. { minimum = j ; } } if (a[minimum ]!= a[i]) { temp= a[i]; a[i] = a[minimum]; a[minimum] = temp; } } printf("Sorted list in ascending order:n"); for (i = 0; i < n; i++) { printf("%dn", a[i]); } } STRINGS: A string is a sequence of characters terminated with a null character 0. A group of characters enclosed in double quotes is known as a string constant.  Some of the examples of string constants are: 1)“hai” 2)“hello world” 3)“My name is NITHIN” In C programming, there is no predefined data type to declare and use strings. So, we use character arrays to declare strings in C programs. Example: char s[5]; a) String Declaration & Initialization: we should declare strings before using them in the program. Strings are implemented as character arrays. Syntax: char string_name[size]; Example: char student_name[26];
  • 55. When the compiler assigns a character string to a character array, it appends a „0‟ to the end of the array. So, the size of the character array should always be number of characters plus 1. Character arrays can also be initialized when they are declared. Some of the examples for initializing the string are as shown below: 1) char name[13] = {„N‟,‟I‟,‟T‟,‟H‟,‟I‟,‟N‟,‟‟,‟K‟,‟U‟,‟M‟,‟A‟,‟R‟,‟0‟}; 2) char name[13] = “NITHIN KUMAR”; If less number of characters are provided than the size of the string, the rest of the characters are initialized to „0‟. b) Reading & Writing Strings: There are two ways read & write the strings 1) Formatted input/output – scanf & printf 2) Unformatted input/output – gets & puts  Syntax for formatted input/output: 1) Read – char str[10]; scanf(“%s”, str); 2) Print – printf(“The string is %s”, str);  Syntax for unformatted input/output: 1) Read – char str[10]; gets(str); //gets(array_name); 2) Print – printf(“The string is:”); puts(str); //puts(array_name);  Example C program to Read & Print Strings: /*Using scanf & printf*/ #include <stdio.h> void main() { char name[20]; printf("Enter name: "); scanf("%s", name);
  • 56. printf("Your name is %s.", name); } /*Using gets & puts*/ #include <stdio.h> void main() { char name[20]; printf("Enter name: "); gets(name); printf("Name: "); puts(name); } STRING-MANIPULATION FUNCTIONS(Built-in String Functions): C provides predefined functions for performing all operations or manipulations on strings. Most of these predefined functions are available in string.h header file. The list of predefined functions is given below: 1) String-concatenate (strcat): The strcat predefined function is used to concatenate/join two strings together. The syntax of the strcat function is shown below: strcat(string1,string2);
  • 57. The strcat function accepts two parameters which are strings. The strcat function takes the content of string2 and merges it with the content in string1 and the final result will be stored in string1. Example: 2) String-length (strlen): The strlen function is used to retrieve the length of a given string. The return type of this function will be an integer. The syntax of strlen function is as shown below: strlen(string); The function returns the length of the string which will be the number of characters in the string excluding the „0‟ character. Example: 3) String-compare (strcmp): The strcmp predefined function is used to compare two strings. The syntax of strcmp function is as shown below: strcmp(string1,string2); After comparison: 1) If the two strings are equal, then the function returns a 0.
  • 58. 2) If 1st string is greater than 2nd string returns 1. 3) If 1st string is lesser than 2nd string returns –1. Example: 4) String-copy (strcpy): The strcpy function is used to copy one string into another string. This function can be used for creating a copy of an existing string. The syntax of strcpy function is as shown below: strcpy(string1,string2); The string in string2 is copied into string1 and the result will be stored in string1 Example: 5) String-reverse (strrev): The strrev function is used to reverse a given string. We can use this predefined function to check whether a given string is a palindrome or not. The syntax for using the strrev function is as shown below: strrev(string);
  • 59. the strrev function reverses the given string and returns it back. The content of the string also changes. Example: EXAMPLE PROGRAMS TO BE PREPARED FROM THIS MODULE:  C program to print String Length without Built-in function #include<stdio.h> #include<string.h> int my_strlen(char[]); void main() { int len; char str1[26]]; printf("Enter String1:"); scanf("%s",str1); len=my_strlen(str1); printf("Length of "%s" is %d n",str1,len); } int my_strlen(char str1[]) { int i=0; while(str1[i] != '0')
  • 60. i++; return i; }  C program to Compare two String’s without Built-in function #include<stdio.h> #include<string.h> int my_strcmp(char[],char[]); void main() { int comp; char str1[26], char str2[26]; printf("Enter String1:"); scanf("%s",str1); printf("Enter String2:"); scanf("%s",str2); comp=my_strcmp(str1,str2); if(comp==0) printf("%s is equal to %sn",str1,str2); else if(comp>0) printf("%s is greater than %sn",str1,str2); else printf("%s is less than %sn",str1,str2); int my_strcmp(char str1[],char str2[]) { int i=0; while(str1[i]==str2[i]) { if(str1[i]=='0') break;
  • 61. i++; } return str1[i]-str2[i]; }  C program to concate two String’s without Built-in function #include<stdio.h> #include<string.h> void my_concat(char[],char[]); void main() { int comp; char str1[26], char str2[26]; printf("Enter String1:"); scanf("%s",str1); printf("Enter String2:"); scanf("%s",str2); my_concat(str1,str2); void my_concat(char str1[],char str2[]) { int i=0,j=0; while(str1[i]!='0') i++; while(str2[j]!='0') { str1[i++]=str2[j++]; } str1[i]='0'; printf("Concatenated string is "%s"n",str1);
  • 62. }  Program to find sum of n array elements #include<stdio.h> void main() { int i,n,a[10],sum=0; printf(“enter number of array elementsn”); scanf(“%d”,&n); printf(“enter array elementsn”); for(i=0; i<n; i++) { scanf(“%d”,&a[i]); } for(i=0; i<n;i++) { sum=sum+ a[i]; } printf(“sum is %dn”,sum): }  Program to find largest of n elements stored in an array #include<stdio.h> void main() { int i,n,a[10],big; printf(“enter number of array elementsn”); scanf(“%d”,&n); printf(“enter array elementsn”); for(i=0; i<n;i++)
  • 63. { scanf(“%d”,&a[i]); } big=a[0]; for(i=0; i<n;i++) { if(a[i]>big) big=a[i]; } printf(“the biggest element in an array is %dn”,big); }  Program to perform Matrix Multiplication. #include<stdio.h> void main() { int a[10][10],b[10][10],c[10][10],m,n,p,q,i,j,k; printf("Enter the size of first matrix n"); scanf("%d %d",&m,&n); printf("Enter the size of second matrix n"); scanf("%d %d",&p,&q); if(n==p) { printf("Enter the elements of first matrix n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d",&a[i][j]); } } printf("Enter the elements of the second matrix n"); for(i=0;i<p;i++) { for(j=0;j<q;j++) { scanf("%d",&b[i][j]); } }
  • 64. for(i=0;i<m;i++) { for(j=0;j<q;j++) { c[i][j]=0; for(k=0;k<n;k++) { c[i][j]=c[i][j]+a[i][k]*b[k][j]; } } } printf("The product of two matrix is n"); for(i=0;i<m;i++) { for(j=0;j<q;j++) { printf("%dt",c[i][j]); } printf("n"); } } else printf("Multiplication is not possible n"); }
  • 65. Module – 4:User Defined Functions & Recursive Functions FUNCTIONS: “In c, we can divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {} that performs a particular task/job”. A function can be called multiple times to provide reusability and modularity to the C program. In other words, we can say that the collection of functions creates a program. The function is also known as procedure or subroutine in other programming languages. Example: void hello( ) { printf("hello nithin"); } Need of Functions: Until now, in all the C programs that we have written, the program consists of a main function and inside that we are writing the logic of the program. The disadvantage of this method is, if the logic/code in the main function becomes huge or complex, it will become difficult to debug the program or test the program or maintain the program. So we‟ll break down entire logic into different parts, this type of approach for solving the given problems is known as Top Down approach. Advantages of Functions: Functions have many advantages in programming. Almost all the languages support the concept of functions in some way. Some of the advantages of writing/using functions are:  Functions support top-down modular programming.  By using functions, the length of the source code decreases.  Writing functions makes it easier to isolate and debug the errors.  Functions allow us to reuse the code.
  • 66. TYPES OF FUNCTIONS: Based on the nature of functions, they can be divided into two categories. They are: 1) In-built functions / Predefined functions / Library functions 2) User defined functions a) In-built functions / Predefined functions: is a function which is already written by another developer. The users generally use these library functions in their own programs for performing the desired task. The predefined functions are available in the header files. So, the user has to include the respective header file to use the predefined functions available in it. Example: the printf function which is available in the <stdio.h> header file is used for printing information. Other examples of predefined functions are: scanf, strlen, strcat, sqrt, fabs etc. b) User defined functions: A user defined function is a function which is declared and defined by the user himself. While writing programs, if there are no available library functions for performing a particular task, we write our own function to perform that task. Example: for user defined function is main function. BASIC ELEMENTS OF USER DEFINED FUNCTION: For creating user defined functions in C programs, we have to perform three steps. They are: a) Function Declaration: Declaring the function (blue-print). b) Function Definition: Defining the function (logic). c) Function Calling: use of function in program (calling)
  • 67. a) FUNCTION DECLARATION: The function declaration is the blue print of the function. The function declaration can also be called as the function’s prototype. The function declaration tells the compiler and the user about what is the function‟s name, inputs and output(s) of the function and the return type of the function. Syntax: for declaring a function is shown below: return_type function_name(parameters list); Example: int add(int m, int n); In the above example, add is the name of the function, int is the return type of the function. In our example, add function has two parameters. The parameters list is optional. b) FUNCTION DEFINITION: The function definition specifies how the function will be working i.e the logic of the function will be specified in this step. Syntax: of function definition is shown below return_type function_name(parameters list) { local variable declaration's; --- return(expression); } Example: int add(int a, int b) { int res; res = a+b; return res; } c) FUNCTION CALLING: After declaring and defining the functions, we can use the functions in our program. For using the functions, we must call the function by its name. Syntax: of function definition is shown below function_name(parameters list); Example: add(m,n); Whenever the compiler comes across a function call, it takes the control of execution to the first statement in the function‟s definition. After the completion of function i.e., whenever the compiler comes across the return statement or the closing brace of the function‟s body, the control will return back to the next statement after the function call.
  • 68. CATEGORIES OF USER DEFINED FUNCTIONS: A function may or may not accept any argument. It may or may not return any value. Based on these facts, there are four different aspects of function calls. a) function without arguments and without return value b) function without arguments and with return value c) function with arguments and without return value d) function with arguments and with return value a) Function without arguments and without return value: In this type of functions there are no parameters/arguments in the function definition and the function does not return any value back to the calling function. Generally, these types of functions are used to perform housekeeping tasks such as printing some characters etc. Example: void printstars( ){ int i; for(i = 0; i < 20; i++) { printf(“ * ”);
  • 69. } } In the above example, printstars function does not have any parameters. Its task is to print 20 stars whenever it is called in a program. b) Function without arguments and with return value: In this type of functions, the function definition does not contain arguments. But the function returns a value back to the point at which it was called. Example: int readint( ) { int num; printf(“Enter a number: “); scanf(“%d”,&num); return num; } In the above example, readint function has no parameters/arguments. The task of this function is to read an integer from the keyboard and return back to the point at which the function was called. c) Function with arguments and without return value: In this type of functions, the function definition contains arguments. But the function does not returns a value back to the point at which it was called. Example: void sum(int a, int b) { printf("nThe sum is %d",a+b); } In the above example, sum function has two parameters/arguments. The task of this function is to print the sum without using return value. d) Function with arguments and with return value: In this type of functions, the function definition consists of parameters/arguments. Also, these functions returns a value back to the point at which the function was called. These types of functions are the most frequently used in programming. Example: int add(int x, int y) { int result; result = x + y; return result; }
  • 70. In the above example, the function add consists of two arguments or parameters x and y. The function adds both x and y and returns that value stored in the local variable result back to the point at which the function was called. PROGRAM TO FIND GCD & LCM USING FUNCTIONS: NESTED FUNCTION: A function calling another function within its function definition is known as a nested function. So, far we are declaring a main function and calling other user-defined functions and predefined functions like printf, scanf, gets, puts etc., So, main function can be treated as a nested function. Example: void main() {
  • 71. func1(); } void func1() { for(i=1;i<10;i++) { func2(); } } void func2() { printf(“%dn”,i); } PARAMETERS PASSING IN C FUNCTION: When a function gets executed in the program, the execution control is transferred from calling-function to called function and executes function definition, and finally comes back to the calling function. When the execution control is transferred from calling-function to called-function it may carry one or number of data values. These data values are called as parameters. In C, there are two types of parameters and they are as follows: 1) Actual Parameters 2) Formal Parameters There are two methods to pass parameters from calling function to called function and they are as follows... 1) Pass by Value 2) Pass by Reference In C, there are two types of parameters and they are as follows:
  • 72. There are two methods to pass parameters from calling function to called function: a) PASS BY VALUE: In call by value parameter passing method, the copy of actual parameter values are copied to formal parameters and these formal parameters are used in called function. The changes made on the formal parameters does not effect the values of actual parameters. That means, after the execution control comes back to the calling function, the actual parameter values remains same. Example: void swap(int a, int b) // called function { int temp; temp = a; a = b; b = temp; } b) PASS BY REFERENCE: In Call by Reference parameter passing method, the memory location address of the actual parameters is copied to formal parameters. This address is used to access the memory locations of the actual parameters in called function. Whenever we use these formal parameters in called function, they directly access the memory locations of actual parameters. So the changes made on the formal parameters effects the values of actual parameters. Example: void swap(int *a, int *b) // called function { int temp;
  • 73. temp = *a; *a = *b; *b = temp; } Difference between Pass by Value & Reference: SCOPE, VISIBILITY & LIFETIME OF VARIABLES (STORAGE CLASSES)
  • 74.  “auto” This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope). example: auto int i=1; They are assigned a garbage value by default whenever they are declared.  “extern” extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. example: int i=1;--------- extern int i; a normal global variable can be made extern as well by placing the „extern‟ keyword before its declaration/definition in any function/block.  “static” This storage class is used to declare static variables which are popularly used while writing programs in C language. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. example: static int i=1; Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.  “register” This storage class declares register variables which have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. example: register int i; An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers. RECURSIVE FUNCTION: A function is said to be recursive, if a function calls itself within the function‟s definition. When writing recursive functions, proper care must be taken that the recursive calls return a value back at some point. Otherwise, the function calls itself infinite number of times.
  • 75. Example: In the above example, func1 is calling itself in the last line of its definition.  FACTORIAL OF A NUMBER – Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n! Example: 5! = 5*4*3*2*1 = 120 Recursive Function: 5! = 5 * 4! // n * Fact(n-1) 4! = 4 * 3! 3! = 3 * 2! 2! = 2 * 1! 1! = 1 * 0! 0! = 1 //Stop Condition Program to find factorial of given number using recursion: #include<stdio.h> int find_factorial(int); void main() { int num, fact; printf("nEnter any integer number:"); scanf("%d",&num); fact =find_factorial(num); printf("nfactorial of %d is: %d",num, fact); } //recursive function definition int find_factorial(int n) {
  • 76. if(n==0) { return 1; } else{ return(n*find_factorial(n-1)); } }  FIBONACCI SERIES – a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. Example: 0, 1, 1, 2, 3, 5, 8, etc. The first two numbers of fibonacci series are 0 and 1. Recursive Function: There are 3 cases in fibonacci series 1) if n = 1 only one digit to be printed i.e “0”. 2) if n = 2 only two digit to be printed i.e “1”. 3) if n > 2 last two digits to be added & printed so “fib(n-1) + fib(n-2)” Program to find Fibonacci Series using recursion: #include<stdio.h> int fib(int); void main() { int n, i = 0, c; printf(“enter N valuen”); scanf("%d", &n); printf("Fibonacci series terms are:n"); for (c = 1; c <= n; c++) { printf("%dn", fib(i)); i++; } } int fib(int n) { if (n == 0 || n == 1) return n; else return (fib(n-1) + fib(n-2)); }
  • 77. EXAMPLE PROGRAMS TO BE PREPARED FROM THIS MODULE: Program to Convert Binary number to Decimal: #include <stdio.h> int convert(int); void main() { int dec, bin; printf("Enter a Binary numbern"); scanf("%d", &bin); dec = convert(bin); printf("The Decimal Equivalent of %d is %d n", bin, dec); } int convert(int bin) { if (bin == 0) { return 0; } else { return (bin % 10 + 2 * convert(bin/10)); } } Program to check whether the given number is prime or not: #include<stdio.h> int isPrime(int); void main() { int res,num; printf("Enter the number:"); scanf("%d",&num); res=isPrime(num); if(res==0) printf("%d is not a Prime Numbern",num); else printf("%d is a Prime Numbern",num); } int isPrime(int num) {
  • 78. int i; if (num==0 || num==1) return 0; for (i=2; i<=num/2; i++) { if (num %i == 0) { return 0; } } return 1; }
  • 79. Module – 5:Structures, Pointers & Preprocessor Directives STRUCTURES: “A structure is a collection of heterogeneous data elements referred by the same name”.  Drawback of arrays: arrays can be used to represent a collection of elements of the same data type like int, float etc. They cannot be used to hold a collection of different types of elements.  Syntax of Structure: structures must be first defined first for their later use. The syntax for defining a structure is as shown below: struct structure_name { datatype var1; datatype var2; ------- }; The keyword struct declares a structure. The structure_name represents the name of the structure. The structure definition is always terminated with a semicolon.  Example: struct student { int rollno; char name[26]; int marks; }; In the above example, student is the name of the structure. The members of the student structure are: name, rollno and marks. A structure itself does not occupy any memory in the RAM. Memory is allocated only when we create variables using the structure. a) Declaring Structure Variables: A structure variable declaration is similar to the declaration of variables of any other data types.  Syntax for declaring structure variables: struct structurename var1, var2, …., varN
  • 80.  Example: struct student s1, s2, s3; We can also combine the structure definition and the declaration of structure variables into a single line such structures are called “Tagged Structures” as shown below: struct student { int rollno; char name[26]; int marks; } s1, s2, s3; We can use the keyword typedef to define a structure as follows: typedef struct { int rollno; char name[26]; int marks; }student; The name student represents the structure definition associated with it and therefore can be used to declare structure variables as shown below: student s1, s2, s3; b) Accessing Structure Members: We can access and assign values to the members of a structure in a number of ways. They should be linked to the structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator „.‟ which is also known as dot operator or period operator.  Syntax for accessing a structure member: structure-varaible.membername  Example: s1.name s1.rollno
  • 81. c) Structure Initialization: The values can be initialized in two ways 1) static initialization 2) dynamic initialization  Example for static initialization: struct student { int rollno; char name[26]; int marks; } ; struct student s1 = {“01”, “nithin”,”96”}; struct student s2 = {“02”,”gowda”,”56”};  Example for dynamic initialization: scanf(“%d”, &s1.rollno); scanf(“%s”, s1.name); scanf(“%d”, s1.marks); ARRAYS OF STRUCTURES: If we want to store details of 100 students it will become difficult to declare and maintain 100 variables and store the data. Instead, we can declare and array of structure variables as shown below: struct student { int rollno; char name[26]; int marks; } ; struct student s[100]; In the above example, we are declaring an array „s‟ with 100 elements of the type student which is a structure.
  • 82. NESTED STRUCTURES: In C, structures can be nested. A structure can be defined within in another structure.  Example of nested structure: struct student { struct name { char fname[10]; char lname[10]; }; int rollno; int marks; }; In the above example, student is the outer structure and the inner structure name consists of two members: fname and lname.  The members of the inner structure can be accessed as shown below: outer_structure_variable.inner_structure_variable.member_name; Example: s1.name.fname; PASSING STRUCTURES TO FUNCTIONS: Functions are the basic building blocks of a C program. So, it is natural for C language to support passing structures as parameters in functions. We can pass the C structures to functions in 3 ways: 1) Passing each individual item of the structure as a function argument. 2) Passing the whole structure as a value. 3) Passing the address of the structure (pass by reference). Syntax for passing the structure variable as a parameter is shown below: return-type function-name(struct structname var) {
  • 83. ---- ---- return expression; } 1] PASSING STRUCTURE TO FUNCTION IN C BY VALUE : the whole structure is passed to another function by value. It means the whole structure is passed to another function with all members and their values. So, this structure can be accessed from called function. Example for pass by value: #include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; }; void func(struct student record); void main() { struct student record = {“01”, “Nithin”,”69”} func(record); } void func(struct student record) { printf(" Id is: %d n", record.id); printf(" Name is: %s n", record.name); printf(" Percentage is: %f n", record.percentage); }
  • 84. 2] PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS : the whole structure is passed to another function by address. It means only the address of the structure is passed to another function. The whole structure is not passed to another function with all members. Example for pass by Address(reference):: #include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; }; void func(struct student *record); void main() { struct student record = {“01”, “Nithin”,”69”} func(&record); } void func(struct student record) { printf(" Id is: %d n", record->id); printf(" Name is: %s n", record->name); printf(" Percentage is: %f n", record->percentage); }  C program to read, write & compute average marks of N students using strurcture #include<stdio.h> struct student {
  • 85. int roll; char name[50]; int marks; }; void main() { struct student s[10]; int i,n,sum=0; float average=0.0; printf("Enter the number of studentsn"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the roll number:"); scanf("%d",&s[i].roll); printf("Enter the Name:"); scanf("%s",s[i].name); printf("Enter Total Marks:"); scanf("%d",&s[i].marks); } for(i=0;i<n;i++) { sum=sum+s[i].marks; } average=(float)sum/n; printf("Class Average is %gn",average); printf("Record details of students:n"); for(i=0;i<n;i++)
  • 86. { printf("%4d",s[i].roll); printf("%15s",s[i].name); printf("%15d",s[i].marks); if(s[i].marks>=average) printf("tYes"); else printf("tNo"); printf("n"); } } POINTERS: A pointer is a derived data type in C. It is built from one of the fundamental data types available in C. Pointers contain memory addresses as their values. Since these memory addresses are the locations in the computer memory where program instructions and data are stored. pointers can be used to access and manipulate data stored in the memory.  Advantages of Pointers: Pointers are used frequently in C, as they offer a number of benefits to the programmers. They include the following:  Pointers are more efficient in handling arrays and data tables.  Pointers allow C to support dynamic memory management.  Pointers provide an efficient way for manipulating dynamic data structures such as structures, linked lists, queues, stacks and trees.  Pointers increase the execution speed and thus reduce the program execution time.  Pointers can be used to return multiple values from a function via function arguments.  Pointers allow passing a function as argument to other functions.
  • 87.  How a Pointer Works: Whenever we declare a variable in our programs, the system allocates somewhere in the memory, an appropriate location to hold the value of the variable. This location will have its own address number. Consider the following example: The above statement int var creates a location in the memory to hold integer value. That location will have an address for example assume it is 5000. The statement var = 200 stores the value 200 at the location whose address is 5000. So, in our example, var is the variable name, 200 is the value stored in var and 5000 is the address of the memory location containing the variable var. So, we can access the value 200 either by using the variable name var or by using the address of the memory location which is 5000.‟ a) Pointer Variable, Constants & Values: “The concept of storing memory address in a variable and accessing the value available at that address is known as a pointer variable.” Since the pointer is also variable, it will also have a memory address just like any other variable.  Pointer Constants: The memory addresses within a computer are referred to as pointer constants.  Pointer Values: We cannot assign the memory addresses directly to a variable. We can only get the address of a variable by using the address operator (&). The value thus obtained is known as pointer value.  Pointer Variables: Once we obtain the pointer value, we can store it in a variable. Such variable which stores the memory address is known as a pointer variable. b) Declaring Pointer Variables: In C, every variable must be declared for its type. Since pointer variables contain addresses that belong to a specific data type, they must be declared as pointers before we use them.  Syntax for declaring a pointer is as shown below: datatype *pointer-name;
  • 88. This tells the compiler three things about the variable pointer-name. They are: The asterisk (*) tells that the variable pointer-name is a pointer variable, pointer-name needs a memory location and pointer-name points to a variable of type datatype.  Example: int *p; float *p; char *ch; c) Initialization of pointer variables: The process of assigning the address of a variable to pointer variable is known as initialization.  Method-1: int x; //declare a data variable int *px; //declare a pointer variable px=&x // copy the address of data variable to pointer variable  Method-2: int x; //declare a data variable int *px=&x; //assign the address of data variable to pointer variable  Method-3: int x,*px=&x; //declare data variable and assign address d) Dereferencing: Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator. Another name for the dereferencing operator is the indirection operator.  Example: int quantity, *p, n; quantity=179; p=&quantity; n=*p; CHAIN OF POINTERS(MULTIPLE INDIRECTIONS): It is possible to make a pointer to point to another pointer, thus creating a chain of pointers. A variable that is a pointer to a pointer must be declared using additional indirection operator symbols in front of the name
  • 89. Here, the pointer variable p2 contains the address of the pointer variable p1, which points to the location that contains the desired value.  Example: int **p2 Consider the following example: void main() { int x,*p1, **p2; x=100; p1=&x; p2=&p1; printf(“%d”, **p2); } RULES OF POINTERS OPERATIONS:  A pointer variable can be assigned the address of another variable.  A pointer variable can be assigned the values of another pointer variable.  A pointer variable can be initialized with NULL or zero value.  A pointer variable can be pre-fixed or post-fixed with increment or decrement operators.  An integer value may be added or subtracted from a pointer variable.  A pointer variable cannot be multiplied by a constant.  Two pointer variables cannot be added.  A value cannot be assigned to an arbitrary address(i.e., &x=10; is illegal) Pointers in Arrays: Consider an 1D-Array x[5] = {100,101,102,103,104}  If we declare ptr as an integer pointer, then we can make the pointer ptr to point to the array x by the following assignment:
  • 90. ptr=x; this is equivalent to ptr=&x[0];  We can access every value of x using p++ to move from one element to another  The address of an element is calculated using its index and the scale factor of the data type address of x[n] = base address+(n * scale factor of datatype)  Example: consider 1000 as base address & scale factor of int = 2 bytes x[3] = 1000+(3*2) = 1006. While working with 2D arrays, we must use two pointers such that one pointer points index “i” & another one points index “j”. ARRAYS OF POINTERS: One of the important uses of pointer is in handling of a table of strings.  Consider the following array of strings: char name[3][25]; //requires 75bytes  Instead of making each row a fixed number of characters, we can make it a pointer to a string of varying length. char *name[3]= {“Mysuru”,“Mandya”,“Hassan”}; Declares name to be an array of three pointers to characters, which requires only 21 bytes, sufficient to hold all the characters.  The following statement would print out all the three names: for(i=0;i<=2;i++) printf(“%sn”,name[i]); The character arrays with the rows of varying length are called “ragged arrays” and they are better handled by pointers. POINTERS AS FUNCTION ARGUMENTS: When we pass the address of a variable as an argument the receiving parameter should be pointers. This process of calling a function using pointers to pass the addresses of variables is known as “Call by reference”. This method will directly access the memory locations of actual parameters. So the changes made on the formal parameters effects the values of actual parameters.
  • 91.  Example: void swap(int *a, int *b) // called function { int temp; temp = *a; *a = *b; *b = temp; } Passing Structures to Functions (using Pointers): Functions are the basic building blocks of a C program. So, it is natural for C language to support passing structures as parameters in functions.  We can pass the C structures to functions using pointers its also called as “Passing the address of the structure (pass by reference)”.  Syntax for passing address the structure variable using pointer as a parameter: return-type function-name(struct structname *var) {
  • 92. ---- return expression; } We can access the members of structure using “arrow () operator or membership operator”.  Example: #include <stdio.h> #include <string.h> struct student { int id; char name[20]; float percentage; }; void func(struct student *record); void main() { struct student record = {“01”, “Nithin”,”69”} func(&record); } void func(struct student record) { printf(" Id is: %d n", record->id); printf(" Name is: %s n", record->name); printf(" Percentage is: %f n", record->percentage); } DRAWBACKS OF POINTERS:  Uninitialized pointers might cause segmentation fault.  Dynamically allocated block needs to be freed explicitly. Otherwise, it would lead to memory leak.  Pointers are slower than normal variables.  If pointers are updated with incorrect values, it might lead to memory corruption.  Understanding and using pointers in best way possible requires a lot of time.
  • 93. PREPROCESSOR DIRECTIVES: C provides many features like structures, unions and pointers. Another unique feature of the C language is the preprocessor.  Preprocessor directives are placed in the source program before the main line. Before the source code passes through the compiler, it is examined by the preprocessor for any preprocessor directives. “Preprocessor directives are lines included in a program that begin with the character #, which make them different from a typical source code text. They are invoked by the compiler to process some programs before compilation.”  The preprocessor directives are divided into four categories. They are: 1) Macro Substitution Directive (#define) 2) File Inclusion Directive (#include) 3) Compiler Control Directives (conditional directives) 4) ANSI C directives MACRO SUBSTITUTION DIRECTIVES: Macro substitution is a process where an identifier in a program is replaced by a predefined string composed of one or more tokens.  The preprocessor accomplishes this task under the direction of #define statement. This statement, usually known as a macro definition  Syntax: #define identifier string  Example: #define PI 3.14 There is no space between the # and the word define. Also there should be atleast a single space between #define, identifier and string. Also, there will be no semi-colon at the end of the statement.  There are different forms of macro substitution. The most common are: 1) Simple macro substitution 2) Argumented macro substitution 3) Nested macro substitution 1] Simple macro substitutions: are generally used for declaring constants in a C program. Some valid examples for simple macro substitution are:  Example for simple macro: #define PI 3.14 #define size 100
  • 94. 2] Argumented macro substitution: The preprocessor allows us to define more complex and more useful form of substitutions. The Argumented macro substitution takes the following form:  Syntax: #define identifier(arg1,arg2…., argn) string Care should be taken that there is no space between the identifier and the left parentheses. In the program, the occurrence of a macro with arguments is known as a macro call. When a macro is called, the preprocessor substitutes the string, replacing the formal parameters with actual parameters.  Example for argument macro: #define CUBE(x) (x*x*x) //Macro definition volume = CUBE(side) //Macro Call volume = side*side*side //Execution 3] Nested Macros: We can use one macro inside the definition of another macro. Such macros are known as nested macros.  Example for Nested Macros: #define SQUARE(x) (x*x) #define CUBE(x) (SQUARE(x)*x) FILE INCLUSION DIRECTIVES: The external files containing functions or macro definitions can be linked with our program so that there is no need to write the functions and macro definitions again.  This can be achieved by using the #include directive. The syntax for this directive is as shown below: #include “filename” or #include<filename> We can use either of the above statements to link our program with other files.  If the filename is included in double quotes, the file is searched in the local directory. If the filename is included in angular brackets, then the file is searched in the standard directories.
  • 95. COMPILER DIRECTIVES: The following are the compiler control directives used in c programming: Directive Purpose #ifdef Test for a macro definition #endif Specifies the end of #if #ifndef Tests whether a macro is not defined #if Test a compile-time condition #else Specifies alternative when #if fails These directives allow the programmer to include the portions of the codes based on the conditions. #ifdef and #endif directive:
  • 96. #ifndef and #else directive: The #ifndef works exactly opposite to that of #ifdef preprocessor tests whether the identifier has defined substitute text or not. If identifier is defined then #else block is compiled and executed and the compiler ignores #if block. ANSI PREPROCESSOR DIRECTIVES: The ANSI committee has added some more preprocessor directives to the existing list. They are: Directive Purpose #elif Provides alternative test facility #pragma Specifies compiler instructions #error Stops compilation when an error occurs #elif directive:”#elif directive”: enables us to establish an “if…else…if” sequence for testing multiple conditions.  The syntax is as shown below:
  • 97. #if expr1 Stmts; #elif expr2 Stmts; #elif expr3 Stmts; #endif #pragma directive: directive is an implementation oriented directive that allows the user to specify various instructions to be given to the compiler. Syntax: #pragma name Where name is the name of the pragma we want. For example, under Microsoft C, #pragma loop_opt(on) causes loop optimization to be performed. “#error directive”: is used to display user defined message during compilation of the program. Syntax: #if !defined(identifer) #error <ERROR MESSAGE> #endif Example: #include<stdio.h> #define B1 void main(){ #if !defined(A) #error MARCO NOT DEFINED #else printf(“macro found”) #endif }