0% found this document useful (0 votes)
3 views205 pages

c Notes Compiled by Ns

This document provides an overview of programming languages, categorizing them into low-level and high-level languages, along with their advantages and disadvantages. It also discusses software types, including system software, application software, and programming software, as well as the software development lifecycle (SDLC) steps. Additionally, it outlines the evolution of programming languages through different generations and emphasizes the importance of structured programming.

Uploaded by

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

c Notes Compiled by Ns

This document provides an overview of programming languages, categorizing them into low-level and high-level languages, along with their advantages and disadvantages. It also discusses software types, including system software, application software, and programming software, as well as the software development lifecycle (SDLC) steps. Additionally, it outlines the evolution of programming languages through different generations and emphasizes the importance of structured programming.

Uploaded by

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

UNIT 1

Introduction to Programming Languages


1.1 Programing Languages
A programming language is a standardized communication technique for describing
instructions for a computer. In other word, the language which are needed to
communicate with the computers are known as computer languages or programming
language. It has simple structures which provide meaning and understand by computer
only.

Programming language are classified mainly in two categories:


1. Low level programming language
2. High level programming language

1. Low level programming language


Low level language are specific to hardware. Before creating a program, it is
required to have through knowledge of that hardware.

Advantages of low level languages


• It makes fast and efficient use of computers
• Translator is not required.
Disadvantages of low level languages
• Programmer should have hardware knowledge.
• All memory addresses and operation codes are needed to be remembered.
• Testing and Debugging are difficult to carry out.
• They are machine dependent.

Low level programming language are divided into two types.


a. Machine language
b. Assembly language

a. Machine language
Machine language are lowest- level programming language. A computer
understands program written only in the machine language. It is directly
executable by computer without the need for translation by a compiler or an
assembler. Machine code consist entirely of the 0’s and 1’s of the binary
system. Early computers were programmed using machine language. Programs
written in machine language are faster and efficient. Writing program in
machine language is very tedious, time consuming, difficult to find bugs in
longer programs.

b. Assembly language
In assembly language, instead of using numeric opcodes (i.e. pattern of 0 &1
),mnemonics are used eg. ADD,SUB etc. Program written in assembly language
must be converted into machine language which could be done by assembler.
Assembly language program written for one type of CPU won’t run on another.
So that assembly language is time consuming and machine dependent.

2. High Level programming language


High level language were developed to make programming easier. Most of the high
level language are English like languages. They use familiar English words, Special
symbols (! & etc.)in their syntax .Therefore high level language are easier to read,
write, understand and maintain. Each high level language has their own set of
grammar and rules to represent set of instructions. Eg. C ,C++,Java, FORTAN etc.
Program written in high level language also need to translated into machine
language. This can be done either by compiler or interpreter.

Advantages of High level language


• High level languages are programmer friendly.
• They are easy to write, debug and maintain.
• They are portable, which means same code can run on different
hardware.
• Easy to learn.

Disadvantages of High level language


• It takes additional translation times to translate the source to machine
code.
• Execution of high level programs are comparatively slower than low
level programs.
• Compared to low level programs, they are generally less memory
efficient.
• Cannot communicate directly with the hardware.

Differences between high level and low level programming language


High level programming language Low level programming language
1. It is programmer friendly language. 1. It is machine friendly language.
2. Compiler or interpreter is required 2. Assembler is required for
for translation. translation.
3. They execute slower. 3. They execute faster.
4. For writing program hardware 4. For writing program hardware
knowledge is not required. knowledge is required.
5. They are easier to learn and 5. It is difficult to learn and understand
understand by human by human
6. It is simple to debug and maintain. 6. It is difficult to debug and maintain
as compared to high level language.
7. Example: C, C++, Java etc. 7. Example: Assembly language
.
Language Translator
A programmer write a program in high level language that is to be translated into
machine language equivalent code.
This task is achieved by using language translator. The common language translator
are:
• Compiler
• Interpreter
• Assembler
Difference between compiler and interpreter
Compiler Interpreter
1. A compiler translates the entire 1. An interpreter translates one
source code to object code and statement at a time, executes it
then only object code is and continues for another
executed. statement.
2. Compiler is faster than 2. Interpreter is slower than
interpreter. compiler.
3. It generates the error message 3. It continuously translates the
only after scanning the whole program until the first error is
program. Hence debugging is met, in which case it stops.
comparatively hard. Hence debugging is easy.
4. As compared to an interpreter 4. As compared to a compiler
developing a compiler is developing interpreter is easier
difficult.
5. Programming language like 5. Python use interpreter.
C,C++,FORTAN use compiler.

Assembler
An assembler is a program (software) which translates the program written in
assembly language to machine language. It takes the basic commands and
operations from assembly code and converts them into binary code that can be
recognized by a specific type of processor. Assemblers are similar to compilers in
that they produce executable code. However, assemblers are more simplistic since
they only convert low-level code (assembly language) to machine code.

1.2 Software and its types


Software is a computer program which is a sequence of instructions designed to direct
a computer to perform certain task. The software enables a computer to receive input,
store information, make decisions, manipulate and output data in the correct format. A
program consists of instruction that tell the computer what to do and how to behave.

Types of Software
1. System software
2. Application software
3. Malicious or malware software
4. Programming software
1. System software
The purpose of system software is to help run the computer system by controlling,
Integrating and managing the individual hardware components of a computer
system.eg. Operating system, device drivers etc. Operating systems like linux ,
windows and DOS (Disk operating system) control all parts of the computer system
by handling I/O devices, coordinating and managing resources like memory, disk
,CPU etc. and provide a environment over which other programs(software) can run.
2. Application software
Application software is a software program or group of programs designed for end-
users to fulfill their requirement. It enables the end users to accomplish certain
specific tasks. It is designed to process data and support users in an organization such
as solving equations or producing bills, result processing of colleges, data processing
of accounts in banks.
Example: word, Excel, PowerPoint, Photoshop etc.

Application software can be classified into following categories.


• Tailored software: These kind of software are developed for solving particular
problem. It is specifically developed for some specific organization or other user.
Example: Banking software, school student record keeping software, business
software.
• Packaged software: These software that is often used together, performs similar
functions, or includes similar features, and is bundled together as a set of software
programs. For example, Microsoft Office is packaged software, including multiple
software programs used in a home or office, such as Microsoft Excel, Microsoft
Word, and Microsoft PowerPoint. Video and audio editing software may be available
as packaged software as well, as they may be used together for editing music and
video files used in a movie.
• Utility software: These are special types of application software which help us to
fine tune the performance of a computer, prevent unwanted actions or perform system
related tasks such as checking for virus and removing virus, system utilities which
provide information about current state of the use of files, memory, users and
peripherals eg disk info, check disk, debuggers for removing “bugs” from program.

3. Malicious or malware software


Malware refers to any programs or file that is intentionally harmful to computer,
network or server. It is design to cause disruption to a computers. Unauthorized
access to information or system and interfere the system security and privacy.
Example: computer virus, worms ,Trojan horses.

4. Programming software
While application software is designed for end-users, and system software is designed
for computers or mobile devices, programming software is for computer
programmers and developers who are writing code. It is also known as programming
tool or software development tool, that assists software developer or programmers to
create, develop, debug and maintain other programs and application.

1.3 Levels/Generations of Programming Languages:


Programming Languages have been developed over the year in a phased manner. Each
phase of developed has made the programming language more user-friendly, easier to
use and more powerful.
We shall consider five levels (or generations) of programming languages
1. Machine Languages / First-generation languages
2. Assembly Languages / Second-generation languages
3. Procedural Languages / Third-generation languages
4. Problem-oriented Languages / Fourth-generation languages
5. Natural Languages / Fifth-generation languages

1. Machine Languages / First-generation languages


The first-generation languages are also called machine languages/ 1G language.
This language is machine-dependent. The machine language statements are written
in binary code (0/1 form) because the computer can understand only binary
language.
Advantages:
• Fast & efficient as statements are directly written in binary language.
• No translator is required.
Disadvantages:
• Difficult to learn binary codes.
• Difficult to understand – both programs & where the error occurred.

2. Assembly Languages / Second-generation languages


The second-generation languages are also called assembly languages/ 2G languages.
Assembly language contains human-readable notations that can be further converted to
machine language using an assembler.
Assembler – converts assembly level instructions to machine-level instructions.
Programmers can write the code using symbolic instruction codes that are
meaningful abbreviations of mnemonics. It is also known as low-level language. In
assembly language, instead of using numeric opcodes (i.e. pattern of 0 &1),
mnemonics are used eg. ADD, SUB etc.
Advantages:
• It is easier to understand if compared to machine language.
• Modifications are easy.
Disadvantages:
• Assembler is required.
• This language is architecture /machine-dependent, with a different
instruction set for different machines

3. Procedural Languages / Third-generation languages


The third generation is also called procedural language /3 GL. The third generation
programming languages were designed to overcome the various limitations of the first
and second generation programming languages. It consists of the use of a series of
English-like words that humans can understand easily, to write instructions. It is
also called High-Level Programming Language. For execution, a program in this
language needs to be translated into machine language using a Compiler/
Interpreter. Examples of this type of language are C,C++, PASCAL, FORTRAN,
COBOL, etc.
Advantages:
• Use of English-like words makes it a human-understandable language.
• Lesser number of lines of code as compared to the above 2 languages.
Disadvantages:
• Compiler/ interpreter is needed.
• Different compilers are needed for different machines

4. Problem-oriented Languages / Fourth-generation languages


The fourth-generation language is also called a non – procedural language/ 4GL. It
enables users to access the database. Examples: SQL, Foxpro, Focus, etc.
These languages are also human-friendly to understand. The fourth generation
programming languages were designed and developed to reduce the time, cost and
effort needed to develop different types of software applications.
Advantages:
• Easy to understand & learn.
• Less time is required for application creation.
• It is less prone to errors.
Disadvantages:
• Memory consumption is high.
• Has poor control over Hardware.
• Less flexible.

5. Natural Languages / Fifth-generation languages


The fifth-generation languages are also called 5GL. It is based on the concept of
artificial intelligence. It uses the concept that rather than solving a problem
algorithmically, an application can be built to solve it based on some constraints,
i.e., we make computers learn to solve any problem. Parallel Processing &
superconductors are used for this type of language to make real artificial
intelligence.
Advantages:
• Machines can make decisions.
• Programmer effort reduces to solve a problem.
• Easier than 3GL or 4GL to learn and use.
Disadvantages:
• Complex and long code.
• More resources are required & they are expensive too.

1.4 Structured Programming Language


The structured programming allows developing a program using a set of modules or
functions. In other word, in structured programming language programs are divided into
small programs or functions. In this programming, user can create its own user-defined
functions. It also requires more discipline at the design and logical structuring stage. Its
main aim is to improve and increase quality, clarity, and development time of computer
program. Example : Pascal, C etc.

Advantages of Structured Programming Language


• Easier to read and understand
• User Friendly
• Easier to Maintain
• Easier to Debug
• Machine-Independent, mostly.
Disadvantages
• Since it is Machine-Independent, So it takes time to convert into machine code.
• The converted machine code is not the same as for assembly language.
• The program depends upon changeable factors like data-types. Therefore it needs to
be updated with the need on the go.
• Lack of encapsulation - lack of information hiding

Why C is called Structured Programming language?


→ C is called a structured programming language because to solve a large problem, C
programming language divides the problem into smaller modules called functions or
procedures each of which handles a particular responsibility. The program which solves the
entire problem is a collection of such function

Basic Structure of c program

program
/* sum of integer*/
#include <stdio.h>
int main()
{
int number1, number2, sum;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
sum = number1 + number2;
printf("%d + %d = %d", number1, number2, sum);
return 0;
}
Some important question of this topic
1. What do you mean by programming language? Explain all types of programming
language with examples.
2. Explain briefly the various generations or level of programming language.
3. What is a software? Differentiate tailored and packaged software.
4. Explain the different type of software used in today’s life.
5. What is programming language? Describe Low level programming language (LLL)
and High level Programming language (HLL) with its advantage and disadvantage.
6. Why High level programming is preferred to low level programming Language.
7. What do you mean by language translation? Differentiate compiler and interpreter.
8. Why C is called Structured Programming language?
Unit 2
Problem solving using computer(software development lifecycle(sdlc))

The steps involved in software development cycle are

1. Problem definition
2. Algorithm and flow chart
3. Coding
4. Compilation and execution
5. Debugging and testing
6. Implementation and maintenance
7. Documentation

Problem definition

• Is a process of becoming familiar with the problem.eg when we have to make program for calculating
area of ellipse wet have to know the formula .
• Study of programs software requirements, manpower requirements,hardware requirements,available
time period etc.
• Feasibility study.
Algorithm

• An algorithm is a step by step description of the method to solve a problem.


• Algorithm maintains sequences of computer instructions required to solve a problem in such a way that if
the instructions are executed in the specified sequence the desired result is obtained.

An algorithm to add two numbers

1.Start
2.Declare variable a,b and sum
3.Input a & b
4.Calculate sum=a+b
5.Display print sum
6.stop

Flowchart
• It is the diagrammatic representation of an algorithm.
• It is drawn by using basic blocks where each box/block have usual meaning.
Flow chart to add two numbers

Coding
• Coding is the process of transforming the program logic into a computer language or programming
language.
• It can be said that coding is the act of transforming operations in each box of the flowchart in terms of the
statement of the programming.

//example of coding
#include<stdio.h>
int main()
{
int num1,num2,sum;
printf("enter two numbers\n");
scanf("%d %d",&num1,&num2);
sum = num1+num2;
printf("the sum is %d",sum);
return 0;
}
Compilation and execution

• It is the process of translating high level language into machine level language.
• Done by software known as compiler.
• It tests the program whether it contains errors or not.
• If syntax errors are present compiler cannot compile the code

Assembly code
#include<stdio.h>
void main() {
int a = 10, b = 20, c;

asm {
mov ax,a
mov bx,b
add ax,bx
mov c,ax
}
printf("c= %d",c);
}
Fig:compilation and execution process
Debugging and testing

• Debugging is the discovery and correction of programming errors.


• Even after taking full care in program design and coding,some errors may remain in the program because
the programmer might have not thought about a particular case.
• Testing ensures that program performs correctly.

Implementation and maintenance

• Once the product is tested and ready to be deployed it is released formally in the appropriate market.
• Maintenance includes all the activity after the installation of software that is performed to keep the system
operational. As we have mentioned earlier, software often has design faults.
• It is generally agreed that for large systems, removing all the faults before delivery is extremely difficult
and faults will be discovered long after the system is installed. As these faults are detected, they have to be
removed. Maintenance activities related to fixing of errors fall under corrective maintenance.

Program documentation

• It is the description of program and its logic written to support understanding of the program.
• Documentation of program helps to those who use to maintain and extend the program in future.
• A program may be difficult to understand even to the programmers who wrote the code after some days.
• Two type of documentation:programmer documentation,user documentation.
Algorithm to calculate simple interest
1. Start
2. Declare variable p,t,r and si
3. Input p,t and r
4. Calculate si =(p*t*r)/100
5. Print si
6. stop

Flow chart to calculate simple interest


C program to calculate simple interest
#include <stdio.h>
int main()
{
float principle, rate, time, simple_interest;
printf("Enter the principle ");
scanf("%f", &principle);
printf("Enter the rate ");
scanf("%f", &rate);
printf("Enter the time ");
scanf("%f", &time);
simple_interest = (principle * rate * time) / 100;
printf("Simple interest is %f", simple_interest);
return 0;
}

Flowchart TO CALCULATE AREA OF A RECTANGLE


Flowchart to calculate area and circumference of a circle
UNIT 3
The C Language and its Basic Constructs

3.1 History of C language


The base or father of programming languages is ‘ALGOL.’ ‘ALGOL’ introduced the concept
of structured programming to the developer community. In 1967, a new computer
programming language was announced called as BCPL was designed and developed by
Martin Richards, especially for writing system software. Just after three years, in 1970 a new
programming language called ‘B’ was introduced by Ken Thompson that contained multiple
features of ‘BCPL.’

In 1972, a great computer scientist Dennis Ritchie created a new programming language
called ‘C’ at the Bell Laboratories. It was created from ‘ALGOL’, ‘BCPL’ and ‘B’
programming languages. ‘C’ programming language contains all the features of these
languages and many more additional concepts that make it unique from other languages.

‘C’ is a powerful programming language which is strongly associated with the UNIX
operating system. Even most of the UNIX operating system is coded in ‘C’. Initially ‘C’
programming was limited to the UNIX operating system, but as it started spreading around
the world, it became commercial, and many compilers were released for cross-platform
systems.

Today ‘C’ runs under a variety of operating systems and hardware platforms. As it started
evolving many different versions of the language were released To assure that ‘C’ language
will remain standard, American National Standards Institute (ANSI) defined a commercial
standard for ‘C’ language in 1989. Later, it was approved by the International Standards
Organization (ISO) in 1990. ‘C’ programming language is also called as ‘ANSI C’.
1. ALGO→ 1960 2. BCPL➔1967 3. B→1970 4. C→1972 5. ANSI C→1989
6. ANSI/ISO C→1990
3.2 Features of C
C is a general-purpose, structured programming language that is powerful, efficient and
compact.
Some of the feature of C are as follow:
1. Simple - C language is simple and easy to learn. The syntax of C is simple and gives
flexibility to the programmer with its wide variety of in-built functions and data types.
2. Fast- C is a compiler based language. C is power packed with several features but it
is not bloated like some other programming languages, it supports only useful features
which makes the compilation of C file fast.
3. Portable - C is a machine independent language, which means a C program written
one machine can run on another machine without requiring a code change.
4. Extensible - C program supports code modifications and addition of new code to the
already existing programs, this makes C language extensible. It becomes easier to
add new functionalities to the existing C programs.
5. Rich libraries -C libraries are full of useful in-built functions. These functions can be
used frequently to perform some repeated tasks. As a C programmer, you won’t need
to write same code again and again for some trivial repeated tasks; rather you can use
in-built functions to perform the task.
6. Dynamic memory allocation-Dynamic memory allocation means, optimizing and
allocating the memory during runtime. C language supports dynamic memory
allocation, which supports function like free() to free the un-utilized memory space
and other memory management functions such as malloc(), calloc() etc.
7. Reusability -Function is a block of code that is used to perform a specific task. Along
with the in-built predefined functions, C language allows you to create you own
functions that you can create for a reoccurring tasks. This improves the reusability of
the code and avoids the unnecessary writing of the same code again and again.
8. Mid-Level programming language- C language provides the benefits of high level
and low-level languages both. C allows manipulation of hardware just like low level
language and allows high user end functionalities like high-level languages.
9. Supports pointers -C language supports pointers. The pointer in C allows you to
directly interact with the memory.
10. Recursion -C supports recursion. Recursion means a function calls itself. Recursion
provides the features of code reusability and backtracking.

3.3 The C Character set


It is a set of characters that are used as building blocks to form basic program elements.
The C character set consists of
a. Letters/Alphabets
• Uppercase(A-Z)
• Lowercase(a-z)alphabet
b. Decimal digits (0-9)
c. Certain special characters
C-tokens
A token is the smallest unit used in a C program. C has six types of tokens .They are as
follows:

3.4 Keywords and Identifiers


Keywords
Keywords are predefined words whose meaning has already defined to c compilers. These
keywords are used for pre-defined purposes and cannot be used as identifier. The standard
keywords are:

Note:
• A keyword cannot be used as an Identifier .Keywords must be written in lower case.

Identifiers
Identifiers in C are the user-defined words that are used for naming variables, functions,
arrays, structures, etc.
Rules for constructing identifiers in C are given below:

1. The first character of an identifier should be either an alphabet or an underscore.


2. It should not begin with any numerical digit.
3. In an identifier, upper- and lowercase are treated as different
For e.g., the identifier count is not equivalent to Count or COUNT
4. Commas or blank spaces cannot be specified within an identifier.
5. Keywords cannot be represented as an identifier.
6. The length of the identifiers should not be more than 31 characters.
7. Identifiers should be written in such a way that it is meaningful, short, and easy to read.

3.5 Data types


Data types are the type of data stored in a C program. Data types are used while defining a
variable or functions in C.
This determines the type and size of data associated with variables. For example
int num;
Here, num is a variable of int (integer) type. The size of int is 2 or 4 bytes
The data types in C can be classified as follows
1. Primary data type

2) Derived data type


A derived type formed by using the basic types in combination. Array, function, structure,
union and pointers are the derived types

3) User defined data type


The data type that are defined by user is known as user defined data types.
Examples enum (Enumerated data type) and typedef (type definition datatype)

General form of typedef


typedef existing_data_type new_name_for_existing_data_type ;
Example :
typedef int integer ;
integer symbolizes int data type Now, we can declare int variable “a” as integer a rather than
int a .

3.6 Variables, Constants and their declaration


Variable
Variable is defined as a meaningful name given to the data storage location in computer
memory. It is a medium to store and manipulate data. The value of variable can change
during execution of program.
Variable declaration

int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
Rules for defining variables

• A variable can have alphabets, digits, and underscore.


• A variable name can start with the alphabet, and underscore only. It can't start with
a digit.
• No whitespace is allowed within the variable name.
• A variable name must not be any reserved word or keyword, e.g. int, float, etc.
• Variable name are case sensitive .ie. uppercase and lowercase are different. Thus
variable temp is not same as TEMP.
• No two variables of the same name are allowed to be declared in the same scope.

Variable initialization
Initializing variable means specifying an initial value to assign it
1) Compile time initialization
In compile time initialization value is assigned to variable using assignment operator ‘=’
Example:
int a=10,b=20; //declaring 2 variable of integer type
float f=20.8;
char c='A';

2) Runtime initialization
In runtime initialization the value is assigned by using scanf() function.
Syntax:
scanf(“format specifier”,list of address of variable);
eg. scanf(“%d%d”,&a,&b);
Types of Variables in C
1. local variable
2. global variable

1. local variable
A variable that is declared inside the function or block is called a local variable.
Local variables can only be accessed within the function where it is declared.
e.g.
void function1()
{
int x=10;//local variable
}

Program
#include<stdio.h>
int main()
{
int a, b, sum; //local variable
printf("enter to number");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum : %d", sum);
return 0;
}

2. Global variable
A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is accessed by all the functions.
int value=20;//global variable
void function1()
{
int x=10;//local variable
}
Programs
#include<stdio.h>
int sum; // global variable
int main()
{
int a, b; // local variable
printf("enter to number");
scanf("%d %d", &a, &b);
sum = a + b;
printf("Sum : %d", sum);
return 0;
}

Constants
A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.

1. Numeric Constant
It consist of:
a. Integer Constant
A constant written without a decimal point.
b. Real Constant/Floating Point constant
Real constant is written with a decimal point.

2. Character Constant
It consists of
a. Single Character Constant
A single character constant (or simply character constant) contains a single character
enclosed within a pair of single quote marks. Eg. ‘5’ ‘X’ ‘A’ ‘4’ etc.
b. String constant
A string constant is a sequence of characters enclosed in double quotes. The characters may
be numbers, special characters and blank space.eg. “Hello” “green” “305” etc.

Preprocessor directive
Preprocessor directives is a collection of special statement that are executed at the beginning
of compilation process. They are placed in a source program before the main function and
begins with #(Hash).
Some examples of preprocessor directives are
#include //used for standard input and output
#define PI 3.1416 //used for defining symbolic constant PI as 3.1416
#define TRUE 1 //used for defining True as 1
We use preprocessor directive for
• File inclusion
• Conditional compilation

Symbolic constant
Symbolic constant are constant that is represented by a name (symbol) in your program. They
are usually defined as the start of the program.
Whenever you need the constant’s value in your program, you use its name as you would use
a variable name.
Preprocessor directive like #define allow an identifier to have constant value throughout the
program.
The syntax for defining symbolic constant is

Advantages of symbolic constant is modifiability and Understandability


Escape sequences
Escape sequences are non-printable characters used for formatting the output only. It is a
character combination of backslash (\) followed by a letter or by combination of digits. Each
sequences are typically used to specify actions such as carriage return, backspace, line feed or
move cursors to next line. The commonly used Escape sequences are as follows

Type casting
Converting one datatype into another is known as type casting or type-conversion.

Types of Type Casting in C


The process of type casting can be performed in two major types in a C program. These are:

1. Implicit Conversion
2. Explicit Conversion

1. Implicit Conversion
The compiler itself does this type of data type casting in C without any notification from
the user, and thus it is also known as automatic type casting in C. Implementing the
implicit type casting is very easy in a program. We use it to convert the data type of any
variable without losing the actual meaning that it holds.

#include<stdio.h>
int main()
{
int i=20;
float result;
result=i; // implicit conversion
printf("value=%f", result);
return 0;
}

Output
Result=20.000000

2. Explicit Conversion

In this type of conversion one data type is converted forcefully to another data type by the
user. The general rule for cast is

(type-name) expression

Program
#include<stdio.h>
int main()
{
int a=5,b=2;
float result;
result=(float)a/b; // Explict conversion
printf("value=%f",result);
return 0;
}

Output
Result=2.50000

Pseudo code
The pseudocode in C is an informal way of writing a program for better human
understanding. It is written in simple English, making the complex program easier to
understand.
Pseudo code are phrases written ordinary natural language .The pseudo code is not
recognized by computer because they are not written in programming language.

Advantages:
• A beginner can develop the logic to used to solve particular problem without knowing
the syntax of computer language.
• Easy to understand and modify.
• Can be easily converted into program.
• A non-technical professional can easily understand

Disadvantages:
• Not recognized by computer
• No any fix and standard rules to write pseudocode.so one can misunderstand the
pseudo-code written by other programmer.

ASCII
ASCII is the American Standard Code for Information Interchange. It defines an encoding
standard for the set of characters and unique code for each character in the ASCII chart. A
character variable holds ASCII value (an integer number between 0 and 127) rather than that
character itself in c programming. That value is known as ASCII value. for example ASCII
value of ‘A’ is 65 what this means is that, if you assign ‘A’ to a character variable,65 is
stored in that variable rather than ‘A’ itself.
3.7 Input/Output function
C programming language provides many built-in functions to read any given input and to
display data on screen when there is need to output the result. The header file for input/output
functions is stdio.h
The input/output function is classified into two types.
1) Formatted I/O functions
2) Unformatted I/O functions

1) Formatted input/output function


Formatted input function
Formatted Input refers to an input data that can be arranged in a particular format according
to user requirements.
The scanf() function is an example of formatted input function.
scanf() is used in the C program for reading or taking any value from the keyboard by the
user, these values can be of any data type like integer, float, character, string, and many
more.
In scanf() function we use &(address-of operator) which is used to store the variable value
on the memory location of that variable.
Syntax:
scanf(“Format Specifier”, &var1, &var2, …., &varn);
eg. scanf(“%d%d”,&num1,&num2);

Formatted output function


Formatted output functions are used to display data in a particular specified format.
The printf() is an example of formatted output function.
Syntax:
printf(“Format Specifier”, var1, var2, …., varn);
eg. printff(“%d%d”,num1,num2);

Program
#include <stdio.h>
int main()
{
int num1;
// Printing a message on the output screen
printf("Enter a integer number: ");

// Taking an integer value from keyboard


scanf("%d", &num1);

// Displaying the entered value


printf("You have entered %d", num1);
return 0;
}

2) Unformatted I/O functions


Unformatted I/O function do not allow the user to read or display data in a desired format.
These type of library functions basically deal with a single character or string of characters.
The functions getchar(), putchar(),gets(),puts(),getch(),getche(),putch() are considered as
unformatted functions.
a. getchar() and putchar()
The getchar() function reads character type data form the input. The getchar() function reads
one character at a time till the user presses the enter key.
Syntax is :
character_variable=getchar();
where character_variable refers to some previously declared character variable.

putchar() function displays a character to standard output device.


Syntax is:
putchar(character_variable);

Program
#include<stdio.h>
int main()
{
char ch;
printf("Enter the character");
ch=getchar();
printf("Entered characer is :");
putchar(ch);
return 0;
}

b. getch(), getche() and putch()


The function getch() and getche() both reads a single character in a instant. It is typed without
pressing the ENTER key. The difference between them is that getch() reads a character typed
without echoing it on a screen, while getche() reads the character and echoes (displays) it
onto the screen.
Syntax:
character_variable=getch();
characher_varibale=getche();
The function putch() prints a character onto the screen.
Syntax: putch(character_variable);

Program
#include<stdio.h>
int main()
{
char ch1,ch2;
printf("Enter First character:");
ch1=getch();
printf("\nEnter Second character:");
ch2=getche();
printf("\n Firstcharacter is:");
putch(ch1);
printf("\nSecond character is:");
putch(ch2);
return 0;
}

Output
Enter First character:
Enter Second character: b
First character is: a
Second character is: b

At first input getch() function read the character input from the user but that the entered
character was not displayed. But in second input getche() function read the a character from
the user input and entered character was echoed to the user without pressing any key.

c. gets() and puts()


The gets() function is used to read a string of text containing whitespaces, until newline
character is encountered. It can be used as an alternative function for reading strings. Unlike
scanf() functions, it does not skip whitespaces(i.e. It can be used to read multiwords string)
Syntax: gets(string_variable);

The puts() function is used to display the string on the screen.


Syntax: puts(string_variable);

Program
WAP to display your name
#include<stdio.h>
int main()
{
char name[20];
printf("Enter your name:\n");
gets(name);
printf("Your name is:");
puts(name);
return 0;
}

3.8 The C operators


Operator
Operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations.
Operators are used in program to manipulate data and variables.
Operand
The data items on which operators are act upon are called operands.
eg. a + b
• Here, symbol + is known as operator
• a and b are operands
Expression
The combination of variables, constants and operators written according to syntax of
programming language is known as Expression. eg. a+b*c, a*b/5

Types of operators
Types of Operators are classified as:
1. On the basis of no of operands
2. On the basis of function/utility
1. On the basis of no of operands

a. Unary operator
The operator which operates on single operand known as unary operator
++ (increment Operator),-- ( Decrement operator) ,+ ( Unary plus), - (Unary minus) are
unary operator.
eg . ++x, -5, +8 , y- - etc

b. Binary operator
The operator which operates on two operands are known as binary operator. Example:
+(addition), – (subtraction) , /(division) , * (multiplication) , >(greater than) ,<(less than) etc.
eg 3+3, 5>2 , 6*7 , 15-4
c. Ternary operator
The Operators that operates on three operands are known as ternary operator.
Ternary olperator pair “?:” (conditional operator)
2. On the basis of function/utility

According to utility and action, operator are classified into following categories:

a. Arithmetic Operators
b. Relational Operators
c. Logical Operators
d. Assignment Operators
e. Increment and Decrement operator
f. Conditional operator
g. Bitwise Operators
h. special Operators

a. Arithmetic Operators
They are used to perform Arithmetic/Mathematical operations on operands.

Program
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}

Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b = 1

b. Relational Operators
These are used to compare two quantities and depending on their relation take certain
decision. The value of relational operator is either 1(if the condition is true) and 0 (if the
condition is false).

Program
// Working of relational operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d is %d \n", a, b, a == b);
printf("%d == %d is %d \n", a, c, a == c);
printf("%d < %d is %d \n", a, c, a < c);
printf("%d != %d is %d \n", a, b, a != b);
printf("%d >= %d is %d \n", a, b, a >= b);
return 0;
}

Output
5 == 5 is 1
5 == 10 is 0
5 < 10 is 1
5 != 5 is 0
5 >= 5 is 1

c. Logical Operators
Logical Operators are used to compare or evaluate logical and relational expressions and
returns either 0 or 1 depending upon whether expressions results true or false.

Program
// Working of logical operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) is %d \n", result);

result = !(a != b);


printf("!(a != b) is %d \n", result);

result = !(a == b);


printf("!(a == b) is %d \n", result);
return 0;
}

Output
(a == b) && (c > b) is 1
(a == b) || (c < b) is 1
!(a != b) is 1
!(a == b) is 0

d. Assignment Operators
Assignment Operators are used to assign the result of an expression to a variable. The
mostly used assignment operator is “=”.

// Working of assignment operators


#include <stdio.h>
int main()
{
int a = 5, c;
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
return 0;
}

Output
c=5
c = 10
c=5
c = 25
c=5
c=0

e. Increment and Decrement operator


The increment operators (++) causes its operand to be increased by 1 whereas
decrement operator (-- ) causes its operand to be decreased by 1.
They are unary operators (ie. They operate on single operand).
It can be written as
• x++( post increment) or ++x (pre increment)
• x—( post decrement) or - - x (pre decrement)

// Working of increment and decrement operators


#include <stdio.h>
int main()
{
int a = 10, b = 100;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
return 0;
}

Output
++a = 11
--b = 9

Program
#include <stdio.h>
int main()
{
int a = 10;
printf("a = %d \n", a);
printf("++a = %d \n", ++a); //a=a+1 and a is returned after addition
printf("a++ = %d \n", a++); //a=a+1 value of a is returned before addition and then
only increment occur
printf("a = %d \n", a);
return 0;
}

Output
a = 10
++a = 11
a++ = 11
a = 12

f. Conditional operator
The ternary Operator pair “?:” is available in c to construct condtional expressions of
the form.
expression1? expression2: expression3
The expression1 is evaluated first,
• if it is true then the expression 2 is evaluated and its value becomes the value of the
expression.
• If expression1 is false expression3 is evaluated and its value becomes the value of
the expression.

Example:
Consider the following statements.
int a, b;
a=10;
b=15;
max= (a>b)? a: b;
In this example value of b will be assigned to max.
WAP to read two numbers from user and determine the larger number using
conditional operator.
#include<stdio.h>
#include<conio.h>
int main( )
{
int n1,n2,larger;
printf("\nEnter the two numbers:\n");
scanf("%d%d",&n1,&n2);
larger=(n1>n2)?n1:n2;
printf("\nThe largest number is %d",larger);
getch();
return 0;
}

g. Bitwise Operators
The operators which are used for the manipulation of data at bit level. These operators
are used for testing the bits, shifting them right or left.

Assume a = 60 and b = 13 in binary format,


they will be as follows –
n1 = 0011 1100
n2 = 0000 1101
n1&n2 = 0000 1100 =>12 (bitwise AND operator)
n1|n2 = 0011 1101 =>61 (bitwise OR operator)
n1^n2 = 0011 0001 => 49 (bitwise exclusive OR operator)
program
#include<stdio.h>
#include<conio.h>
int main( )
{
int n1=60,n2=13,AND,OR,XOR;
AND= n1 & n2;
OR=n1 | n2;
XOR=n1 ^ n2;
printf("AND=>%d\n",AND);
printf("OR=>%d\n",OR);
printf("XOR=>%d\n",XOR);
getch();
return 0;
}

Output
AND=>12
OR=>61
XOR=>49

bitwise shift operator


i. Left shift <<
This causes the operand to be shifted left by some bit positions.
General form:
Operand<<<3
Eg. n=60, n1=n<<3

ii. Right shift >>


This causes operand to be shifted to the right by some bit positions.
Operand >>n
Eg. n=60, n2=n>>3
WAP to illustrate the shift operator in C program
#include<stdio.h>
#include<conio.h>
int main( )
{
int n1=60,left,right;
left=n1<<3;
right=n1>>3;
printf("left=>%d\n",left);
printf("right=>%d\n",right);
getch();
return 0;
}

Output
left=>480
right=>7

h. special Operators
C supports some special operators. Some of them are
i. comma operator
comma operator are used to link related expressions together. A comma linked list of
expression are evaluated from left to right and the value of right most expression is
the value of combined expression.
Fore.g. n3=(n1=10,n2=50,n1+n2);

program
#include<stdio.h>
#include<conio.h>
int main( )
{
int n1,n2,n3;
n3=(n1=10,n2=50,n1+n2);
printf("n3=%d\n",n3);
getch();
return 0;
}

ii. Sizeof operator


The sizeof is a compile time operator and when used with an operand, it returns the
number of bytes the operand occupies. The operand may ne variable, constant or data
type qualifier.
Examples:
m=sizeof(sum);
n=sizeof(long int);

program
#include<stdio.h>
#include<conio.h>
int main()
{
float num;
printf("Number of bytes allocated =%d",sizeof(num));
getch();
return 0;
}

Output
Number of bytes allocated =4

Operator precedence and associativity


Operator precedence is a predefined rule of priority of operators. If more than one
operators are involved in an expression the operator of higher precedence is evaluated
first. • Associativity indicates the order in which multiple operators of same
precedence executes.
Some related Programs
WAP to calculate area and circumference WAP that asks three coefficients of a
of circle having the radius r should be quadratic equation and calculate its
taken from user. roots.
#include<stdio.h> #include <stdio.h>
#include<conio.h> #include <math.h>
int main() int main() {
{ float a, b, c, discriminant, root1, root2;
float r,area,circum; printf("Enter coefficients a, b and c: ");
printf("Enter the radus of circle"); scanf("%f %f %f", &a, &b, &c);
scanf("%f",&r); discriminant = b*b-4*a*c;
area=3.1416*r*r; root1=(-b+sqrt(discriminant))/(2*a);
circum=2*3.1416*r; root2=(-b-sqrt(discriminant))/(2*a);
printf("\nArea of circle=%f",area); printf("root1 = %f and root2 = %f",
printf("\nCircumference of circle is root1,root2);
%f",circum); return 0;
getch(); }
return 0;
}
WAP to swap two numbers WAP to swap two numbers without using
third variable
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int a,b,temp; int a,b;
a=5; a=5;
b=10; b=10;
printf("Number before swapping a=%d and printf("\nNumber before swappig a=%d and
b=%d",a,b); b=%d",a,b);
temp=a; a=b+a;
a=b; b=a-b;
b=temp; a=a-b;
printf("\nNumber after swapping a=%d and printf("\nNumber after swappig a=%d and
b=%d",a,b); b=%d",a,b);
getch(); getch();
return 0; return 0;
} }

WAP that will convert temperature in WAP to check the given 3 digit number is
centigrade into Fahrenheit. armstrong or not.
#include<stdio.h>
#include<stdio.h> #include<conio.h>
#include<conio.h> #include<math.h>
int main() int main()
{ {
float centi,fah; int num,a,b,c,arm;
printf("\nEnter the temperature in printf("\nEnter the number");
centigrade"); scanf("%d",&num);
scanf("%f",&centi); c=num%10;
fah=1.8*centi+32; b=(num/10)%10;
printf("\nThe equivalent temperature in a=num/100;
fahrenheit is %f",fah); arm=pow(a,3)+pow(b,3)+pow(c,3);
getch(); if(num==arm)
return 0; {
} printf("Entered number is armstrong
number");
}
else
{
printf("Entered number is not armstrong
number");
}
getch();
return 0;
}
WAP to find the reverse of a given (3 WAP to find the sum of digit of given (3
digit) number. digit) number.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int num,a,b,c,rev; int num,a,b,c,sum;
printf("Enter the number"); printf("Enter the number");
scanf("%d",&num); scanf("%d",&num);
c=num%10; c=num%10;
b=(num/10)%10; b=(num/10)%10;
a=num/100; a=num/100;
rev=c*100+b*10+a; sum=a+b+c;
printf("Reverse of given number is printf("Sum of digit of given number is
%d",rev); %d",sum);
getch(); getch();
return 0; return 0;
} }

Questions
1.What are the rules for naming identifier?
2.Differentiate Keywords and Identifier.
3.Define the following terms with suitable examples. Statements, Tokens and
format specifier.
4. What are the different data types available in C? Explain their type qualifier,
conversion character, range of value and storage size in memory occupied by
each type.
5. Why it is necessary to have knowledge of data type in C programming.
Explain all types of data type available in C
6. Explain the necessary rules to define the variable name is C programming.
7. Differentiate between local and global variables
8. Define operator and operand. List the types of operators and explain any five
of them.
9. What is an operator? Explain conditional operator with suitable example.
10. Describe about the unary operator, binary operator and ternary operator with
example.
11. Write a short notes on:
• Escape sequences
• Symbolic Constant
• Pseudo code
• Operator precedence and associativity
• Delimiter
• ASCII
12. Which of the following are invalid variable name and why? Minimum,
First.name, Row total, &name, Doubles , 3rd_row , column_total, float
Control statements

It enable us to specify the flow of program control; ie, the order in which the instructions in a program must be
executed. They make it possible to make decisions, to perform tasks repeatedly or to jump from one section of code
to another.
There are four types of control statements in C:
• Decision making statements
• Selection statements
• Iteration statements
• Jump statements

Decision making statements


1. If statement
2. If else statement
3. If else ladder
4. Nested if else
C if Statement
How if statement works?
The if statement evaluates the test expression inside the parenthesis ().If the test expression is evaluated to true,
statements inside the body of if are executed
syntax
if (test expression)
{
// code
}
Example
Write a program to display a number if a number is negative

Algorithm to check given number is positive or negative


1. Start
2. Declare variable num
3. Input num
4. If(num<0)
print num is negative
5. Stop

program
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number < 0) {
printf(“%d is a negative number”,number);
}
return 0;
}
//fkiwchart
C if...else Statement

• The if statement may have an optional else block. The syntax of the if..else statement is:

Syntax

if (test expression)
{
// run code if test expression is true
}
else
{
// run code if test expression is false
}

flowchart

true false
Test
condition

Code inside body of Code inside body of


if else
Wap to check whether a number is odd or even.
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}

Algorithm to check given no is odd or even

1. Start
2. Declare variable num
3. Input num
4. If(num%2==0)
print num is even
5. else
Print num is odd
6. stop

flowchart
Write a C program to check maximum of two number.
#include<stdio.h>
int main()
{
int a,b;
printf("Enter two numbers:\n");
scanf("%d%d",&a,&b);
if(a>b)
{
printf("%d is a maximum number\n",a);
}
else
{printf("%d is a maximum number\n",b);
}
return 0;
}
C if else ladder

The if...else ladder allows you to check between multiple test expressions and execute different statements.

Syntax of if...else Ladder

if (test expression1)
{ // statement(s)
}
else if(test expression2)
{ // statement(s)
}
else if (test expression3)
{ // statement(s)
}..
else
{ // statement(s)
}

flowchart
Example
#include <stdio.h>
int main()
{
int i = 20;
if (i == 10)
{ printf("i is 10"); }
else if (i == 15)
{ printf("i is 15"); }
else if (i == 20)
{ printf("i is 20"); }
else
{ printf("i is not present"); }
return 0;
}
Example 2
// Program to relate two integers using =, > or < symbol
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}
else {
printf("Result: %d < %d",number1, number2);
}
return 0;
}
Nested if...else

In C programming, a nested if-else statement is when you have an if-else block inside another if or else block. It's
like placing one decision within another decision. You use this when you want to check for a new condition after a
previous condition has already been found true (or false)

Example

#include <stdio.h>
int main()
{
int i =8;
if (i <15)
{

if (i < 10)
{
printf("i is smaller than 10\n");
}
else
{
printf("i is greater than 10");
}
}
else
{
printf(“i is greater than 15”);
}
return 0;
}
Wap to find the greatest among three numbers. Algorithm

#include <stdio.h> 1. Start


int main() { 2. Read the three numbers to be compared, as A, B and C.
int n1, n2, n3; 3. Check if A is greater than B.
printf("Enter three numbers: "); 3.1 If true, then check if A is greater than C.
scanf("%d %d %d", &n1, &n2, &n3); 3.1.1 If true, print 'A' as the greatest number.
if (n1 > n2) { 3.1.2 If false, print 'C' as the greatest number.
if (n1 >n3) 3.2 If false,
{ printf("%d is the largest number.", n1);} then check if B is greater than C.
3.2.1 If true, print 'B' as the greatest number.
else 3.2.1 If false, print 'C' as the greatest number.
{ printf("%d is the largest number.", n3);} 4. End
}
else {
if (n2 > n3)
{printf("%d is the largest number.", n2);}
else
{ printf("%d is the largest number.", n3);}
}
return 0;
}

flowchart
Q. Wap to find the roots of quadratic equation
#include <math.h>
#include <stdio.h>
int main()
{
float a, b, c, discriminant, root1, root2;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f", &a, &b, &c);
discriminant = b * b - 4 * a * c;
if (discriminant > 0) {
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %f and root2 = %f", root1, root2);
}
else if (discriminant == 0) {
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %f;", root1);
}
else {
printf(“roots are imaginary”);
}
return 0;
}
Flow chart of program to find roots of quadratic equation

start

Declare a,b,c,r1,r2,d

Read a,b,c

Calculate d=sqrt(b*b-4ac)

true
Print r1=(-b+d)/2a
d>0 r2=(b+d)/2a

false

true
d==0
Print r1=r2=-b/2a

false

true
d<0 Print imaginary number
Switch case
Switch statement in C tests the value of a variable and compares it with multiple cases. Once the case match is found,
a block statements associated with that particular case is executed. ... If case match is NOT found, then the
default statement is executed, and the control goes out of the switch block.

Syntax
switch (expression)
{
case constant1:
// statements break;
case constant2:
// statements break;
case constant3:
// statements break;
Case constantn:
//statement break;

default:
// default statements
}

flowchart
Simple calculator program using switch case
#include <stdio.h>
int main() {
char operator;
float first, second;
printf("Enter an operator (+, -, /,*):" );
scanf("%c", &operator);
printf("Enter two operands: ");
scanf(“%f %f", &first, &second);
switch (operator) {
case '+':
printf("%f + %f = %f”, first, second, first + second);
break;
case '-':
printf ("%f - %f = %f ", first, second, first - second);
break;
case '*':
printf("%f * %f = %f ",first, second, first * second);
break;
case '/':
printf ("%f / %f = %f ", first, second, first / second);
break;
default:
printf("Error! operator is not correct");
}
return 0;
}
Flowchart for simple calculator using switch case
Example

#include <stdio.h>
int main () {
char grade = 'B‘;
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
Example2
#include<stdio.h>
int main()
{
int day;
printf("Enter any number (1 to 7)");
scanf("%d",&day);
switch(day)
{
case 1: printf("Today is Monday");
break;
case 2: printf("Today is Tuesday");
break;
case 3: printf("Today is Wednesday");
break;
case 4: printf("Today is Thursday");
break;
case 5: printf("Today is Friday");
break;
case 6: printf("Today is Saturday");
break;
case 7: printf("Today is Sunday");
break;
default: printf("Only enter value 1 to 7");
}
return 0;
}
ITERATION STATEMENTS

In programming, loops are used to repeat a block of code until a specified condition is met.
C programming has three types of loops.
✓ for loop
✓ while loop
✓ do...while loop

While loop
1. The while loop evaluates the test expression inside the parenthesis ().
2. If the test expression is true, statements inside the body of while loop are executed. Then, the test
expression is evaluated again.
3. The process goes on until the test expression is evaluated to false.
4. If the test expression is false, the loop terminates (ends).

Syntax

while(testExpression) {
// the body of the loop
}

Flowchart

false
Test
expression

true

While loop body


Wap to Print numbers from 1 to 10 using while loop
#include <stdio.h>
int main()
{
int i = 1;

while (i <= 10)


{
printf("%d\n", i);
++i;
}
return 0;
}
Armstrong Number:
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the
number itself.
In other word “A number is Armstrong if it is equal the sum of cube of its digits.”
For example,
153 is an Armstrong number because
13 + 53 + 33 = 1 + 125 + 27 = 153
124 is not an Armstrong number because
13 + 23 + 43= 1 + 8 + 64 = 73

Program to check given number is armstrong or not Algorithm


#include<stdio.h>
Int main() Step 1: Start
{ Step 2: Declare Variable sum, temp, num
int n, num,r,ans=0; Step 3: Read num from User
printf("Enter a positive integer: "); Step 4: Initialize Variable sum=0 and
scanf("%d", &n); temp=num
num=n; Step 5: Repeat Until num>0
while(n>0) 5.1 r=num%10
{ 5.2 sum=sum + r*r*r
r=n%10; 5.3 num=num/10
ans=ans+r*r*r; Step 6: IF sum==temp
n=n/10; Print "Armstrong Number"
} ELSE
if(num==ans) Print "Not Armstrong Number"
printf("%d is an Armstrong number.",num); Step 7: Stop
else
printf("%d is not an Armstrong number.",num);
return 0 ;
}
Flowchart for Armstrong number

start

Declare variable sum=0,n,r,N

Read n

N=n

While If
n>0 sum==N

r=n%10
Sum =sum +r*r*r Print Print not
n=n/10 armstrong Armstrong

end
Wap to find the Sum of digits of a given number
#include<stdio.h>
int main()
{
int n,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}

//flowchart to find sum of digits of a given number


Q.Wap to check given number is Palindrome number or not.
#include <stdio.h>
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);
return 0;
}
Do while loop

The do..while loop is similar to the while loop with one important difference. The body of do...while loop is
executed at least once. Only then, the test expression is evaluated.

Syntax

do
{
// the body of the loop
}
while (testExpression);

flowchart

Do while body

false
true
Test
expresession

Example
#include <stdio.h>
int main()
{
int i=1;
do
{
printf(“%d\n”,i);
i++;
}
while(i <=100);
return 0;
}
Write a program to print odd numbers from 1 to 100 using do while loop
#include<stdio.h>
int main(){
int c =1;
do{
if(c%2==1){
printf(“%d\n”,c);
}
c++;
}
while(c<=100);
return 0;
}
for loop

• In the for loop initialization statement is executed only once.


• Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is terminated.
• However, if the test expression is evaluated to true, statements inside the body of the for loop are executed,
and the update expression is updated.
• Again the test expression is evaluated.
• This process goes on until the test expression is false. When the test expression is false, the loop
terminates.

syntax
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
}

flowchart

start

false
Test
condition

true

Body inside for looop

update
write a program to print numbers from 1 to 10 using for loop.

#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d\n", i);
}
return 0;
}

Q.Write a program to find the sum from 1 to 100 using for loop.

#include<stdio.h>
Int main()
{
int i,sum=0;
for(i=1;i<=100;i++)
{
sum=sum+i;
}
printf(“Sum of numbers from 1 to 100 =%d”,sum);
return 0;
}

Q.Write a c program to find sum from 1 to n where n is given by user.

#include<stdio.h>
Int main()
{
int i,sum=0,n;
printf(“enter the value of n”);
Scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum of nos 1 to n =%d”,sum);
return 0;
}
Flow chart of program to find the sum of n numbers from 1 to n where n is given by user.

start

Declare variable sum=0,n,i

Read n

false
If i<=n

true

Print sum

sum = sum +i
i = i+1

end
Flow chart to print sum of even numbers from 1 to 100

start

Declare variable sum=0,i

false
If i<=100

true

Print sum
false
If
i%2==0

true

end
Sum=sum+i

i=i+1
Q.Wap to reverse a number
#include <stdio.h>
int main() {
int n, reverse = 0, remainder;
printf("Enter an integer: ");
scanf("%d", &n);
while (n > 0) {
remainder = n % 10;
reverse = reverse * 10 + remainder;
n =n/10;
}
printf("Reversed number = %d", reverse);
return 0;
}
Q.Wap to find the factorial of a given number.

#include <stdio.h>
int main()
{
int n, i;
int fact = 1;
printf("Enter postive integer: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
fact = fact* i;
}
printf("Factorial of %d = %d", n, fact);
return 0;
}

C program to find sum of all odd numbers between 1 to N using for loop

#include <stdio.h>

int main() {
int counter, N, sum = 0;
printf("Enter a Positive Number\n");
scanf("%d", &N);

for(counter = 1; counter <= N; counter++) {

if(counter%2 == 1) {
sum = sum + counter;
}
}
printf("Sum of all Odd numbers between 1 to %d is %d", N, sum);

return 0;
}
C program to count number of even numbers from 1 to 100.

#include <stdio.h>

int main() {
int i, evencount=0;

for(i= 1; i<= 100; i++) {

if( i%2 == 0) {

evencount=evencount+1;
}
}
printf(“total no of even count is %d”,evencount);

return 0;
}
Jump statement in c program

Jump Statement in C is used in C programming to transfer the program control from one part of the code to another.
C provides three types of Jump Statements in C, namely, break, continue, and goto. The break statement is used to
terminate the execution of a loop or switch statement.Mainly thery are

• Break
• Continue
• goto

Break statement

• The break statement ends the loop immediately when it is encountered.


• Its syntax is:

break;

Example of break statementExample of break statement

#include <stdio.h> Output


int main () 1
{ 2
int a; 3
for (a = 1; a <=10; a++) 4
{
if ( a == 5)
{
break;
}
printf("%d\n",a);
}
return 0;
}
continue statement

• Like a break statement, continue statement is also used with if condition inside the loop to alter the flow of
control.
• When used in while, for or do...while loop, it skips the remaining statements in the body of that loop and
performs the next iteration of the loop.
• Unlike break statement, continue statement when encountered doesn’t terminate the loop, rather interrupts
a particular iteration.
Syntax is
Continue;
Example of continue statement#include <stdio.h>
int main () output
{ 1
int a; 2
for (a = 1; a <=10; a++) 3
{ 4
if ( a== 5) 6
{ 7
continue; 8
} 9
printf("%d\n",a); 10
}
return 0;
}
Nested for loop
The syntax for a nested for loop statement in C is as follows −
for ( init; condition; increment )
{
for ( init; condition; increment )
{ statement(s);
}
statement(s);
}
Q.Wap to print the series Sum = 1+1/2+ 1/3+……+1/n
#include<stdio.h>
int main()
{
int i,N;
float sum;
printf("Enter the value of N: ");
scanf("%d",&N);
sum=0.0;
for(i=1;i<=N;i++)
{ sum = sum + (1/(float)i);
}
printf("Sum of the series is: %f\n",sum);
return 0;
}

Q.Write a C program to find sum of the square of all natural numbers from 1 to N.
Series: 1^2+2^2+3^2+4^2+..N^2
#include<stdio.h>
int main()
{
int i,n, sum;
printf("Enter the value of n: ");
scanf("%d",&n);
sum=0;
for(i=1;i<=n;i++){
sum= sum+ (i*i);
}
printf("Sum of the series is: %ld\n",sum);
return 0;
}
Q.Write a program to print the series Sum= x + x^2 + x^3+……+ x^n
#include<stdio.h>
#include<math.h>
int main()
{
int i, sum,x,n;
printf("Enter the value of x: ");
scanf("%d",&x);
printf("Enter the value of n: ");
scanf("%d",&n);
sum=0;
for(i=1;i<=n;i++){
sum= sum + pow(x,i);
}
printf("Sum of the series is: %ld\n",sum);
return 0;
}

Q.Write a program to print series Sum = 1 /1! + 1/2! +1/3! +…..1/n!


#include <stdio.h>
int main()
{int i,n,fact;
float sum=0.0;
fact =1;
printf("Enter the value of n: ");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
fact =fact*i;
sum = sum + ( 1 /(float) fact );
}
printf("Sum of the series is: %f\n",sum);
return 0;
}

Pattern printing
#include <stdio.h>
*
int main() {
**
int i, j;
***
****
for (i = 1; i <= 5; ++i) {
**** *
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
#include <stdio.h> 1
int main() { 12
int i, j, rows; 123
printf("Enter the number of rows: "); 1234
scanf("%d", &rows); 12345
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}

#include <stdio.h>
*
**
int main() {
***
int i, j;
****
for (i = 1; i <= 5; ++i) {
**** *
for (j = 1; j <= i; ++j) {
printf("* ");
} printf("\n");
}
return 0;
}
#include <stdio.h>
12345
int main() {
1234
int i, j, rows;
123
12
for (i = 5; i >= 1; --i) { 1
for (j = 1; j <= i; ++j) {
printf("%d ", j);
}
printf("\n");
}
return 0;
}

//FLOYD’S TRIANGLE
#include <stdio.h> 1
int main() { 23
int rows, i, j, number = 1; 456
printf("Enter the number of rows: "); 7 8 9 10
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
for (j = 1; j <= i; ++j) {
printf("%d ", number);
++number;
}
printf("\n");
}
return 0;
}
#include<stdio.h> A
Int main() BB
{ CCC
int i,j,n; DDDD
printf("Enter the no of lines\n"); EEEEE
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
printf("%c",i+64);
}
printf("\n");
}
return 0;
}
#include<stdio.h>
int main()
{ 1

int i,j,k,n;

printf("Enter number of rows");


1 2
scanf("%d",&n);

for(i=1;i<=n;i++)
{ 1 2 3
for(j=1;j<=n-i;j++)
{
printf(" "); 1 2 3 4
}
for(k=1;k<=i;k++)
{
printf("%d",k);
}
printf("\n");
}

}
Goto statement

• The goto statement is a jump statement which is sometimes also referred to as unconditional jump
statement. The goto statement can be used to jump from anywhere to anywhere within a function.

Example1
#include <stdio.h>
int main()
{

goto label1;
printf("hello world");
label1:
printf("hello science");
return 0;
}
Example2
#include <stdio.h>
int main()
{
int n = 4;
if (n % 2 == 0)
{
goto label1;
}
else
{
goto label2;
}
label1:
printf("even");
return 0;
label2:
printf("odd");
return 0;
}
UNIT 4
Arrays and Structures in C

4.1 Array
An array is the collection of similar type of data items stored at contiguous memory locations
under a common variable name.
Arrays are the derived data type in C programming language which can store the primitive
type of data such as int, char, double, float, etc.
The array is the simplest data structure where each data element can be randomly accessed by
using its index number.
So to be an array,
• All elements must be of same data type.
• All elements are stored in contiguous memory location.
For example, if you want to store 100 integers, you can create an array for it.
int num[100];
Syntax:
datatype arrayName [arraySize];
Eg. int a[10];
float b[5];
char name[20];

Why do we use array in programming language?


If we want many elements of similar type than it is not feasible to declare all variables and
also manipulate these elements. So in this case we use array.
For example, if we want 100 integer variables, then instead of writing all 100 variables, we
use array like int a[100]. Here 100 integer elements a[0], a[1], a[2] ......... a[99] are declared.
Limitation of Array
Memory allocation in array are static in nature. Which means memory is allocated before the
execution of program begins (During compilation).In this type of allocation the memory
cannot be resized after initial allocation.
So it has some limitations.
• Wastage of memory
• Overflow of memory
eg. int a[100];
Here, the size of an array has been fixed to 100.If we just enter to 10 elements only, then
their will be wastage of 90 memory location and if we need to store more than 100 elements
there will be memory overflow.
Why array is called static data type?
The array is called static data type because when the size of array is once allocated ,it cannot
be modified.So that maximum size needed must known in advance. eg. int a[100]; Here, the
size of an array has been fixed to 100 and cannot be change during program execution.
Types of array
1. One dimensional Array
2. Multidimensional Array

1. One dimensional Array


An array where data is arranged in a single dimension is called one dimensional array.
Elements of an array can be represented either as a single row or single column. one-
dimensional arrays are also called as Single dimensional arrays, Linear Arrays or simply 1-D
Arrays.
Declaration:
datatype arrayName [arraySize];
eg. int num[10];
Here, int is a data type and num is the name of the array and 10 is the size of the array. It
means num can only contain 10 elements of int type.
Initialization of 1-D array
After the array is declared it must be initialized, otherwise it will contain garbage value (any
random value) .An array can be initialized at either compile time or runtime.
a. Compile time initialization
General form:
data_type array_name[size]={list of values};
The value in the list are separated by commas.
Example:
int mark[5] = {19, 10, 8, 17, 9}; //integer array initialization
float area[5]={33.4,55.6,88.9,77.8,5.5}; //float array initialization
Note: It is also possible to initialize array without defining its size.
int mark[] = {19, 10, 8, 17, 9};
In this case compiler determines the size of array by calculating the number of elements in an
array.
Accessing Array Elements
We can access the elements of an array by giving the name and proper subscript inside the
bracket.
int mark[5] = {19, 10, 8, 17, 9};
Considering base address 1000, now array elements can be illustrated as:

Here, mark[0] is 19 which is stored at 1000.


Similarly,
mark[1]=10,
mark[ [2]=8,
mark[ [3]=17,
mark[ [4]=9

Example 1
#include <stdio.h>
int main()
{
int i;
int mark[5] = {19, 10, 8, 17, 9}; //declaration and initialization of array
for(i=0;i<5;i++)
{
Printf(“\t%d”,mark[i]);
}
return 0;
)

Output
19 10 8 17 9

Example 2
#include <stdio.h>
int main()
{
int arr[5]={2,4,6,8,10};
printf(“%d”,arr[0]);
printf(“%d”,arr[1]);
return 0;
}

b. Runtime initialization
An array can also be initialized at runtime using scanf() function. This Approach is used for
initializing large arrays with user specified values.
#include <stdio.h>
int main()
{
int mark[5];
int i;
printf("\nEnter the array elements");
for(i=0;i<5;i++)
{
scanf("%d",&mark[i]);
}
printf("\nArray elements are");
for(i=0;i<5;i++)
{
printf("%d",mark[i]);
}
return 0;
}

2. Multidimensional Array
Multidimensional array are those who have two or more than two dimensions.
Multi dimensional array can be of two dimensional array or three dimensional array or four
dimensional array or more.

Declaration
datatype array_name[s1][s2][s3]….[sn]
where, sn is the size of nth dimension.
Example:
int num[3][5][12]; Here, num is a three dimensional array.
Two dimensional array
Most popular and commonly used multi dimensional array is two dimensional array. The 2-D
arrays are used to store data in the form of table. We also use 2-D arrays to create
mathematical matrices.
Declaration:
data_type array_name[row_size][column_size];
eg. int arr[3][3];
It creates two dimensional array to store 9 elements of integer type. There are 3 rows and 3
columns in array matrix

Initialization of 2-D array


a. Compile time initialization
In compile time initialization, user has to enter the details in the program itself. Two
dimensional array may be initialized by following their declaration with a list of values
enclosed in braces.
Example:
int arr[3][3]={ {2,4,6},{8,9,12},{15,16,18}};

Similarly for,
int arr[2][3]={{1,2,3},{5,8,5}};
int arr[2][3]= {1,2,3,55,8,5};
1 2 3
5 8 5
int arr[3][4]={{65,85,75,50},{67,65,45,75},{35,5,60,50}};
Note: When array is completely initialized with all values, explicitly, we need not specify the
size of the first dimension. That is the statement,
int arr[ ][ 3]={{2,4,6},{8,9,12},{15,16,18}}; is permitted.
Example:
#include<stdio.h>
int main()
{
int i,j;
int a[3][3]={{12,14,16},{5,7,15},{15,25,45}};
printf("The matrix is\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",a[i][j])
}
printf("\n");
}
return 0;
}

b) Runtime initialization
Runtime initialization is used for initializing array with user specified values. An array can
also be initialized at runtime using scanf() function.
Example:
Program to input 3*3 matrix and display it.
#include<stdio.h>
int main()
{
int i,j;
int arr[3][3];
printf("Enter the elements of matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("Elements of matrix are\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
printf("\n");
}
return 0;
}

Program of One Dimensional Array


WAP to input 10 number in an array and WAP to input n elements in array and
display it. display them.
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int values[10],i,n; int values[100],i,n;
printf("Enter 10 array elements\n"); printf("Enter value of n: ");
for(i = 0; i <10; i++) scanf("%d",&n);
{
scanf("%d", &values[i]); for(i = 0; i <n; i++)
} {
printf("Displaying integers:\n "); scanf("%d", &values[i]);
for( i = 0; i < 10; i++) }
{ printf("Displaying integers:\n ");
printf("%d\n", values[i]); for( i = 0; i < n; i++)
} {
getch(); printf("%d\n", values[i]);
return 0; }
} getch();
return 0;
}

WAP to read n elements in array and WAP to input n numbers in an array and
display them in reverse order. find sum of all elements and find its
average
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
int main() int main()
{ {
int values[100],i,n; int n,i;
printf("Enter value of n: "); float num[100],sum=0,avg;
scanf("%d",&n); printf("Enter number of array elements \n");
printf("Enter %d array elements\n",n); scanf("%d",&n);
for(i = 0; i <n; i++) printf("Enter %d elements\n",n);
{ for(i=0;i<n;i++)
scanf("%d", &values[i]); {
} scanf("%f",&num[i]);
printf("Displaying integers:\n "); }
for( i = n-1; i >= 0; i--) for(i=0;i<n;i++)
{ {
printf("%d\n", values[i]); sum=sum+num[i];
} }
getch(); avg=sum/n;
return 0; printf("the sum of all element of array is
} %f\n",sum);
printf("Average=%f\n",avg);
getch();return 0;

WAP to input n numbers in an array WAP to input n numbers in an array and


and find the sum of all even numbers find the sum of all even numbers and odd
and count them. numbers and count their numbers and
display them.
Wap to input n elements in an array and find sum of all even elements of
an array
Wap to input n numbers in an array and Write a program to read n
display the highest element in an array number from keyboard and find
the smallest and largest number
using array.
WAP to input n elements in an array and WAP to read n numbers in an array
count the number of odd elements and and display the sum of even numbers
even elements in an array only and product of odd numbers only.
WAP to input n elements in array and
copy to another array.
WAP to check whether the given number is WAP to add contents of two arrays
present in a array or not. into another
WAP to input n number in an array and sort them in Ascending order
WAP to input n number in an array and sort them in Descending order.
WAP to Store Fibonacci series of 10 WAP to store n numbers in an array and
terms in array and display them. display prime numbers stored in array and
calculate the sum of those prime numbers

Assignment
1. WAP to read n numbers in an array and find the sum of even numbers and odd
numbers and display the result.
2. WAP to read the marks of 10 students calculate and display the average marks and
deviation of marks of each student from average marks
3. WAP to check whether the given number is present in a array or not and if present
find its position.
Program of Two Dimensional Array

WAP to input 3*3 matrix and WAP to input m*n order matrix and display
display it. it.
Write a program to find the sum of all Write a program to read matrix of order
elements of 3 x 3 matrix m*n from user and multiply each element
of matrix by 3
#include<stdio.h>
#include<conio.h>
WAP to input m*n order matrix and find Write a program to enter values in 3*3
its transpose order matrix and compute the sum of
odd elements
Write a program to read a matrix and WAP to read m*n matrix and find the
find the sum of all digits in its main sum of diagonal elements from right
diagonal.
WAP to input m*n order matrix and find WAP to input m*n order matrix and find
Largest element. Smallest element
WAP to input m*n matrix and find sum WAP to input m*n matrix and find sum
of each row of each column
WAP to input m*n order matrix and WAP to input m*n order matrix and
convert it to the upper triangular matrix convert it to the lower triangular matrix
Write a program to add two 3X3 matrix. WAP to read two 3*3 matrix and
Display the sum stored in third matrix. multiply them.

Questions
Array
1. What is array? Why do we use array in programming language?
2. Write the disadvantage of arrays.
3. How can you initialize one dimensional array at compile time and run time? Explain
with suitable example.
4. Why array is important in programming? How can you initialize different types of
arrays? Explain 2-dimensional array in C
Assignment
1. WAP to read the matrix of size 2*3 from user and display it to the screen.
2. WAP to input m*n order matrix and find sum of all even and odd numbers and count
them.
3. Write a program to read values of 3*3 order matrix the compute the sum of even
elements.
4. WAP a Program to read two 3*3 matrix and subtract them
5. WAP to test whether given two matrix are equal or not.
6. WAP to input m*n order matrix and convert it to the lower triangular matrix.

4.3 Character arrays (Strings)


• String is an array of character.
• Strings are sequence of characters stored in consecutive memory location.
• Each character in string occupies one byte of memory.
• String always terminated with ‘\0’(NULL character).
• Character may be letter, special symbol or numeric value.
• String format specifier is %s.

Note: Character format specifier is %c.


Declaration:
char string_name [size];
Eg. Char name[5];

Note: When the compiler assigns a character string to character array, it


automatically supplies a null character (‘\0’) at the end of string. Therefore, size
should be equal to maximum number of characters in string plus one.

Initialization of strings
a. Compile time initialization
char string_name [size]= ”list of character”;
Char name[6]=“patan”;
Or
char string_name[size]={list of character};
Char name[6]={‘p’, ’a’ , ’t’, ’a’ , ’n’ , ’\0’};
Char name[]=“patan”;

Program to illustrate compile time initialization of string


#include<stdio.h>
#include<conio.h>
int main()
{
char str[6]={'H','e','l','l','o','\0'};
char name[5]="ram";
printf("Greeting :%s",str);
printf("\nName: %s",name);
getch();
return 0;
}

Output
Greeting:Hello
Name:ram

b. Runtime initialization
The input function scanf() can be used with %s format specification to read string.
Example:
char name[20];
scanf(“%s”,name);

Limitation: Here, string variable takes only single word, It is because when
whitespace is encountered the scanf() function terminates,

Example:
Enter your name: Dennis Ritchie
Your name is: Dennis

To overcome this problem the gets() function is used to read a string of text
containing whitespaces, until newline character is encountered.
#include<stdio.h>
#include<conio.h>
int main()
{
char name[20];
printf("Enter your name:");
gets(name);
printf("Your name is:");
puts(name);
getch();
return 0;
}

Output:
Enter your name: Dennis Ritchie
Your name is: Dennis Ritchie

Array of strings
In C programming String is a 1-D array of characters and is defined as an array of
characters.
But an array of strings in C is a two-dimensional array of character types.

Eg. char name[5][6];


Here, first dimension denotes the number of strings in the array and the second
dimension denotes the maximum length of the string.
In above declaration, we can store 5 strings, each can store maximum 5 characters.
Last 6th space is for null terminator in each string.

Similarly,
char name[3][10] = {
"spike",
"tom",
"jerry"
};

Program to input name of 5 students and display it


#include<stdio.h>
#include<conio.h>
int main()
{
int i;
char name[5][20];
printf("Enter the name of 5 students\n");
for(i=0;i<5;i++)
{
puts(name[i]);
}
getch();
return 0;
}
String handling function
C programming language provides a set of pre-defined functions called string
handling functions to work with string values.
The string handling functions are defined in a header file called string.h.

The following table provides most commonly used string handling function and their
use
1. strlen()
The strlen() function calculates the length of a given string.The strlen() function
takes a string as an argument and returns its length.

Syntax: integer_variable =strlen(string);

Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char str[20];
int len;
printf("Enter the string:");
gets(str);
len=strlen(str);
printf("The length of a string is %d",len);
getch();
return 0;
}

Output:
Enter the string : ramesh
The length of string is 6

2. strcpy()
This function copies one string to another.
The syntax is :
strcpy(destination_string,source_string);
i.e. strcpy(str2,str1) means the content of str1 is copied to str2.

3. strcat()
This function concatenates two strings i.e it appends one string at the end of another.
This function accepts two strings as parameters and stores the contents of second
string at the end of first.
Its syntax is : strcat (string1,string2);
ie.string1=string1+string2
4. strcmp()
This function compares two strings to find out whether they are same or different.
This function accepts two strings as parameters and returns an integer whose value is
i) less than 0 if the first string is less than second
ii) equal to 0 if both are same
iii) greater than 0 if first string is greater than second
Its syntax is: integer_variable=strcmp(string1,string2);
5. strrev()
This function is used to reverse all characters in a string except null character at the
end of string. The reverse of string “abc” is “cba”.
It’s syntax is strrev(string);
6. strlwr()

7. strupr()
This function converts the lowercase string into uppercase.
Question
What is string? Explain any seven functions related to string

Program of string
WAP to print the following pattern: WAP to print the following pattern
N 1N
NE 2EE
NEP 3PPP
NEPA 4AAAA
NEPAL 5LLLLL

#include<stdio.h>
#include<string.h>
int main(){
int i,j;
char str[] ="NEPAL";
for(i=0;i<5;i++){
for(j=0;j<=i;j++)
{
printf("%c\t", str[j]);
}
printf("\n");
}
return 0;
}

WAP to print the following pattern WAP to print the following pattern

P PROGRAMMING
PR PROGRAMMING
PRO PROGRAMMIN
PROG PROGRAMMI
PROGR PROGRAMM
PROGRA PROGRAM
PROGRAM PROGRA
PROGRAMM PROGR
PROGRAMMI PROG
PROGRAMMIN PRO
PROGRAMMI NG PR
P
#include<stdio.h> #include<stdio.h>
#include<string.h> #include<string.h>
int main(){ int main(){
int i,j; int i,j;
char str[20] ="PROGRAMMING"; char str[20] ="PROGRAMMING";
for(i=0;i<11;i++){ for(i=11;i>=0;i--){
for(j=0;j<=i; j++) for(j=0;j<=i; j++)
{ {
printf("%c\t",str[j]); printf("%c",str[j]);
} }
printf("\n"); printf("\n");
} }
return 0; return 0;
} }

Write a program to check whether WAP to sort n students name in


the given string is palindrome or alphabetical order.
not.(palindrome is a word which
reads same from left to right and
right to left.eg LIRIL,MADAM etc.

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<string.h>
#include<string.h> int main()
int main() {
{ int i,j,n;
char str1[20],str2[20]; char str[25][25],temp[25];
printf("Enter the string\n"); puts("How many strings u are going to
gets(str1); enter?: ");
strcpy(str2,str1); scanf("%d",&n);
strrev(str2);
if(strcmp(str1,str2)==0) puts("Enter Strings one by one: ");
{ for(i=0;i<=n;i++)
printf("String is palindrome"); gets(str[i]);
} for(i=0;i<=n;i++)
else for(j=i+1;j<=n;j++){
{ if(strcmp(str[i],str[j])>0)
printf("String is not palindrome"); {
} strcpy(temp,str[i]);
getch(); strcpy(str[i],str[j]);
return 0; strcpy(str[j],temp);
} }
}
printf("Order of Sorted Strings:");
for(i=0;i<=n;i++)
puts(str[i]);

return 0;
}
Write a program to read n employees names and display them in alphabetical order

4.4 Structure and Union


Structure
• Structure is a collection of different or similar data types variable under a common
variable name.
• Structure is a convenient tool for handling a group of logically related data items.

Why structure is needed?


Suppose we need to store the data of students like name, address, class, rollno, age etc.
One way of doing this would be creating a different variable name, age, address to store these
information separately.
However when we need to store the data of multiple students, in that case we would need to
create these several variables again for each student .This is such a big headache to store data
in this way.
We can solve this problem easily by using structure. We can create a structure that has
members name, address, class, rollno, age etc. and then we can create the variables of this
structure or each student.
Example:
struct student
{
char name[20];
char address[20];
int class;
int rollno;
int age;
}
Now multiple variable of struct student type can be declared as:
int main()
{
struct student st1, st2,st3. ...... stn;
...........................
return 0;
}

Defining structure
The general format or syntax to create structure is:
struct structure_name
{
data_type member1;
data_type member2;
.....................
.....................
data_type membern;
};
For example
struct student
{
char name[20];
int roll;
float marks;
};
Here a derived type struct student is defined. Student is a structure name and name, roll,
marks, are called structure elements or members. Each of these members belongs to different
data types.

Declaration of structure

Accessing Member of Structure


How members of the structure are accessed? Show it with example. [PU: 2017 Spring]

To access any member of a structure, we use the dot operator (.) .

Syntax: structure_variable.member
Here structure variable refers to the name of structure type variable and member refers to
name of member within structure.

Array of structure
Array of structure is the collection of multiple structures variables where each variables
contain information about different entities.
Let us consider the structure employee

struct employee
{
char name[20];
int id;
float salary;
};
Normally, when we want to store the record of multiple employee ,Let’s suppose 10 ,we have
to declare 10 different structure variables such as e1,e2,e3……. e9, e10.
By using array of structure we can simply declared in following ways;

Example
Array of structures that stores information of 10 employees and display it.
#include<stdio.h>
#include<conio.h>
struct employee
{
char name[20];
int id;
float salary;
};
int main()
{
int i;
struct employee e[10];
printf("Enter the Information of 10 employee\n");
for(i=0;i<10;i++)
{
printf("Enter the Employee id\n");
scanf("%d",&e[i].id);
printf("Enter the name of employee\n");
gets(e[i].name);
printf("Enter the salary of employee\n");
scanf("%f",&e[i].salary);
}
printf("\nEmployee Information List:");
for(i=0;i<10;i++)
{
printf(" \nId:%d\tName:%s\tsalary:%f",e[i].id,e[i].name,e[i].salary);
}
getch();
return 0;
}

Nested structure ( Structure as structure member or Embedded structure)

What is nested structure? [PU: 2013 fall, 2014 spring, 2015 spring]

The structure within structure is called Nested structure. In other words the individual
members of structure can be other structure as well.
Let us consider structure date which has members day, month and year. This structure can be
nested another structure say employee.ie. structure date is member of another structure
employee.

Eg.
struct date
{
int day;
int month;
int year;
};
This structure can be nested within another structure as its member.
structure employee
{
char name[50];
int id;
struct date dob;
float salary;
}e;

Accessing member of nested structure


1. Write a program enlightening how to access the nested structure components.
[PU: 2012 fall]
2. How the members of the nested structure are accessed? Show it with example.
[PU: 2016 fall]

#include<stdio.h>
#include<conio.h>
struct date
{
int day;
int month;
int year;
};
struct employee
{
char name[20];
int id;
struct date dob;
float salary;
}e;
int main()
{
printf("Enter the name of employee");
scanf("%s",e.name);
printf("Enter ID of employee");
scanf("%d",&e.id);
printf("Enter the year of birthday\n");
scanf("%d",&e.dob.year);
printf("Enter the month of birthday\n");
scanf("%d",&e.dob.month);
printf("Enter the day of birthday\n");
scanf("%d",&e.dob.day);
printf("Enter the salary of employee\n");
scanf("%f",&e.salary);
printf("Detail information of employee is\n");
printf("Name\tId\tDate\tMonth\tYear\tsalary\n");
printf("%s\t%d\t%d\t%d\t%d\t%f",e.name,e.id,e.dob.day,e.dob.month,e.dob.year,e.salary);
getch();
return 0;
}
In nested structure the member within inner structure is accessed as:
structure_variable.member.submember;

In above example,
The member within date are accessed as
e.dob.day;
e.dob.month;
e.dob.year;

Union
Union is a derived data type which allows to store number of variables of different data types
in same memory location.
Unions are similar to structure but there is only difference in terms of storage. In structures,
each member has its own memory location but all member of the union use the same storage
location. Due to sharing of a common memory location, all the members of union cannot
accessed at a time.
The memory occupied by the union will be the memory sized occupied by a member which
requires largest memory space among members.

Eg.
union student
{
char name[20];
int roll;
float marks;
};

Here, memory required for member name is 20 bytes, roll is 2 bytes and marks is 4 bytes.
Here,
largest memory space (ie.20 bytes) will be allocated for union.

Example:
#include<stdio.h>
#include<conio.h>
union student
{
char name[20];
int roll;
float marks;
};
int main()
{
union student st;
printf("Enter the Name");
scanf("%s",st.name);
printf("Name is:%s",st.name);
printf("Enter the Rollno");
scanf("%d",&st.roll);
printf("Rollno is %d",st.roll);
printf("Enter the marks");
scanf("%f",&st.marks);
printf("Marks is %f",st.marks);
getch();
return 0;
}

Structure vs union
Some Important Questions:
1. Differentiate structure and union. [PU: 2016 fall]
2. Define structure and union. Explain way of declaring and accessing member of them
with suitable example. [PU: 2015 fall]
3. Compare and contrast structure with union. [PU: 2012 Fall]

Programs related to structure


Create a structure called employee having name, address, salary and age. Input n records of
employee and display information of employee whose address is Kathmandu.

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct employee
{
char name[20];
char address[20];
float salary;
int age;
};
int main()
{
struct employee e[100];
int i,n;
printf("Enter how many records you want to enter");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the records of employee %d\n",i+1);
printf("Enter the name");
gets(e[i].name);
printf("Enter the address");
gets(e[i].address);
printf("Enter the salary");
scanf("%f",&e[i].salary);
printf("Enter the age");
scanf("%d",&e[i].age);
}
printf("\nInformation of employee whose address is kathmandu are\n");
printf("\nName\tAddress\tSalary\tAge");
for(i=0;i<n;i++)
{
if(strcmp(e[i].address,"kathmandu")==0)
{
printf("\n%s\t%s\t%f\t%d",e[i].name,e[i].address, e[i].salary,e[i].age);
}
}
getch();
return 0;
}

Perform the following operations for above question:

1. Display information of employee whose name is raju:


Hint:
printf("\nInformation of student whose name is raju are\n");
printf("\nName\tAddress\tSalary\tAge");
for(i=0;i<n;i++)
{
if(strcmp(e[i].name,"raju")==0)
{
printf("\n%s\t%s\t%f\t%d",e[i].name,e[i].address, e[i].salary,e[i].age);
}
}
2. Display information of employee whose salary is greater than 10, 000

Hint:
printf("\nInformation of employee whose salary is greater than 10,000 are\n");
printf("\nName\tAddress\tSalary\tAge");
for(i=0;i<n;i++)
{
if(e[i].salary>10000)
{
printf("\n%s\t%s\t%f\t%d",e[i].name,e[i].address,e[i].salary,e[i].age);
}

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct dob
{
int dd;
int mm;
int yy;
};
struct student
{
int roll;
char name[20];
char address[20];
char faculty[20];
struct dob d;
};
int main()
{
int i;
struct student st[100];
for(i=0;i<100;i++)
{
printf("Enter the records of student %d\n",i+1);
printf("Enter the roll");
scanf("%d",&st[i].roll);
printf("Enter the name");
gets(st[i].name);
printf("Enter the address");
gets(st[i].address);
printf("Enter the faculty");
gets(st[i].faculty);
printf("Enter year of birthday");
scanf("%d",&st[i].d.yy);
printf("Enter month of birthday");
scanf("%d",&st[i].d.mm);
printf("Enter day of birthday");
scanf("%d",&st[i].d.dd);
}
printf("\nThe records of student whose faculty is computer are\n");
printf("\nRollno\tName\tAddress\tFaculty\tDate of Birth");
for(i=0;i<100;i++)
{
if(strcmp(st[i].faculty,"computer")==0)
{
printf("\n%d\t%s\t%s\t%s\t%d\t%d\t%d",st[i].roll,st[i].name,st[i].address,st[i].faculty,st[i].d.
mm,st[i].d.dd,st[i].d.yy);
}
}
getch();
return 0;
}

Assignment
Create a structure called book, member name, price, author, and published date in day,
month, and year. Write a program to read 100 books information from the user and displays
those records having price greater than 250.
Unit 5
Functions and Pointers in C
functions and their importance
➢ Function is a self -contained block of code or statement that performs a particular
task.
➢ Every program must contain one function named main() from where the program
execution begin.
➢ Complex problem can be solved by breaking them into set of sub-problems, called
modules or functions. This technique is called divide and conquer. Each module can be
implemented independently and later can be combined into single unit.

Example of function in c
#include<stdio.h>
int add(int a,int b);//function declaration or function prototype ,argument is optional
here
int main(){
printf(“sum is %d”,add(2,3));
return 0;
} function call
int add(int x,int y){
return (x+y); //function body or function defination
}

Output: sum is 5

Importance/ Key Benefits


• Enables reusability and reduces redundancy
• Makes a code modular
• Provides abstraction functionality
• The program becomes easy to understand and manage
• Breaks an extensive program into smaller and simpler pieces

Disadvantage
• It increase the execution time because when function is called the control have to
jump to function definition to perform the particular task ,and after completion of task
, control again come back to the function call.

questions
1. What do you mean by functions in C programming?Why functions are used?
2. . Without using functions also we can write a program. But we need functions in our
program.
What are the benefits of using them.

5.2 Declaration of a function


A function declaration in C provides information to the compiler on the name and
method of calling a function. The function’s actual body can be specified
independently. A function declaration has the following parts –
Syntax:
return_type function_name( parameter list );

For the below-defined function max(), the function declaration is as follows –


int max(int num1, int num2);

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}

Only their type is necessary when defining a function; hence, the following
declaration is likewise acceptable: int max(int, int);

5.3 Structure of function and return statement


Here is the syntax that we use to create a function in the C programming language:

return_type name_of_function(data_type parameter…){


// executable code in c
}
The return -type specifies the type of data that the function returns. A function may return
any type (default: int) of data except an array .The parameter (formal arguments) list is a
comma-separated list of variable names and their associated types. The parameters
receive the values of the arguments when the function is called. A function can be without
parameters: An empty parameter list can be explicitly specified as such by placing the
keyword void inside the parentheses

return statement
The return statement is used to terminate the execution of a function and transfer program
control back to the calling function. In addition, it can specify a value to be returned by
the function. The general format of the return statement is given below.
return expr ;
where, expr is the expression whose value is returned by the function. The execution of
the return statement causes the expression expr to be to be evaluated and its value to be
returned to the point from which this function is called. The expression expr in the return
statement is optional and if omitted, program control is transferred back to the calling
function without returning any value. ·
If a function does not return any value, the return statement may be omitted, in which
case all the statements within the function body are always executed before control is
transferred back to the calling program. However, we can include one or more return
statements (without expr) to transfer control back to the calling function.
Categories of function in C
1. No return type with argument
2. No return type without argument
3. Return type with argument
4. Return type without argument.
//no return type with no argument
Here argument is not passed in the called function .Also function doesnot return any value.
#include<stdio.h>
void difference();
int main(){//main is calling function

difference();//called function
return 0;
}
void difference()
{
int a,b,differ;
printf("enter two numbers\n");
scanf("%d %d",&a,&b);
differ = a-b;
printf("difference is %d",differ);
}

no return type with argument


here argument is passed in the called function but value is not returned by the function.
#include<stdio.h>
void difference(int a,int b);
int main(){
int a,b;
printf("Enter two numbers\n");
scanf("%d %d",&a,&b);
difference(a,b);
return 0;
}
void difference(int x,int y)
{
int differ;
differ = x-y;
printf("difference is %d",differ);
}
//return type with no argument
Here the argument is not passed to the called function but the function return some value after performing its task.
#include<stdio.h>
int difference();
int main(){
int diff;
diff = difference();
printf("difference: %d",diff);
return 0;

}
int difference()
{
int a,b,differ;
printf("enter two numbers\n");
scanf("%d %d",&a,&b);
differ = a-b;
return differ;
}

//return type with argument


Here the function takes the argument and also it return some value after performing its task.
#include<stdio.h>
int difference(int m,int n);
int main(){
int a,b,differ;
printf("Enter two numbers\n");
scanf("%d %d",&a,&b);
differ=difference(a,b);
printf("difference is %d",differ);
return 0;
}
int difference(int x,int y)
{

return (x-y);

}
Some examples of function
write a program to calculate simple interest using function.
#include<stdio.h>
float simple_intrest(float p,float t,float r);
int main()
{
float p,r,t,intrest_amt;
printf("input principle,rate and time");
scanf("%f %f %f",&p,&r,&t);
intrest_amt = simple_intrest(p,t,r);
printf("simple interst is %f",intrest_amt);
return 0;
}
float simple_intrest(float p,float t, float r) {
float si;
si = (p*t*r)/100;
return si;
}

Write a program to calculate simple interest with no returntype and with argument
#include<stdio.h>
void simple_intrest(float p,float t,float r);
int main()
{
float p,r,t,intrest_amt;
printf("input principle,rate and time");
scanf("%f %f %f",&p,&r,&t);
intrest_amt = simple_intrest(p,t,r);
return 0;
}
void simple_intrest(float p,float t, float r){
float si;
si = (p*t*r)/100;
printf("simple interst is %f",intrest_amt);
}
Wap to find Sum of n natural number using function call
#include<stdio.h>
int snatural(int n);
int main(){
int num,s;
printf("enter value of n:");
scanf("%d",&num);
s = snatural(num);
printf("sum of %d natural numbers is %d",num,s);
return 0;
}
int snatural(int n){
int i,sum = 0;
for(i = 1;i<=n;i++){
sum = sum + i;
}
return sum;
}

Wap to find the factorial of given number using function call


#include<stdio.h>
int factorial(int a);
int main(){
int n;
printf("enter a number");
scanf("%d",&n);
printf("factorial of a given number is %d",factorial(n));
return 0;
}
int factorial(int n){
int i,fact = 1;
for(i=1;i<=n;i++){
fact = fact *i;
}
return fact;
}
Wap to find the Fibonacci series upto n term using function
#include<stdio.h>
void fibonacci(int n);
int main(){
int n;
printf("enter a number");
scanf("%d",&n);
fibonacci(n);
return 0;
}
void fibonacci(int n){
int a = -1,b = 1,c,i;
for(i=1;i<=n;i++)
{
c = a + b;
printf("%d ",c);
a = b;
b = c;
}
}

Wap to find the reverse of a given number using function call

#include<stdio.h>
void reverse(int n);
int main(){
int n;
printf("enter a number");
scanf("%d",&n);
printf("the original number is %d\n",n);
reverse(n);
}
void reverse(int num){
int rem,rev = 0;
while(num>0){
rem = num %10;
rev = rev * 10 + rem;
num = num /10;
}
printf("reversed number is %d",rev);
}
C SCOPE RULES

• A scope in any programming is a region of the program where a defined variable can have its existence
and beyond that variable it cannot be accessed. −
• Inside a function or a block which is called local variables.
• Outside of all functions which is called global variables.

Local Variables

• Variables that are declared inside a function or block are called local variables.
• They can be used only by statements that are inside that function or block of code.
• Local variables are not known to functions outside their own.

#include <stdio.h>
int main () {
int a, b,c; //local variable declaration
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}

Global Variables
• Global variables are defined outside a function, usually on top of the program.
• Global variables hold their values throughout the lifetime of your program and they can be accessed inside
any of the functions defined for the program.

#include <stdio.h>
int x = 20; /* global variable declaration */

void sum();
int main () {
int g = 10; /* local variable declaration */
printf ("value of g = %d\n", g);
printf("%d \n",x);
sum();
return 0;
}
void sum(){
printf("%d",x);
}
Call by value

• In call by value method, the value of the actual parameters is copied into the formal parameters. In other
words, we can say that the value of the variable is used in the function call in the call by value method.

//example
#include<stdio.h>
void change(int);
int main()
{
int x=100;
change(x);
return 0;
}
void change(int num) {
printf("%d",num);
}
Preprocessor directive and macros in C.

Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the source code before
compiling.All of these preprocessor directives begin with a ‘#’ (hash) symbol.The ‘#’ symbol indicates that whatever
statement starts with a ‘#’ will go to the preprocessor program to get executed.The #include preprocessor is used to
include header files to C programs. For example#define preprocessor is used to define macros.
A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor
directive.
//example
#include <stdio.h>
#define PI 3.1415
int main()
{ //macro
float radius, area;
printf("Enter the radius: ");
scanf("%f", &radius);
area = PI*radius*radius;
printf("Area=%f",area);
return 0;
}
Pointer
The pointer in C language is a variable which stores the address of another variable.for example

int a=2;
int *ptr;
ptr =&a;

//example
#include <stdio.h>
int main()
{
int a = 8;
int *ptr;
ptr =&a;
printf("%d\n",ptr);
printf("%d",*ptr);
return 0;

Call by reference

#include <stdio.h>
void pass(int *);
int main()
{
int num1 = 5;
pass(&num1);
return 0;
}
void pass(int *n)
{
printf("%d\n",*n);
}
Function returning multiple values
Normally, (when function arguments are passed by value) more than one value cannot be returned at a time using
function. But when we use pointer in function we can return more than one value.example

#include<stdio.h>
void mathoperation(int x,int y,int *s,int *d);
int main()
{
int x = 20,y=10,s,d;
mathoperation(x,y,&s,&d);
printf("s=%d d=%d\n",s,d);
return 0;
}
void mathoperation(int a,int b,int *sum,int *diff)
{
*sum = a + b;
*diff = a-b;
}
One dimensional array and pointer

#include <stdio.h>
int main()
{
int a[5]={5,10,15,20,25},i;
int *ptr=&a[0]; //a
for(i=0;i<5;i++){
printf("%d ",*(ptr+i));
}
return 0;
}
Pointers, Pointer Operator, Pointer Arithmetic
A Pointer in C language is a variable that holds a memory address. This memory
address is the address of another variable (mostly) of same data type. In simple words,
if one variable stores the address of second variable then the first variable can be said
to point towards the second variable.
Simply, Pointer is a variable that stores or points the address of another variable.

What is Memory Address in C?


Whenever a variable is defined in C language, a memory location is assigned for it, in
which it's value gets stored. We can check this memory address, using the & symbol.
If var is the name of the variable, then &var will give it's address. Let's write a small
program to see memory address of any variable that we define in our program.
Program
#include<stdio.h>
int main()
{
int a=5;
printf("The address of a is:%u",&a);
printf("\nThe value of a is:%d",a);
return 0;
}

output
The address of a is: 6356732
The value of a is: 5

Syntax:
int num; //num is integer variable
int *p; //pointer declaration
p is a pointer variable that store the address of integer variable only

valid
int *ptr; //pointer declaration
int a=5;
ptr=&a; //address of variable a is assigning to pointer variable ptr
Here ptr is a pointer variable that only contains the address of integer data type.

Advantages of pointer
• Pointers are more efficient in handling arrays.
• Pointers can be used to return multiple values from functions via function
arguments.
• Pointer reduce the storage space and complexity of programs.
• They increase the execution speed and thus reduce the program execution
time.

Pointer Operators
There are two pointer operators in C, they are:
(a) * operator
(b) & operator
The & operator returns the memory address of its operand. For example,
a = &b;
In the variable a the memory address of the variable b will get stored.
The * operators is the complement of &. This operator returns the value located at the given
address.For example, if a contains the memory address of the variable b, then the code,
c = *a;
will store the value of the variable b into c.

Pointers in C Example
Let's see a basic code example where we will create a pointer and assign it a value.For
example, if a contains the memory address of the variable b, then the code.c = *a; will store
the value of the variable b into c.
#include<stdio.h>
int main()
{
int x = 22;
// declare a pointer
int *ptr;
// assign value to pointer
ptr = &x;
printf("Value at ptr is: %d \n", *ptr);
printf("Address pointed by ptr is: %p \n", ptr);
return 0;
}
Output:
Value at ptr is: 22
Address pointed by ptr is: 0060FEF8
Pointer Arithmetic
There are only a few operations that are allowed to perform on Pointers in C language. The
operations are slightly different from the ones that we generally use for mathematical
calculations. The operations are:
(a) Increment/Decrement of a Pointer
(b) Addition and subtraction of integer to a pointer
(c)Comparison of pointers of the same type.

(a) Increment/Decrement of a Pointer


Increment: It is a condition that also comes under addition. When a pointer is incremented, it
actually increments by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size
of an int) and the new address it will points to 1002. While if a float type pointer is
incremented then it will increment by 4(size of a float) and the new address will be 1004.
Like increment, we can Decrement a pointer variable. If we decrement a pointer, it will start
pointing to the previous location.

If arithmetic operations done values will be incremented or decremented as per data type
chosen. Let ptr=&arr[0]=1000 i.e Base address of array.

Note: Similar operation can be done for decrement.


Example for pointer increment/decrement
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[5] = {10,20,30,40,50};
int *ptr1,*ptr2;
ptr1=&arr[0];
ptr1++;
printf("\nvalue %d has address %u",*ptr1,ptr1); //points to 2nd element
ptr2=&arr[4];
ptr2-- ;
printf("\nvalue %d has address %u",*ptr2,ptr2); //points to 4th element
getch();
return 0;
}
Output
value 20 has address 6356696
value 40 has address 6356704

(b) Addition and Subtraction of integer to a pointer

When a pointer is added with a value, the value is first multiplied by the size of data type and
then added to the pointer. The formula of adding value to pointer is given below:
new_address= current_address + (number * size_of(data type))
Like pointer addition, we can subtract a value from the pointer variable. Subtracting any
number from a pointer will give an address. The formula of subtracting value from the
pointer variable is given below:
new_address= current_address - (number * size_of(data type))
Example for pointer addition/subtraction with integer constant
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[5] = {10,20,30,40,50};
int *ptr1,*ptr2;
ptr1=&arr[0];
ptr1=ptr1+4;
printf("\nvalue %d has address %u",*ptr1,ptr1); //points to 5th element
ptr2=&arr[4];
ptr2=ptr2-4 ;
printf("\nvalue %d has address %u",*ptr2,ptr2); //points to 1st element
getch();
return 0;
}

Output
value 50 has address 6356708
value 10 has address 6356692
(c) Comparison of pointers of the same type
We can compare pointers if they are pointing to the same array. Relational pointers can be
used to compare two pointers. Pointers can’t be multiplied or divided.
int main() {
int arr[5]={1,2,3,4,5};
int *ptr1,*ptr2;
ptr1=&arr[0];
ptr2=&arr[4];
if(ptr2>ptr1)
printf("ptr2 is far from ptr1");
else
printf("ptr1 is far from ptr2");
return 0;
}
Questions
• Can function return more than one value? Justify your answer with examples.
• Does function return single or multiple value? When and how a function will return
single or multiple value? Illustrate with examples
• How can function return multiple values? Explain with example?
Unit vi
Introduction to C++
History of C++
• C++ language has been derived from C programming.
• Originanlly named c with classes in 1979
• Developed by Bjarne stroustrup at bell labs(AT & T)
• He borrowed features from simula,ada,clu languages and added to C
• In 1983 the name of the new language was changed to c with classe to C++
• The increment operator ‘++’ to C indicates the enhancement of C language
• Commercial release of C++ was launched in October 1985.
• All the features of C are supported by C++ also.Thus C is also subset of C++.

Introduction
• C++ is a high level programming language.
• Supports variety of platforms such as windows,mac and various version of UNIX
• It is general purpose,case-sensitive,compiled and free form of programming language that
supports procedural,object oriented and generic programming.
• C++ fully supports object oriented programming with features ,encapsulation,data
hiding,inheritance,polymorphism.

Application of C++
• Game development:IT is use to make game engine,gui based games etc
• Embedded system
• Computer aided design(CAD)
• Object oriented database
• Simulation and modeling
• Hypertext and hypermedia:hypertext and hypermedia is another area where OOP approach is
being used.As it is easy to represent real media objects with the concept of OOPs object it is
easy to use in Hypertext and Hypermedia
• Office automation system:We need various types of systems or software for office
automation.Automation system is just a type of real time system.The embedded systems make it
easy to use OOP automated system.
• Website application,desktop application
• Decision support system ,AI and Expert system.:Decision support system ,AI and Expert systm
also use real time system which are too advanced and complex system.We can use OOP to
design and develop the system to use for decision
• Real time system:A real time system is a system that gives outpur at given instant and its
parameters change every time.A real time system is a dynamic system,means the system that
changes every moment based on input to the system.OOP approach is very useful for real time
system as code changing is very easy in OOP system and its leads to toward dynamic behavior
of OOP codes.

1
Procedure oriented programming(POP)
• High level language such as COBOL,FORTRAN and C is commonly known as procedure
oriented programming (POP)
• The problem is viewed as a sequence of things to be done such as reading ,calculating and
printing.
• Many functions are written to finish the task.

Main function

Function 1 Function 2 Function 3

Function 4 Function 5

Function 8
Function 6 Function 7

Main (){

Function1();

Function2()

;}

Function1(){

}
Function2(){

2
• In multifunction program many important data items are placed as global so that they may be
accessed by all the functions.
• Each function may have its own local data.

DRAWBACKS

• Global data may be unintentionally changed by a function;


• Procedural coding is very difficult to maintain for larger code.
• Code reusability is difficult.
• It does not model real world problems very well.
• Difficult ot hide information to unauthorized user.

Characteristics of pop
• Emphasis is on doing things (algorithm).
• Large programs are divided into smaller program known as function.
• Most functions share global data
• Function transform data from one form to another.
• Employs top down approach in program design.

Object oriented programming as a new paradigm


• Motivating factor of OOP is some of the flaws encountered in the procedural approach.
• It ties data more closely to the functions that operate and protects it from accidental
modification form outside function.
• The central concept of object oriented programming is object,which is a kind of models
containing data and function.
• OOP allows decomposition of a problem into a number of entities called objects and then builds
data and functions around these objects.

data

function

data
data

function
function 3

Fig:communcation between
objects
Characterics of OOP
• Emphasis is on data rather than procedure
• Programs are divided into what are known as objects
• Data is hidden and cannot be accessed by external function.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in a program design.
• Functions and data area tied together in a class.the binding of functions with data is known as
encapsulation.
• Objects communicate with each other by sending message and receving message.
• Supports reusability of code.
• Supports polymorphism.(i.e same name can be assigned to different things).

Features of OOP
• CLASS
• OBJECT
• INHERITANCE
• POLYMORPHISM
• ENCAPSULATION
• DATA ABSTRACTION
• MESSAGE PASSING.

Class
• CLASS is a user defined data type which has data members and member function.
• Class is building block that leads to object oriented programming.
• Data members are the data variables and member functions are the functions to manipulate
those variables and together these data members.
• An object is an instance of a class .when a class is defined ,no memory is allocated but when it is
instantiated(an object is created) memory is allocated.
Structure of class

keyword

Private,public,prottected
Class classname{

Access specifier: Properties, or attributes

Member variable declaration:

Member function declaration: behaviour

}
methods

//example
#include <iostream>
using namespace std;
class rectangle
{
private:
float len ,br;
public:
void getdata(float l,float b)
{

len=l; br =b;
}

void calculatearea()
{
cout<<"the area is "<<(len *br)<<endl;
}

};

int main()
{ rectangle r1,r2;
r1.getdata(10,20);
r2.getdata(15,10);
r1.calculatearea();
r2.calculatearea();
return 0;
}
Output
the area is 200
Example
the area is 150
Object
• An object is an class variable or instance of a class.
• Creating object of a class is lke defining a variable of a data type.
• An object doesnot exist until an instance of class has been created.
• When an object is physicall created,space for that object is allocated in primary memory.

Example

Classname o1,o2,o3 ;

Here we have created three class objects namely o1,o2 and o3 using classname.

Inheritance
• Inheritance is the ability of creating new class form existing class with new data and methods.
• The existing class is called base class and newly created class is called derived class.
• Derived class inherits all the features of except private data members.
• It supports code reusability means it can add additional features to an existing class without
modifying it.
Class vehicle

Apply brake()

Increase speed()

Class bus Class car

Fig:inheritanc
e

Polymorphism
• The word polymorphism is derived from two greek words poly and morphe.The word poly
means many and morphe means forms.
• Polymorphism means the ability to take more than one form.
• OOP supports polymorphism through function overloading,operator overloading,function
overriding and template.
• An operation may exhibit different behaviours in different instances.The behavior depends on
the data types used in the operation.like ‘+’ operator can be used to add two integer data items
and also to add two objects.
Encapsulation
• Encapsulation is an ability to bind(package)functions and data together in a place and hide( or
prevent) the data from unauthorized use from other parts of the program.Thus function and data
in OOP are always together within an object that provides data hiding.Thus data is hidden within
an object.

Data

function

An object(i.e capsule containing data and functions)

Data abstraction

• Abstraction refers to an act of representing essential features without including background


details or explations.Thus ,data abstraction is a methodology that supports use of compound or
complex object without its detail knowledge.for example a class car would be made up of an
engine,gearbox,steering object and many other components .to build a car class ,one does not
know how the different components of the car work internally ,but only how to interface with
them(i.send message to them,receive message from them).
Message passing
Objects can communicate with each others by passing message same as people pass message
with each other.An object can send or receive message/information form /to another object.A
message for an object is a request for execution of a procedure and therefore will invoke function
in receiving object that generates the desired result.The message passing involves name of
object,name of function(message) and information to be send.

Object.functionname(parameter

s) For example: student.getmarks(10);

Here,student is object name ,getmarks() is a message and 10 is information.

Following are the basic steps in message passing.

• Creating classes that define objects and its behavior


• Creating objects from class definations.
• Establishing communication among objects.
Difference between POP and OOP

sn Procedure oriented programming Object oriented programming

1 It is Structure oriented It is Object oriented..

2 Program is divided into functions. Program is divided into objects.

3 It follows Top-down approach. It follows Bottom-up approach.

Inheritance property is used


4 Inheritance is not allowed.

5 It doesn’t use access specifier. It uses access specifier.

6 No data hiding. Encapsulation is used to hide the data.

7 Example c,fortran,pascal Example c++,java


Access Specifier
Access Modifiers or Access Specifiers in a class are used to assign the accessibility to the class members, i.e., they
set some restrictions on the class members so that they can’t be directly accessed by the outside functions. There
are 3 types of access modifiers available in C++s Specifiers in a class are used to assign the accessibility to the
class members, i.e., they set some restrictions on the class members so that they can’t be directly accessed by the
outside functions. There are 3 types of access modifiers available in C++. 1.Public 2.Private 3.Protected

1. Public: All the class members declared under the public specifier will be available to everyone. The data
members and member functions declared as public can be accessed by other classes and functions too. The public
members of a class can be accessed from anywhere in the program using the direct member access operator (.)
with the object of that class. // C++ program to demonstrate public access modifie

#include<iostream>
using namespace std;
// class definition
class Circle
{
public:
float radius;
float compute_area()
{
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
// accessing public datamember outside class
obj.radius = 5.5;
cout << "Radius is: " << obj.radius << "\n";
cout << "Area is: " << obj.comp
}
return 0;
}
2. Private: The class members declared as private can be accessed only by the member functions inside the
class. They are not allowed to be accessed directly by any object or function outside the class. Only the member
functions or the friend function are allowed to access the private data members of the class
// C++ program to demonstrate private access modifier

#include<iostream>
using namespace std;
class Circle
{
private:
float radius;
public:
float compute_area()
{
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
// trying to access private data member
// directly outside the class
obj.radius = 1.5; //error
cout << "Area is:" <<
obj.compute_area();
return 0;
}
Protected: The protected access modifier is similar to the private access modifier in the sense that it can’t be
accessed outside of its class unless with the help of a friend class. The difference is that the class members
declared as Protected can be accessed by any subclass (derived class) of that class as well

// C++ program to demonstrate protected access modifie

#include <iostream>
using namespace std;
class Parent
{
protected:
int id_protected;
};
class Child : public Parent
{
public:
void setId(int id)
{id_protected = id;
}
void displayId()
{
cout << "id_protected is: " <<
id_protected << endl;
}
};
int main() {
Child obj1;
// member function of the derived class
can
// access the protected data members of
the base class
obj1.setId(82);
obj1.displayId();
return 0;
}
Member function inside the class

In this case ,a member function is defined inside the class body at the time declaration.The function
declaration is replaced by the function definition inside the class body.This technique is applied in the
case of short functions.The function defined within a class body is treated as inline function

//example of c++ program


#include<iostream>
using namespace std;
class box{
private:
float length,breadth,height,volume;
public:
void readdata(){
cout<<"enter length
,breadth,height"<<endl;
cin>>length>>breadth>>height;
}
void calculate(){
volume = length*breadth*height;
}
void display()
{
cout<<"the volueme is "<<volume;
}
};
int main(){
box b1;
b1.readdata();
b1.calculate();
b1.display();
return 0;
}
output
enter length ,breadth,height
2
3
4
the volueme is 24
Member function Outside the class body

Member functions that are declared inside a class have to be defined separately outside the class. • Their
definations are very much like the normal functions.They should have a function header and a function body. The
general form of member function definition is
return _type class_name::functionname(argument declaration)
{ Function body }

#include<iostream>
using namespace std;
class box{
private:
float
length,breadth,height,volume;
public:
void readdata();
Void calculate();
Void display();
};
Void box:: readdata()
{cout<<"enter length ,breadth,height"<<endl;
cin>>length>>breadth>>height;
}
Void box:: calculate(){
volume = length*breadth*height;
}
Void box:: display()
{
cout<<"the volueme is "<<volume;
}
int main(){
box b1;
b1.readdata();
b1.calculate();
b1.display();
return 0;
}
Output
enter length ,breadth,height
1
2
3
the volueme is 6
Write a c++ program to keep the records of books

#include<iostream>
using namespace std;
class book
{
char bname[30];
float bprice;
char bauthor[20];
public:
void getdata()
{
cout << "enter bookName = ";
cin >> bname;
cout << "bookPrice = ";
cin>>bprice;
cout<<"bookauthor = ";
Output
cin >> bauthor;
}
Item : 1
void print()
enter bookName = c
{
bookPrice = 1000
cout << "bookName : " << bname <<endl;
bookauthor = ritchie
cout << "bookPrice : " << bprice<<endl;
Item : 2
cout<<"book author:"<<bauthor<<endl;
enter bookName = c++
}
bookPrice = 1200
};
bookauthor = balaguruswamy
int main()
------------------------------------
{
Book Details : 1
book t[2];
bookName : c
for(int i = 0; i < 2; i++)
bookPrice : 1000
{
book author:ritchie
cout << "Item : " <<
Book Details : 2
(i + 1) << "\n";
bookName : c++
t[i].getdata();
bookPrice : 1200
}
book author:balaguruswamy
cout<<"------------------------------------"<<endl;
for(int i = 0; i < 2; i++)
{
cout << "Book Details : " <<(i+1)<<endl;
t[i].print();
}
return 0;
}
Constructor
Constructor is a member function that has the same name as the class itself • constructor being function can be
overloaded • It is executed automatically whenever an object is created. • constructor may or maynot take
argument depending on how the object is to be constructed

Characteristic
• Same name as class name • It cannot be inherited.
• Should be declared in public section always
• It has no return type.
• It cannot be inherited
Example

#include<iostream>
using namespace std;
class A
{
int a;
public:
A()
{ a=0;
}
Void display(){
cout<<a;
}
int main()
{ A obj;
return 0;
}

Default constructor
Constructor declared which doesnot accept any argument is called default constructor.
It is invoked when the object is created with no argument .
Syntax:
class classname()
{
public:
classname()
{
//body
}
};
// default constructor example
#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;

public:
// constructor
student()
{
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}

void display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
};

int main()
{
student s; // constructor gets called automatically when
// we create the object of the class
s.display();
return 0;
}
output

Enter the RollNo:1


Enter the Name:ram
Enter the Fee:222

1 ram 222
Parameterized constructor
The constructor that takes argument is called parameterized constructor.

//example
#include<iostream>
using namespace std;
class rational{
int num,denum;
public:
rational(int a,int b)
{
num =a;
denum =b;
}
void display(){
cout<<"num="<<num<<endl;
cout<<"denum="<<denum;
}
};
int main(){
rational r(10,20);
r.display();
return 0;
}

Output
num=10
denum=20
Destructor

We have seen that special member function constructor is called automatically when an object is first created.
similarly when an object is destroyed a function is called destructor automaticllay. A destructor has the same name
as the constructor(which is the same name as the class name) but is preceded by a tilde. A destructor never takes
any argument nor does it return any values

#include<iostream>
using namespace std;
class base{
private:
int
i
;
public:
base()
{ i =0;
}
~base()
{
cout<<"I m in destructor section"<<endl;
}
};
int main(){
base b1,b2,b3;
return 0;
}
Output
I m in destructor section
I m in destructor section
I m in destructor section
Unit vii
Object oriented programming concept
Inline function
When a function is likely to be called many times each time the control is passed between calling and
called function.Due to this passing of control between calling and called function the execution speed of
the program is decreased.If passing of control during the repetitive call of the function is avoided,the
program execution speed increases.C++ has a different solution to this problem .To eliminate the costs of
call to small functions,c++ purposes a new feature called inline function.An inline function is a function
that is expanded inline where it is invoked or called. That means compiler replaces the function call with
corresponding function code.If the function code is very large in such case don’t use inline function that
reduces the program execution speed.

Syntax:
inline returntype functionname(arguments)
{ function body

Example
#include<iostream>
using namespace std;
inline int add(int a,int b)
{
return (a+b);
}
inline float sub(float a ,float b){
return (a-b);
}
int main(){
cout<<”ths sum is “<<add(5,2);
cout<<”the difference is”<<sub(5.0,2.0);
return 0;
}
Output
ths sum is 7
the difference is3
Friend function
• Non member function cannot have an access to the private data of the class.However,there could be a
situation where we would like two classes to share a particular function.
• In c++ this is achieved by using the concept of friend function.
• It permits the function or all other function of class to access a different class of private data member.
• The function that are declared with a keyword friend , is called friend function.It can be defined
anywhere in the program like normal function. •
• The function definition does not use either keyword friend nor (::) scope resolution operator.

#example

#include<iostream>
using namespace std;
class sample
{
float a;
float b;
public:
void setvalue(){
a =25;
b=40;
}
friend float mean(sample s);
};
float mean(sample s)
{
return (s.a+s.b)/2;
}
int main(){
sample obj;
obj.setvalue();
cout<<”mean value=”<<mean(obj);
return 0;
}
Output
mean value=32.5
Adding private data of two classes using friend function

#include<iostream>
using namespace std;
class beta;//forward declaration
class alpha
{ private:
int data1;
public:
void getdata(){
cout<<"enter data"<<endl;
cin>>data1;
}
friend int fren_func(alpha ,beta );
};
class beta
{ private:
int data2;
public:
void getdata(){
cout<<"enter data"<<endl;
cin>>data2;
}
friend int fren_func(alpha ,beta );
};
int fren_func(alpha a,beta b)
{
return (a.data1+b.data2);
}
int main(){
alpha a1;
a1.getdata();
beta b1;
b1.getdata();
cout<<"sum is
"<<fren_func(a1,b1)<<endl;
return 0;
}
Output
enter data
2
enter data
6
sum is 8
Function overloading
Function overloading is a feature of object-oriented programming where two or more functions can have
the same name but different parameters or different number of arguments. • In Function Overloading
“Function” name should be the same and the arguments should be different.

//example
#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum = " << (a + b)<<endl;
}
void add(int a)
{
cout << a;
}
int main(){
add(10, 2);
add(1);
return 0;
}
Output
sum = 12
1

#example2

#include <iostream>
using namespace std;
void add(int a, int b)
{
cout << "sum = " << (a + b);
}
void add(float a, float b)
{
cout << endl << "sum = " << (a + b);
}
int main()
{
add(10, 2);
add(5.3f, 6.2f);
return 0;
}

Output
sum = 12
sum = 11.5
Inheritance
• It is the capability of one class to inherit the properties and behavior from another class.
• The technique of building new classes from the existing class is called inheritance
• Base class(super class or parent class) Is the class whose properties or member functions are inherited.
• Derived class(child class) is the class which inherits the properties or member functions from the base
class Advantages of inheritance.

Base class/super class/parent class

Derived class/sub class/child class


Types of inheritance
• Single inheritance
• Multiple inheritance
• Multilevel inheritance

Single inheritance

Base class

Derived class

//example
#include <iostream>
using namespace std;
// base class
class Animal {
public:
void eat() {
cout <<"animal eats!" << endl;
}
void sleep() {
cout <<"animal sleeps!" << endl;
}
};
// derived class
class Dog : public Animal {
public:
void bark() {
cout << "dog can bark! Woof woof!!" << endl;
}
}; int main() {
Dog dog1;
dog1.eat();
dog1.sleep();
dog1.bark();
return 0;
}

Output
animal eats!
animal sleeps!
dog can bark! Woof woof!!
//example 2 single inheritance
#include<iostream>
using namespace std;
class A{
protected:
float r;
public:
void getdata(){
cout<<"enter value of r";
cin>>r;
}
};
class B:public A{
private:
float area;
public:
void calculate(){
area = 3.14 * r*r;
}
void show(){
cout<<"area of circle is "<<area;
}
};

int main(){
B obj1;
obj1.getdata();
obj1.calculate();
obj1.show();
return 0;
}
Output
enter value of r2
area of circle is 12.56
Multiple inheritance in c++

Multiple Inheritance is the concept of the Inheritance in C++ that allows a child class to inherit properties
or behaviour from multiple base classes.
Therefore, we can say it is the process that enables a derived class to acquire member functions,
properties, characteristics from more than one base class

Base class 1 Base class 2

Derived class

//example
#include <iostream>
using namespace std;
class Mammal {
public:
void mammal_behavior() {
cout << "Mammals can give direct birth." << endl;
}
};
class WingedAnimal {
public:
void WingedAnimal_behavior() {
cout << "Winged animal can flap." << endl;
}
};
class Bat: public Mammal, public WingedAnimal {
public:
void bat1(){
cout<<"sits upside down";
}
Output
};
Mammals can give direct birth
int main() {
Winged anmical can flap
Bat b1;
Sits upside down
b1.mammal_behavior();
b1.WingedAnimal_behavior();
b1.bat1();
return 0;
}
//example 2 multiple inheritance

#include<iostream>
using namespace std;
class length
{
protected:
int l;
};
class breadth
{
protected:
int b;
};
class peri:public length,public breadth{
private:
int p;
public:
void getdata(){
cout<<"enter length and ,breadth"<<endl;
cin>>l>>b;
}
void calculate(){
p = 2*(l+b);
}
void show(){
cout<<"perimeter is "<<p<<endl;
}
};
int main(){
peri obj1;
obj1.getdata();
obj1.calculate();
obj1.show();
return 0;
}

Output
Enter length and breadth
2
3
Perimeter is 10
Multilevel inheritance
• If a class is derived from another derived class then it is called multilevel inheritance.
The inheritance in which a class can be derived from another derived class is known as Multilevel

Class A

Class B

Class C

Inheritance

//example
#include <iostream>
using namespace std;
class P {
public:
void display () {
cout<<"All contents of Base Class"<<endl;
}
};
class Q: public P {
public:
void display1() {
cout<<"all content of class Q."<<endl;
}
};
class R: public Q {
public:
void display2() {
cout<<"All contents of class R."; }
};
int main () {
R r;
r.display();
r.display1();
r.display2();
return 0;
}
Output
All contents of Base Class
all content of class Q.
All contents of class R.
//example 2 multilevel inheritance
#include <iostream>
using namespace std;
class A { // single base class
protected:
int a;
public:
void get_A_data()
{
cout << "Enter value of a: ";
cin >> a;
}
};
class B : public A { // derived class from base class
protected:
int b;
public:
void get_B_data()
{
cout << "Enter value of b: ";
cin >> b;
}
};
// derived from class derive1
class C : public B {
private:
int c;
public:
void get_C_data()
{
cout << "Enter value of c: ";
cin >> c;
}
void sum()
{
int ans = a + b + c;
cout << "sum: " << ans;
}
};
int main()
{
C obj;
obj.get_A_data();
obj.get_B_data();
obj.get_C_data();
obj.sum();
return 0;
}
Output
Enter value of a: 1
Enter value of b: 2
Enter value of c: 3
sum: 6
Function Overriding in C++
When a derived class or child class defines a function that is already defined in the base class or parent
class , it is called function overriding in C++. Suppose, the same function is defined in both the derived
class and the based class. Now if we call this function using the object of the derived class, the function of
the derived class is executed.

//example
#include <iostream>
using namespace std;
class base //single base class
{ public:
void print()
{
cout << "in a base class"<<endl;
cout<<a<<endl;
}
};
class derive : public base //single derived
class
{
public:
void print(){
cout<< "in a derive class"<<endl;
}
};
Int main(){
derive d;
d.print();
}

//output
In a derive class.
C++ Function Template
Templates are powerful features of C++ which allows us to write generic programs. • We can create a
single function to work with different data types by using a template. • A function template starts with
the keyword template followed by template parameter(s) inside <> which is followed by the function
definition. • It is used in generic programming. •
Syntax
template <class T>
T functionName(T parameter1, T parameter2, ...)
{ // code
}

//example

#include<iostream>
using namespace std;
template<class T>
T add(T a, T b){
return a+b;
}
int main()
{
int iresult,a =10,b=30;
float fresult,x =4.6,y=4.2;
iresult = add(a,b);
fresult = add(x,y);
cout<<"sum of two integers "<<iresult<<endl;
cout<<"sum of two fractional numbers:"<<fresult;
return 0;
}
Output
Sum of twos integers 40
Sum of two fractional numbers 8.8
Q.Wap to swap two integers,two floats and two characters using function template.

#include <iostream>
using namespace std;
template<class T>
void swap(T *a, T *b){
T temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int m =10,n=30;
float x=5.6,y=4.3;
char A ='a',B='b';
cout<<"value of m and n before swap "<<m<<" "<<n<<endl;
cout<<"value of x and y before swap "<<x<<" "<<y<<endl;
cout<<"value of A and B before swap "<<A<<" "<<B<<endl;
swap(&m,&n);
swap(&x,&y);
swap(&A,&B);
cout<<"value of m and n after swap "<<m<<" "<<n<<endl;
cout<<"value of x and y after swap "<<x<<" "<<y<<endl;
cout<<"value of A and B after swap "<<A<<" "<<B<<endl;
return 0;
}

output

value of m and n before swap 10 30


value of x and y before swap 5.6 4.3
value of A and B before swap a b
value of m and n after swap 30 10
value of x and y after swap 4.3 5.6
value of A and B after swap b a
Function template with multiple parameter
We can also use multiple parameter type in function template.for example
#include <iostream>
using namespace std; output
template <class T,class U>
void display(T x, U y)
{
cout<<x<<endl; 2 3.5
cout<<y<<endl; 3.5 2
} a 3
int main()
{
display(2, 3.5);
display(3.5,2);
display('a',3);
return 0;
}

Overloading a function template


We can also overload a function template in c++.//for example
#include <iostream>
using namespace std;
template<class A>
void func(A x)
{
cout << "Value of x: " <<x<< endl;
} output
template<class A,class B> Value of x: 20
void func(A y ,B z) Value of y: 2
{ Value of z: 2
cout << "Value of y: " <<y<< endl;
cout << "Value of z: " <<z<< endl;
}
int main()
{
func(20);
func(2,2);
return 0;
}
Errors
Errors are the problems or the faults that occur in the program, which makes the behavior of the program
abnormal.types of error.
➢Logical error
➢Syntax error
➢Linker error
➢Runtime error

Syntax errors are mistakes in the programming language's grammar rules, which make the program
unable to compile. A syntax error can be caused by various reasons, such as a missing semicolon,
unmatched braces, or incorrect variable declarations.

A logical error in C is a mistake in the implementation of the programmer's intended logic, leading to
incorrect results when the program is executed. The program compiles and runs without any errors or
issues, but the output isn't what the programmer expected.
Runtime errors
Unlike syntax errors, runtime errors do not prevent the code from being compiled, but they cause the
program to behave unexpectedly, crash, or produce incorrect output. Runtime errors are typically caused
by invalid input, zero division,

Linker errors happen when the linker cannot find the libraries or object code necessary to create a
running executable. This can happen either due to the wrong function prototyping or the usage of the
wrong header file.
Exception handling
• An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
• Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
• throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
• catch − A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an
exception.
• try − A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.
When Divide by zero error program when exception is not handled.

#include<iostream>
using namespace std;
int main(){
int a,b,c;
cout<<"enter values "<<endl;
cin>>a>>b;
c = a/b;
cout<<c;
return 0;
}
//divide by zero error program when exception is handled.
#include <iostream>
using namespace std;
int main()
{
int x,y,z;
cout<<"enter values"<<endl;
cin>>x>>y;
try{
if(y==0)
{
throw "divide by zero error";
}
z=x/y;
cout<<z;
}
catch( const char *c){
cout<<c;
}
return 0;
}

Output
enter values
4
0
divide by zero error
Multiple catch block
Multiple catch blocks are used when we have to catch a specific type of exception out of many
possible type of exceptions i.e. an exception of type char or int or short or long etc. Let's see the
use of multiple catch blocks with an example.

#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught integer " << x;
}
catch (float b){
cout<<"float caught "<<b;
}
catch (...) { //catch all block
cout << "Default Exception\n";
}
return 0;
}

Output
Default exception
Rethrowing an exception
Rethrowing an exception in C++ involves catching an exception within a try block and instead of
dealing with it locally throwing it again to be caught by an outer catch block. By doing this. we
preserve the type and details of the exception ensuring that it can be handled at the appropriate
level within our program.This approach becomes particularly valuable when managing exceptions
at multiple levels or when additional actions need to be performed before resolving the
exception.for example

#include<iostream>
using namespace std;
void sub(int i,int j)
{
try
{
if(i==0)
{
throw i;
}
else
{
cout<<"Subtraction result is: "<<i-j<<endl;
}
}
catch(int i)
{
cout<<"Exception caught inside sub()"<<endl;
throw;
}
}
int main()
{
try
{
sub(8,4);
sub(0,8);
}
catch(int k)
{
cout<<"Exception caught inside main()"<<k<<endl;
}
return 0;
}
Output
Subtraction result is: 4
Exception caught inside sub()
Exception caught inside main()

You might also like