0% found this document useful (0 votes)
80 views189 pages

Introduction to Programming for B.Tech

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)
80 views189 pages

Introduction to Programming for B.Tech

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

SESHADRIRAO

GUDLAVALLERUENGINEERINGCOLLEGE
(An Autonomous Institute with Permanent Affiliation to JNTUK, Kakinada)
Seshadri Rao Knowledge Village :: Gudlavalleru-521356

Academics Strengthening & Advancement (AS&A)

Department
of
Electronics and Communication Engineering

R-23

I [Link] – I Semester

INTRODUCTION TO PROGRAMMING

Learning Material

Prepared by: Faculty of ECE


R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

[Link]. Topic Page no.

Unit – I: Introduction to Programming and Problem Solving


History of Computers: What is Computer? Early computing 2
1
Devices, Generations
Basic organization of a computer: ALU, input-output units, 6
2
memory, program counter.
Introduction to Programming Languages
Basics of a Computer Program- Algorithms, flowcharts, 9
3
pseudo code.
Introduction to Compilation and Execution: What is compiler, 13
4
explain how programs are executed.
5 Primitive Data Types: List with range and size. 14
Keywords, Identifiers and Constants: Declaration of variables, 16
6
Identifiers and its rules. Declaration of constants.
Basic Input and Output, Operations: Formatted and 19
7 Unformatted I/O: scanf(), getch(), getche(), getchar(),
printf(), putch(), putchar().
8 Type conversion: implicit and explicit 21
Problem solving techniques: Algorithmic approach, 22
9
characteristics of algorithm
Problem solving strategies: Top-down approachand Bottom- 23
10
up approach.
Time and space complexities of algorithms: Calculating time 24
11 and space complexity for simple problems. Big Oh notation
for time complexity.

Unit – II: Control Structures


1 Selection Statements: simple if , if-else, else-if ladder, switch 36

2 Iteration statements (or) Loops: for, while, do-while 46

3 Unconditional branching or Jump statements: break and continue 52

Problem Solving:
4 Write a C program to generate electricity bill. 55

5 Write a C program to simulate a calculator using switch case. 56

6 Implement C code to find out the roots of the quadratic equation. 58

7 Develop C program to Check a number is palindrome or not. 60

8 Write a C program to find out given number is prime or not. 61

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26


R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

Unit – III :Arrays and Strings


1 Arrays definition and indexing 68

2 One dimensional array: Declaration Initialization 68


Two dimensional array: Declaration Initialization and 71
3
Multidimensional arrays
Memory Model : Storage of Array elements, base address, 72
4
accessing array elements.
5 Strings: Declaration, Initialization, 77

6 String handling functions 79

7 2D character arrays with strings. 81

Problem Solving:
Implement C program to Find the min and max of a 1-D integer 74
8
array
9 Write a C program to Perform linear search on1D array. 75

10 Develop C programto findout Additionof two matrices 76


Write a C program to concatenate two strings without built-in 82
11
functions.

Unit – IV: Pointers &User Defined Datatypes


1 Pointers: definition, declaration, initialization 90

2 de-referencing and address operators 94

3 Pointer Arithmetic 95

4 array manipulation using pointers 97

5 Pointers and strings 99

User Defined Data types


6 Structures: definition, Syntax, initialization and accessing, 103

7 Nested structures 107

8 Array of Structures 109

9 Array within structures 112

10 Unions: definition, syntax initialization and accessing 113

11 Differences between structure and union 118

Problem Solving:

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26


R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Write C program to find out sum of given array elements using 121
12
Pointers.
13 Develop C program to illustrate nested structure concept. 121
Implement C code to read ‘n’ students information using array of 122
14
structures concept.

Unit-V: Functions & File Handling


Introduction to Functions: definition, syntax, calling and 134
1
definition ,
2 Function call return types 137

3 Types of arguments 141


Parameter passing techniques: call by value and call by 142
4
reference.
5 Recursion 145

6 Modifying parameters inside function using pointers 149

7 Array as parameter to the function. 149

8 Scope and lifetime of variables: local and global variables, 151

9 storage classes: auto, static, extern and register. 153

File Handling
10 Definition of file, Types of files 157

11 file opening modes. 159

12 Basic file Operations: open, read/write and close 159


File I/O: fscanf(), fprintf(), fgets(), fputs(), fgetc(), fputc(), 160
13
fread() and fwrite()
14 Random access files: fseek(), ftell(), rewind() 165

Problem Solving:
Write a C program to find out GCD of given two numbers using 169
15
recursion.
16 Develop C program to access file using Random access methods. 170
Implement C code to illustrate Call by value and Call by 171
17
reference mechanisms.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26


R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

INTRODUCTION TO PROGRAMMING

Course Objectives
 To introduce students to the fundamentals of computer programming.
 To provide hands-on experience with coding and debugging.
 To foster logical thinking and problem-solving skills using programming.
 To familiarize students with programming concepts such as data types,
control structures, functions, and arrays.
 To encourage collaborative learning and teamwork in coding projects
Course Outcomes
A student after completion of the course will be able to
CO1: Understand basics of computers, the concept of algorithm and algorithmic
thinking.
CO2: Analyse a problem and develop an algorithm to solve it.
CO3: Implement various algorithms using the C programming language.
CO4: Understand more advanced features of C language.
CO5: Develop problem-solving skills and the ability to debug and optimize the
code

Course Content
UNIT I: Introduction to Programming and Problem Solving
History of Computers, Basic organization of a computer: ALU, input-output units,
memory, program counter, Introduction to Programming Languages, Basics of a
Computer Program Algorithms, flowcharts (Using Dia Tool), pseudo code. Introduction
to Compilation and Execution, Primitive Data Types, Variables, and Constants, Basic
Input and Output, Operations, Type Conversion, and Casting. Problem solving
techniques: Algorithmic approach, characteristics of algorithm, Problem solving
strategies: Top-down approach, Bottom-up approach, Time and space complexities of
algorithms.
UNIT II: Control Structures
Simple sequential programs, Conditional Statements (if, if-else, switch), Loops (for,
while, dowhile) Break and Continue.
UNIT III: Arrays and Strings
Arrays indexing, memory model, programs with array of integers, two dimensional
arrays, Introduction to Strings.
UNIT IV: Pointers & User Defined Data types
Pointers, dereferencing and address operators, pointer and address arithmetic, array
manipulation using pointers, User-defined data types-Structures and Unions.
UNIT V: Functions & File Handling
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Introduction to Functions, Function Declaration and Definition, Function call Return
Types and Arguments, modifying parameters inside functions using pointers, arrays as
parameters. Scope and Lifetime of Variables, Basics of File Handling.

Text Books
1. "The C Programming Language", Brian W. Kernighan and Dennis M. Ritchie,
PrenticeHall, 1988
2. Schaum’s Outline of Programming with C, Byron S Gottfried, McGraw-Hill
Education, 1996

Reference Books
1. Computing fundamentals and C Programming, Balagurusamy, E., McGraw-
Hill Education, 2008.
2. Programming in C, Rema Theraja, Oxford, 2016, 2nd edition.
3. C Programming, A Problem Solving Approach, Forouzan, Gilberg, Prasad,
CENGAGE, 3rd edition

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26


R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

UNIT-I
Introduction to Programming and Problem Solving
Syllabus

1.1 History of Computers

1.2 Basic organization of a computer


1.2.1 ALU
1.2.2 Input-output units
1.2.3 Memory
1.2.4 Program counter

1.3 Introduction to Programming Languages

1.4 Basics of a Computer Program

1.4.1 Algorithms
1.4.2 Flowcharts (Using Dia Tool)
1.4.3 Pseudo code

1.5 Introduction to Compilation and Execution

1.6 Primitive Data Types

1.7 Keywords, Variables and Constants

1.7.1 Keywords

1.7.2 Variables or Identifiers

1.7.3 Constants

1.8 Basic Input and Output Operations

1.9 Type Conversion, and Casting

1.10 Problem solving techniques: Algorithmic Approach

1.11 Problem solving strategies

1.11.1 Top-down approach

1.11.2 Bottom-up approach

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 1
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1.12 Time and space complexities of algorithms
1.1 History of Computers
What is a Computer?
A computer is an electronic machine that takes input from the user, processes the given
input and generates the output in the form of useful information.
Generations of Computers
The computer generations are classified into five generations
1. First generation (1946-1955) uses vacuum tubes.
2. Second generation (1956-1965) use transistors.
3. Third generation (1966-earlyy 1975) use integrated circuit.
4. Fourth generation (early 1976-1985) use LSI and VLSI.
5. Fifth generation (1986 – at present) use ULSI and artificial intelligence.

First generation (1946-1955) uses vacuum tubes


The first generation computers were vacuum tubes based machines. The characteristics of
these machines are;
Characteristics of First generation computers
 These computers are developed using vacuum tube technology.
 In these computers vacuum tubes are used for processing and magnetic drums are
used for data storing.
 These computers were unreliable
 These are the fastest computing devices of their times.
 These computers are very large in size and it occupies more space.
 It consumes more power and it produces more heat.
 The troubleshooting is more complicated.
 They are programmed only in machine language. So it is very difficult to program
and use.
 In these computers the input is based on punched cards and paper tapes and output
was in the form of printouts.
 Examples: ENIAC, EDVAC,UNIVAC

ENIAC (Electronic Numerical Integrator and Calculator)


EDVAC (Electronic Discrete Variable Automatic Computer)

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 2
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
UNVAC(Universal Automatic Computer)
Advantages
- Able to execute complex mathematical problems in an efficient manner.

Disadvantages
- These are not easy to program
- Very large in size and occupies more space
- It consumes more power and produces more heat
- Difficult to move from one place to another

Second Generation (1956-1965) use transistors:


In second generation computers transistors replaced vacuum tubes. Which were superior
to vacuum tubes. A transistor is made up of semiconductor material like germanium and
silicon.
Characteristics of second generation computers
 These machines were based on transistors.
 These were smaller in size compared to first generation.
 It consumes less power and produces less heat compared to first generation.
 The processing time of these computers was reduced from milliseconds to
microseconds.
 Assembly language was used to write the program.
 Example: PDP-8, IBM 1401 and IBM 7090.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 3
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Third Generation (1966-earlyy 1975) use integrated circuit
In third generation computers the transistors are replaced by integrated circuit(IC).
It consistsofhuge number of transistors and other components. The IC was invented by
jack kilby.
Characteristics of third generation computers
 These computers are based on integrated circuits(IC).
 The processing time of these computers was reduced from micro seconds to
nanoseconds.
 It is portable in size and more reliable.
 These computers are consumed less power and generated less heat.
 These computers the users are interacted through keyboards and monitors.
 These computers were capable of running many programs simultaneously.
 These computers also understand high level language. So the users are easy to
interact to the computers.
 Examples NCR 395, and B6500.

Fourth generation (early 1976 - 1985) use LSI and VLSI.


The fourthgeneration computers are extension of third generation computers.
Fourthgenerationcomputers were marked by the use of very largescale integrated
[Link] were used tobuild computers.
Characteristics of forth generation computers
 Fourth generation computers are microprocessor based systems.
 These computers are very small in size.
 These computers were very cheap among all other generations.
 They are very portable and more reliable.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 4
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 These machines generate negligible amount of heat.
 Interconnection of computer was possible.
 The production cost was very low.
 Example. Apple11, Altair 8800 and CRAY-11

Fifth generation (1986 – on word) use ULSI and artificial intelligence


The period of fifth generation is 1980-till date. In the fifth generation, VLSI
technology became ULSI(Ultra Large Scale Integration) technology.
Characteristics of Fifth Generation Computers
 This generation is based on parallel processing hardware and AI (Artificial
Intelligence) software
 All the high-level languages like C and C++, Java, .Net etc., are used in this
generation.
 Development of true artificial intelligence
 Development of Natural language processing
 Advancement in Parallel Processing
 Advancement in Superconductor technology
 More user-friendly interfaces with multimedia features
 Availability of very powerful and compact computers at cheaper rates.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 5
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1.2 Basic organization of a computer
A computer is an electronic device which may be used to perform various computations
involving arithmetic and logical operations. The following figure shows the major
components of a computer.

As seen in the figure, the major components in a computer are the central processing unit
(CPU), input device(s), output devices(s) and the memory. These components interact
with each other using buses
Central Processing Unit (CPU)
 The CPU is the unit in which all processing activities take place. The CPU is a
classic example of a very large scale integrated (VLSI) electronic circuit that
consists of the arithmetic and logic unit (ALU), the control unit (CU) and some
registers. The following figure shows the layout of a CPU.

 The ALU contains circuits using which various arithmetic and logical operations
may be executed. These circuits include adders (for addition), subtractors (for
subtraction), comparators (for comparison of operands), etc.
 The CPU, also known as the brain of a computer, is the unit which is responsible
for generating control signals. These control signals control the working of the
various components within a computer.
 The registers present inside the CPU may be considered to be a set of high-speed
storage devices. Some of these registers are assigned the task of holding special

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 6
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
data or instructions. Such registers are known as special purpose registers, whereas
others are known as general purpose registers.
 The units present inside the CPU interact with each other through an internal bus.
 Signals generated by the CPU also control the activities of the various components
within the CPU.
 Apart from the internal bus, three other buses also interface the CPU. The control
bus carries control signals generated by the CPU to the memory and all the
peripherals.
 The address bus carries an address to locate a word in the memory. Finally, the
data bus is used to carry data and information to and from between the
components of the computer.
 In addition to the units mentioned so far, modern day CPUs are also equipped with
high-speed, on-chip memory units known as the cache memory.

Input Devices
Input devices are the ones through which users are allowed to input data and other
instructions to the computer. The most popular choices for input devices are the keyboard
and the mouse. Other examples include scanners, readers, etc.
Output Devices
Just as input devices are used to convey messages to the computer, output devices are
used by the computer to convey messages back to the users. The most common output
device that almost all computers have is the monitor. The monitor is used to display the
results of computations, messages, etc. Other examples of output devices are printers,
speakers, plotters, etc.
The input and the output devices are sometimes known as peripheral devices. These
auxiliary devices may be connected to a computer and used. They are auxiliary because
their existence within a computer is not mandatory unlike the CPU or the memory.
Memory
Memory/storage unit is the component of a computer that serves data storage purposes.
These units are of varying access speeds and volatility. Access speed refers to the time
taken to store/retrieve data from the memory. Volatility refers to the duration of time or
the conditions under which data is stored in the memory. Based on these characteristic
features, the computer’s memory may be categorized into different types. The following

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 7
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
figure shows the classification of the computer’s memory.

 As shown in the figure, the memory is broadly classified into primary memory and
secondary memory.
 The primary memory, also known as the main memory, is so called because the
CPU can directly interact with it through the data bus and the address bus. The
main memory is of two major types, the random access memory (RAM) and the
read only memory (ROM).
 The RAM is a volatile memory that stores instructions and data related to the
program currently being executed. The RAM is volatile because it would lose all
the information stored in it as soon as the power to the computer is switched off.
 The ROM is a read-only, non-volatile memory. The ROM does not permit any
write operation and is non-volatile because the information stored in it would be
retained even after the computer has been switched off. Apart from other
important routines, the ROM houses the boot strap loader. The boot strap loader is
a system software that is responsible for loading the operating system from the
secondary memory into the RAM.
 The secondary memory, also known as auxiliary memory, is a large depository of
non-volatile storage space that can store information for as long as we want. The
secondary memory is slower compared to the access time of the primary memory.
The hard disk, flash drives, etc. are some examples of secondary memory.
Program Counter
A program counter is a register in a computer processor that contains the address
(location) of the instruction being executed at the current time. As each instruction
gets fetched, the program counter increases its stored value by 1 in order to fetch the
next instruction in the sequence. When the computer restarts, the program counter
normally reverts to 0.
1.3 Introduction to Programming Languages
Programming languages are used to write computer programs and applications, and to

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 8
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
control and manipulate computer systems. There are many different programming
languages, each with its own syntax, structure, and set of commands. Some of the most
commonly used programming languages include C, C++, Java, Python, JavaScript, and
C#. The choice of programming language depends on the specific requirements of a
project, including the platform being used.
A computer program is a set of instructions which when executed in sequence performs a
task. For example we may write a program to add two integer numbers. It is clear that this
program would contain three sets of instructions; the first set would enable users to input
the data, the second set to add the numbers and the third set to display the result.
However, more often than not, the problems which a computer is supposed to solve would
be more complex than this. Such complex problems would invariably require complex
solutions. These solutions involve a lot of complex arithmetic operations and logical
decision making. Hence, the need of the hour here is a tool which would enable us to
represent the logic required in the program and make it possible to transform the logic to
an equivalent set of instructions which when executed by the computer would solve the
problem. Algorithms and flowcharts are two such tools. These tools are independent of
the programming language as well as the target machine. Thus, the logic represented
using one of these tools may be used to write programs in any language of the
programmer’s choice.
1.4 Basics of a Computer Program
1.4.1 Algorithm
An algorithm is a finite set of unambiguous instructions which, when executed, performs
a task correctly. There are three characteristics of an algorithm. They are:
 The number of steps required to perform the task should be finite.
 Each of the instruction in the algorithm should be unambiguous in nature;
meaning on the execution of each such instruction, the outcome should be definite
and predictable.
 Finally, the algorithm should solve the problem correctly.

An algorithm can be represented using English like statements, or using pseudo code or
even using a flowchart. However, the most popular convention is the pseudo code.
Example 1: Develop an algorithm to find the average of three numbers
Algorithm AVERAGE

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 9
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

Example 2: Develop an algorithm to divide one number by another and find the quotient.

Example 3: Develop an algorithm to find the maximum of two numbers.

Example 4: Develop an algorithm to find the sum of the first N natural numbers

1.4.2 Flowchart
A flow chart is a pictorial or graphical representation of an algorithm. Just like the
algorithm, the flowchart is also a tool to represent logic. Unlike the algorithm, the
flowchart uses some standard notation to graphically represent the logic. The following
table shows various symbols used in a flowchart.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 10
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

Example 1: Draw the flowchart to find the average of three numbers

Example 2: Draw the flowchart to divide one number by another and find the quotient.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 11
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

Example 3: Draw the flowchart to find the maximum of two numbers.

Example 4: Draw the flowchart to find the sum of the first N natural numbers

1.4.3 Pseudocode
Pseudocodes are a means to represent an algorithm in a coded form. The specifications

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 12
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
used in a pseudocode are syntactically not stringent as in a program code. However, they
represent the steps of an algorithm in a coded form which very closely resembles program
code. Given a pseudocode, translation of the same into program code is relatively easy. A
pseudocode may be considered to be an intermediate code between an algorithm and
program code. The pseudocode for the algorithm in Example 4 is as follows:

1.5 Introduction to Compilation and Execution


The compilation is the process of converting the source code of the C language into
machine code. As C is a high-level language, it needs a compiler to convert it into an
executable code so that the program can run on our machine.
Executing a program written in c involves a series of steps. These are:
 Creating the program.
 Compiling the program.
 Linking the program with functions that are needed from c library.
 Executing the program.
Creating: we can create or write a c program using turbo c –IDE. In this, [Link] will be
there double click on this we get blue screen then type the c program and save the file
using F2 key with an extension..c .
Compiling: In turbo C compiler use Alt+F9 to compile the c-program, to check whether
the source code contains any errors. If source contains errors then goto step1 to modify
the source program. Aftercompiling the source program we get .obj file.
Linking: This process is inbuilt in step2 in turbo Compiler. The .obj file is given as input
to linker. The linker checks for errors. If object code contains any errors then goto step1
to modify. If the object code is error free then linker converts .obj files into .exe file.
Executing: CTRL+F9 in Turbo C.
Pictorially the above steps can be shown as given below.
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 13
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

1.6 Primitive Data Types


Every variable in C has a data type. Data type specifies the size and type values that can
be stored. C language supports 2 different types of data types,
 Primary data types or Primitive Data Types
o These are fundamental data types in C namely integer (int),
floating(float), character (char) and void.
 Derived data types
o Derived data types are like arrays, functions, structures and pointers.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 14
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

Integer type
 Integers are used to store whole numbers.
 Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

int or signed int 2 -32,768 to 32767

unsigned int 2 0 to 65535

short int or signed short int 1 -128 to 127

long int or signed long int 4 -2,147,483,648 to


2,147,483,647

unsigned long int 4 0 to 4,294,967,295

Float type
 Floating types are used to store real numbers.
 Size and range of Integer type on 16-bit machine.

Type Size(bytes) Range

float 4 3.4E-38 to 3.4E+38

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 15
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

double 8 1.7E-308 to 1.7E+308

long double 10 3.4E-4932 to 1.1E+4932

Character type
 Character types are used to store characters value.
Size and range of Integer type on 16-bit machine

Type Size(bytes) Range

char or signed char 1 -128 to 127

unsigned char 1 0 to 255

Void type
void type means no value. This is usually used to specify the type of functions.
1.7 Keywords, Identifiers and Constants
1.7.1 Keywords
Keywords in C are reserved words that have predefined meanings and specific purposes
within the C programming language. These words cannot be used as identifiers (such as
variable names, function names, or struct names) because they are integral to the
language's syntax and functionality.
There are 32 keywords in the C language as per the C99 standard. These keywords are
always written in lowercase.

A list of C keywords includes:


auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for,
goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef,
union, unsigned, void, volatile, and while.
These keywords are used to define data types (e.g., int, char, float), control program flow
(e.g., if, else, for, while), manage memory (e.g., auto, static), and perform other
fundamental operations within a C program. For example, int is used to declare integer
variables, if and else are used for conditional statements, and return is used to exit a
function and optionally return a value.
1.7.2 Identifiers or Variables
A variable is a data name that may be used to store a data value. A variable may take
different values at different times during execution.
Rules for defining variables
1. A variable can have alphabets, digits, and underscore.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 16
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
2. A variable name can start with the alphabet, and underscore only. It can't start with a
digit.
3. No whitespace is allowed within the variable name.
4. A variable name must not be any reserved word or keyword, e.g. int, float, etc.
Some examples of valid variable names are:

Invalid examples include:

Further examples of variable names and their correctness are given in the following table.

Declaration of variables
After defining variable names, we must declare them to the compiler. Declaration does
two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.

The syntax for declaring a variable is


Data-type v1,v2,......vn;
Where v1,v2,......vn are the names of variables. Variables are separated by commas. A
declaration statement must end with a semicolon. For example, valid declarations are:
int a;
int number, total;
float area;

Initializing values to variables


Values can be assigned to variables using the assignment operator = as follows:
The syntax is:
Variable_name = value;
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 17
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
E.g.: int a=20;
bal=75.84;
yes=‟x‟;
Note: We can also initialize more than one variable in one statement using multiple
assignment operators.
e.g.: a=b=c=10;
1.7.3 Constants
Constants in C refer to fixed values that do not change during execution of a program.
The following figure shows categorization of constants.

Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers
namely decimal integers, octal integers and hexadecimal integer.
1. Decimal integers consists of a set of digits 0 to 9 preceded by an optional – or
+ sign.
Valid examples of decimal integer constants are:
123 -321 0 654321
Invalid Examples: 15 750 20,000 $1000
2. Octal integers consist of any combination of digits from set 0 to 7, with a
leading 0.
Examples: 037 0 0435 0551
3. Hexadecimal integers are a sequence of digits preceded by 0x or 0X. This
may also include alphabets A to F(represents numbers from 10 to 15).
Examples: 0x2ef, 0X, 0XABD
Real constants
Integer numbers are inadequate to represent quantities that vary continuously, such as
distances, heights, temperatures and so on. These quantities are represented by numbers
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 18
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
containing fractional parts like 17.548. Such numbers are called as real constants.
Examples: 0.0083 -0.75 435.36 +247.0
A real number can be expressed in exponential notation.
Mantissa e exponent
i. The mantissa is either a real number expressed in decimal notation or an integer
ii. The exponent is integer number with optional plus or minus sign.
iii. The letter e separating the mantissa and the exponent can be written in either
lowercase or uppercase i.e., 0.65e4, 12E-2
Character constants
A character constant consists of a single character enclosed in single quotes.
Example: ‘a’ ‘c’ ‘D’
String constants: A string constant is a sequence of characters enclosed in double
quotes.
Example: “Gudlavalleru” “23481A0501” “a”
Declaration of constants
We define a constant in C language using the const keyword. Also known as a const
type qualifier, the const keyword is placed at the start of the variable declaration to
declare that variable as a constant.
Syntax:
const data_type var_name = value;

Example program:

#include <stdio.h>
void main()
{
const int int_const = 25;
const char char_const = 'A';
const float float_const = 15.66;
printf("Printing value of Integer Constant: %d\n", int_const);
printf("Printing value of Character Constant: %c\n", char_const);
printf("Printing value of Float Constant: %f", float_const);
}
1.8 Basic Input and Output Operations
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 19
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Formatted and Unformatted I/O
scanf():
Formatted input refers to an input data that has been arranged in a particular format.
Ex: 15.73 123 john
The above line contains three pieces of data, arranged in a particular form. Such data has
to be read conforming to the format of its appearance.
The first part of the data should be read into a variable float, the second into int, the third
part into char. This is possible in C using the scanf() is:
scanf(“Control String”, arg 1, arg 2,..............arg n);
The control string specifies the field format in which the data is to be entered and the
arguments arg1, arg2,................arg n specify the address of locations where the data is
stored.
Control string and arguments are separated by comma(,).Control string contains field
specifications, which direct the interpretation of input data. It may include:
 Field specifications consisting of the conversion character %, a data type
character, and optional number specifying the field width.
 Blanks, tabs, or newlines.

Blanks, tabs and newlines are ignored. The data type character indicates the type of data
that is to be assigned to the variable associated with the corresponding argument. The
field width specifier(w) is optional.
By using scanf() statement we can read three types of values. They are:
1. Inputting Integer numbers: The field specification for reading an integer number
is %wd.
2. Inputting Real numbers: The field specification for reading a real number is %wf.
3. Inputting character strings: The field specification for reading a character or string
is %wc or %ws.

printf():
The use of printf function for printing captions and numerical results. It is highly
desirable that the outputs are produced in such a way that they are understandable and are
in an easy-to-use form.
The general form of printf statement is:

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 20
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf(“Control String”, arg 1,arg 2,............arg n);
Control String consists of three types of items:
 Characters that will be printed on the screen as they appear.
 Format specifications that define the output format for displaying of each item.
 Escape sequence characters such as \n, \t, \b.

The control string indicates how many arguments follow and what their types are. The
arg1,arg 2,..........arg n are the variables whose values are formatted and printed according
to the specifications of the control string. The arguments match in number, order and type
with the format specifications.
By using printf statement we can produce four types of values. They are:
 Output of Integer Numbers: The format specification for printing an integer number is
%wd.
 Output of Real Numbers: The output of a real number may be displayed in decimal
notation using the following format specification is %wf.
 Printing of a String Character: A single character can be displayed in a desired
position using the format %wc.
 Printing of strings: The format specification for outputting strings is similar to that of
real number. The format specification is %ws

1.9 Type conversion


The conversion from one data type to another data type is known as Type Conversion. C
provides two types of Type Conversion techniques.
1. Implicit type conversion or Automatic type conversion.
2. Explicit type conversion or Type casting

Implicit or Automatic type conversion


When an operator has operands of different types, they are converted to a common type
according to semantic rules of a language. This is known as “automatic type
conversion”, because it is done by the compiler on its own, without any external trigger
from the user. In general, the only automatic conversions are those that convert a
“narrower” operand into a “wider” one without losing information.
Generally, a smaller data type is promoted to a larger data type to prevent data loss. For
example, if an int and a float are involved in an arithmetic operation, the int will be

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 21
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
implicitly converted to a float.
For example if a float and double datatypes are involved in the operation, then the float
will be implicitly converted to double.
Explicit type conversion
Explicit conversion in C, also known as type casting, is the manual conversion of a value from one data type

to another. This is performed by the programmer using a cast operator (). The datatype name to
which we want to convert is given inside the cast operator. The syntax is as follows:
(datatype_name) expression;
Where datatype_name is one of the standard C data types. The expression may be a
constant, variable or an expression.
Example:
#include<stdio.h>
main()
{
float x=1.2;
int sum;
sum=(int)x+1;
printf(“sum=%d”,sum);
}
Output:
Sum=2

3.1 Problem solving techniques: Algorithmic Approach


Procedure or Steps Involved in Problem Solving:
A computer cannot solve a problem on its own. One has to provide step by step solutions
of the problem to the computer. In fact, the task of problem solving is not that of the
computer. It is the programmer who has to write down the solution to the problem in
terms of simple operations which the computer can understand and execute. In order to
solve a problem by the computer, one has to pass though certain stages or steps. They are
1. Understanding the problem
2. Analyzing the problem
3. Developing the solution
4. Coding and implementation.
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 22
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1. Understanding the problem: Here we try to understand the problem to be solved in
totally. Before with the next stage or step, we should be absolutely sure about the
objectives of the given problem.
2. Analyzing the problem: After understanding thoroughly the problem to be solved, we
look different ways of solving the problem and evaluate each of these methods. The idea
here is to search an appropriate solution to the problem under consideration. The end
result of this stage is a broad overview of the sequence of operations that are to be carries
out to solve the given problem.
3. Developing the solution: Here the overview of the sequence of operations that was the
result of analysis stage is expanded to form a detailed step by step solution to the problem
under consideration.
4. Coding and implementation: The last stage of the problem solving is the conversion
of the detailed sequence of operations in to a language that the computer can understand.
Here each step is converted to its equivalent instruction or instructions in the computer
language that has been chosen for the implantation.
3.2 Problem solving strategies
There are typically two primary ways to approach problem-solving - "top-down
approach" and "bottom-up approach".
1.11.1 Top-down approach
Top-Down Approach is an approach to design algorithms in which a bigger problem is
broken down into smaller parts. Thus, it uses the decomposition approach. This approach
is generally used by structured programming languages such as C, COBOL, FORTRAN.
The drawback of using the top-down approach is that it may have redundancy since every
part of the code is developed separately. Also, there is less interaction and
communication between the modules in this approach.
The implementation of algorithm using top-down approach depends on the programming
language and platform. Top-down approach is generally used with documentation of
module and debugging code.
1.11.2 Bottom-up approach
Bottom-Up Approach is one in which the smaller problems are solved, and then these
solved problems are integrated to find the solution to a bigger problem. Therefore, it uses
composition approach.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 23
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
It requires a significant amount of communication among different modules. It is
generally used with object oriented programming paradigm such as C++, Java, and
Python. Data encapsulation and data hiding is also implemented in this approach. The
bottom-up approach is generally used in testing modules.
1.12 Time and Space Complexities of Algorithms
Time Complexity
Time complexity is defined as the amount of time taken by an algorithm to run, as a
function of the length of the input. It measures the time taken to execute each statement
of code in an algorithm and then the total execution time of an algorithm is obtained.
Space complexity
Space complexity refers to the total amount of memory space used by an
algorithm/program, including the space of input values for execution. Calculate the space
occupied by variables in an algorithm/program to determine the space complexity.
Assignment Cum Tutorial Questions

Questions

[Link] Short Answer Questions: BL


What is the purpose of declaring variables in a program? Name two rules for
1. creating valid identifiers in programming. L1

Name a problem-solving strategy that involves breaking a problem into


2. L1
smaller sub-problems.

3. Explain the role of pseudo code in the software development process L1

4. What does space complexity measure in algorithm analysis? L1

5. Define algorithm and flowchart L1


What does time complexity measure in algorithm analysis? L1
6.
What is a data type? What are primitive data types in C? L1
7

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 24
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

Describe about basic I/O operations with examples. L1


8

Classify constants in C L1
9

10 Define a keyword L1

1.1 History of Computers

Objective Questions:

1. Who is known as the "Father of the Computer"?

A) Alan Turing
B) Charles Babbage
C) Bill Gates
D) Steve Jobs

2. What was the first mechanical computer called?

A) ENIAC
B) UNIVAC
C) Analytical Engine
D) Abacus

3. The first generation of computers used which technology?

A) Transistors
B) Vacuum tubes
C) Integrated circuits
D) Microprocessors

4. ENIAC, one of the earliest electronic general-purpose computers, was developed in


which country?

A) UK
B) Germany

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 25
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
C) USA
D) Japan

5. In which decade did personal computers (PCs) become popular?

A) 1950s
B) 1960s
C) 1970s
D) 1980s

Descriptive Questions

[Link] Questions BL

1 Explain about the first and second generation computers in detail. L2

2 Explain briefly the history of computers L2

1.2 Basic organization of a computer


Objective Questions

1. Which of the following is NOT a basic unit of a computer?

A) Input Unit
B) Storage Unit
C) Output Unit
D) Display Unit

2. What is the main function of the Arithmetic Logic Unit (ALU)?

A) Store data
B) Perform calculations and logical operations
C) Display output
D) Control hardware devices

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 26
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
3. The Control Unit is responsible for

A) Performing arithmetic operations


B) Controlling the flow of data and instructions
C) Storing data
D) Connecting peripherals

4. Which of the following represents the correct basic organization of a computer?

A) Input → Output → Processing → Storage


B) Storage → Input → Processing → Output
C) Input → Processing → Storage → Output
D) Input → Storage → Output → Processing

5. Which component temporarily holds data and instructions that are being
processed?

A) Hard Disk
B) RAM
C) ROM
D) Monitor

6. What part of the computer interprets instructions and initiates control


operations?

A) CPU
B) Input Unit
C) RAM
D) Output Unit

Descriptive Questions

[Link] Questions BL

1 Explain in detail about the basic organization of a computer? L1

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 27
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1.3 Introduction to Programming Languages
Objective Questions:

1. Which of the following is a high-level programming language?


A. Assembly
B. Machine code
C. Python
D. Binary

2. What is the main purpose of a compiler?


A. To execute programs directly
B. To convert high-level code into machine code
C. To debug programs
D. To create user interfaces

3. Which language is considered the first high-level programming language?


A. Python
B. COBOL
C. FORTRAN
D. Java

4. Which of the following is an interpreted language?


A. C
B. Java (compiled to byte code)
C. Python
D. Assembly

Descriptive Questions

[Link] Questions BL

1 What is the difference between a compiled and an interpreted language? L1

2 Why do we use high-level programming languages instead of machine L1


code?.

1.4 Basics of a Computer Program: Algorithms

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 28
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Objective Questions:

1. What is an algorithm?
A. A computer language
B. A step-by-step procedure to solve a problem
C. A hardware component
D. A debugging tool

2. Which of the following best describes a computer program?


A. A physical part of the computer
B. A set of instructions written in natural language
C. A collection of data stored on the computer
D. A set of instructions written to perform a specific task

3. Which characteristic is important for a good algorithm?


A. Ambiguity
B. Complexity
C. Finiteness
D. Randomness

4. What does a flowchart represent?


A. The size of a program
B. The logic of an algorithm using symbols
C. The speed of a program
D. The storage structure of a program

Descriptive Questions
[Link] Questions BL

1 What is an algorithm? List advantages of using algorithms. L1

1.5 Introduction to Compilation and Execution


Objective Questions

1. What is the role of a compiler in program execution?


A. To write code automatically

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 29
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
B. To convert source code into machine code
C. To store data
D. To test internet speed

2. Which of the following is the correct order of compilation and execution?


A. Execution → Compilation → Writing code
B. Writing code → Execution → Compilation
C. Writing code → Compilation → Execution
D. Compilation → Writing code → Execution

3. What file is usually generated after successful compilation?


A. Source code file
B. Executable file
C. Text file
D. Debug log

4. Which tool directly executes the source code line by line?


A. Compiler
B. Linker
C. Interpreter
D. Debugger

Descriptive Questions
[Link] Questions BL

1 What is the difference between compilation and execution? L1

2. Explain what an interpreter does. L2

1.6 Primitive Data Type


Objective Questions:

1. Which of the following is a primitive data type in most programming languages?


A. Array
B. String

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 30
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
C. Integer
D. Object

2. What does the Boolean data type represent?


A. Decimal numbers
B. Text data
C. True/False values
D. Memory addresses

3. Which primitive data type is typically used to store single characters?


A. int
B. float
C. char
D. string

Descriptive Questions
[Link] Questions BL

1 Define a primitive data type? Why are primitive data types important in L1
programming?

1.7 Keywords, Variables, and Constants


Objective Questions:

1. What is a variable in programming?


A. A fixed value that never changes
B. A type of loop
C. A named location in memory to store data
D. An error in the code

2. Which of the following is true about a constant?


A. Its value can be changed during execution
B. It is used only for loops
C. Its value cannot be changed once assigned
D. It is always a string

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 31
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
3. Which of the following is a valid variable name?
A. 2value
B. value_1
C. #total
D. int

Descriptive Questions
[Link] Questions BL

1 Define a Keyword in C? List a few keyword in C. L1

2. Defind an identifier? Write the rules of identifier. L1

3 Explain briefly about types of constants in C L1

1.8 Basic Input and Output Operations

Objective Questions:

1. Which function is commonly used to display output on the screen in many


programming languages like C or Python?
A. input()
B. cin
C. print() or printf()
D. read()

2. What is the purpose of the input () function in Python?


A. To print text
B. To assign variables
C. To take user input
D. To exit the program

3. In C++, which object is used to take input from the user?


A. cout
B. cin
C. print
D. scanf

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 32
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Descriptive Questions
[Link] Questions BL

1 Explain the basic input and output operations in C L1

1.9 Type Conversion, and Casting


Objective Questions:

1. What is type conversion?


A. Converting a program into a function
B. Converting one data type into another
C. Changing the variable name
D. Saving data into a file

2. What is explicit type casting?


A. Automatic conversion done by the compiler
B. Manually converting a data type using a cast operator
C. Using a debugger
D. None of the above

3. Which of the following is an example of implicit type conversion?


A. float x = (float) 10;
B. int x = 5 + 2.5;
C. int x = (int) 3.9;
D. String s = [Link](10);

Descriptive Questions
[Link] Questions BL

1 What is the difference between implicit and explicit type conversion? L1


Explain in detail

1.10 Problem solving techniques


Objective Questions:

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 33
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1. What is the first step in problem-solving?
A. Writing the code
B. Identifying the problem
C. Testing the program
D. Compiling the program

2. Which of the following is a common problem-solving technique in programming?


A. Debugging
B. Algorithm design
C. Typing speed
D. Memorization

3. Which tool helps visualize the logic before coding?


A. Compiler
B. Flowchart
C. Keyboard
D. Memory unit

Descriptive Questions
[Link] Questions BL

1 Explain the procedure of proble solving in C? L1

1.11 Problem solving strategies


Objective Questions:

1. Which strategy involves solving a problem by working backward from the goal?
A. Divide and conquer
B. Bottom-up
C. Backtracking
D. Simulation

2. Which of the following is NOT a common problem-solving strategy?


A. Brainstorming
B. Debugging

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 34
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
C. Divide and conquer
D. Compilation

Descriptive Questions
[Link] Questions BL

1 Explain about Problem solving strategies: Top-down approach, Bottom-up L1


approach in C.

1.12 Time and space complexities of algorithms

Objective Questions:

1. What does time complexity measure?


A. The amount of memory used
B. The time it takes to compile the code
C. The number of steps an algorithm takes to complete
D. The size of the output

2. What does space complexity refer to?


A. The size of the program file
B. The memory required by an algorithm during execution
C. The execution time of a function
D. The number of processors used
Descriptive Questions
[Link] Questions BL

1 Define time complexity and space complexity? L1

UNIT-II
CONTROL STRUCTURES
Syllabus:

2.1. Simple sequential programs Conditional Statements: simple if, if-else, else-if ladder,
switch

2.2. Loops (or) Iteration statements: for, while, do-while


Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 35
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
2.3. Unconditional branching: break and continue

Learning Outcomes:

At the end of the unit student will be able to:


 Understand the control statements in C.
 solve moderate problems on computer using control statements in C.

Learning Material
2.1 CONTROL STATEMENTS:
Controlling the flow of program is very important aspect of programming. Control flow
relates to the order in which the operations of a program executed.
Two types of control structures:
 Selection/Branching Statements
 Iteration/loop Statements
2.1.1 SELECTION STATEMENTS:
A selection statement selects among a set of statements depending on the value of a
controlling expression.
The selection statements are:
 if statement
 switch statement

C has four kinds of if statements that permit the execution of a single statement or a
block of statements based on the evaluation of a test expression. The statements are
1. if
2. if-else
3. if-else-if
4. nested if

1. if Statement:

An if statement consists of a Test expression followed by one or more statements. It is a


one-way decision statement.

Syntax:

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 36
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
if(Text Expr)
{
/*statement(s) will execute if the Test expression is true*/
}
 If the Test expression evaluates to true, then the block of code inside the 'if'
statement will be executed.
 If the Test expression evaluates to false, then the first set of code after the end of
the 'if' statement (after the closing curly brace) will be executed.

Flow Diagram

Example
#include<stdio.h>
void main()
{
int a=10; /*local variable declaration*/
if(a<20)
{
printf(“a is less than 20\n”);
}
printf(“The value of a :%d”,a);
}

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 37
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
When the above code is compiled and executed, it produces the following result −

a is less than 20
The value of a: 10
C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.

2. if-else statement:
It is a two-way decision statement. Similar to one-way decision, the decision here is
based on the test expression.

Syntax
if(Text Expr)
{
/*statement(s) will execute if the Test expression is true*/
}
else
{
/*statement(s) will execute if the Test expression is false*/
}

 If the Test expression evaluates to true, then if block will be executed.


 Otherwise, else block will be executed.
Flow Diagram

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 38
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Example
#include<stdio.h>
void main()
{
int a=10; /*local variable declaration*/
if(a<20)
{
printf(“a is less than 20\n”);
}
else
{
printf(“a is not less than 20\n”);
}
}
When the above code is compiled and executed, it produces the following result

a is less than 20
3. if-else-if Statement: (else-if ladder)
It is a multi-way decision statement. These are used to test various conditions.

When using if-else-if statements, there are few points to keep in mind −
 An if can have zero or one else's and it must come after any else if's.

 An if can have zero to many else if's and they must come before the else.

 Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax
if(Test Expr1)
{
/*statement(s) will execute if the Test expression1 is true*/
}
else if(Test Expr2)

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 39
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
{
/*statement(s) will execute if the Test expression2 is true*/
}
.
.
else if(Test ExprN)
{
/*statement(s) will execute if the Test expressionN is true*/
}
else
{
/*executes when the none of the above condition is true*/
}
Flow Diagram

Example
#include<stdio.h>
void main()
{
int a=100; /*local variable declaration*/
if(a= =20)
{
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 40
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf(“Value of a is 20\n”);
}
else if(a==30)
{
printf(“Value of a is 30\n”);
}
else if(a==40)
{
printf(“Value of a is 40\n”);
}
else
{
printf(“None of the values is matching”);
}
}
When the above code is compiled and executed, it produces the following result

None of the values is matching

4. Nested if statement
 When any if statement is written under another if statement, this cluster is
called nested if.
 It is always legal in C programming to nest if-else statements, which
means you can use one if or else if statement inside another if or else if
statement(s).

Syntax
if(Test Expr1)

/*Statements will execute if the test expr 1 is true*/

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 41
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
if(Test Expr2)

/*Statements will execute if both test expr1 and test expr2 is true*/

Example
#include<stdio.h>
void main ( )
{
int a, b, c;
printf (“\n enter three numbers :”);
scanf (“%d%d%d ”, &a,&b,&c);
if(a > b)
{
if(a>c)
{
printf(“\n a is big”);
}
Else
{
printf(“\n c is big”);
}
}
Else
{
if (b > c)
{

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 42
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf(“\n b is big”);
}
Else
{
printf(“\n c is big”);
}
}
When the above code is compiled and executed, it produces the following result :
Enter three numbers:
264
b is big
Dangling else problem:
In nested if statements, when a single “else clause” occurs, the situation happens to be
dangling else. For example:
if(condition)

if(condition)

if(condition)

else

printf(“dangling else!”);

1. In such situations, else clause belongs to the closest if statement which is


incomplete that is the innermost if statement.
2. However, we can make else clause belong to desired if statement by enclosing all
if statements in block outer to which if statement to associate the else clause.
For example:

if(condition)

if(condition)

if(condition)

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 43
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
}

else

printf(“\n else associates with the outermost if statement”);

switch statement:
A switch case statement is a multi-way decision statement that is simplified version of if-
else block that evaluates only one variable.
Syntax:
switch (expr)

case constant1: stmtList1;

break;

case constant2: stmtList2;

break;

-------------

-------------

default: stmtListN;

The following rules apply to a switch statement −

 The expression used in a switch statement must have an integral or enumerated type, or be of a
class type in which the class has a single conversion function to an integral or enumerated type.
 You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in the switch, and
it must be a constant or a literal.
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 44
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.

Flow Diagram

Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,ch,c;
clrscr();
printf(“\nenter a and b values”);
scanf(“%d%d”,&a,&b);
printf(“\[Link]\[Link]\[Link]\[Link]”);
scanf(“%d”,&ch);
switch(ch)

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 45
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: c=a/b;
break;
default: printf(“\nenter valid choice”);
}
printf(“\nresult=%d”,c);
getch();
}
When the above code is compiled and executed, it produces the following result
enter a and b values
56
1. Addition 2 .Subtraction [Link] [Link] 1
result=11
2.2 ITERATION STATEMENTS:
Iterative statements are used to repeat the execution of a list of statements, depending on
the value of an integer expression.
C language supports three types of iterative statements also known as looping statements.
They are:

 while loop
 do-while loop
 for loop

1. while loop
The while loop provides a mechanism to repeat one or more statements while a
particular condition is true.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 46
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Syntax:
statement x;
while(condition)
{
statement block;
}
statement y;
 In the while loop, the condition is tested before any of the statements in the
statement block is executed.

 If the condition is true only the statement block will be executed otherwise
(if the condition is false), the control will jump to statement y, which is the
immediate statement outside the while loop block.

Flow Diagram:

Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=1;
clrscr();
while(a<=5)
{
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 47
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf(“%d\t”,a);
a++;
}
}
When the above code is compiled and executed, it produces the following result

1 2 3 4 5

2. do-while loop
The do-while loop is similar to the while loop. The only difference is that in a do-
while loop, the test condition is tested at the end of the loop. Now as the test
condition is tested at the end, this clearly means that the body of the loop gets
executed at least one time even though if the condition is false.
Syntax:
statement x;
do
{
statement block;
}while(condition);
statement y;
Disadvantage: The major disadvantage of using a do-while loop is that it always
executes at least once, even if the user enters some invalid data.

Flow Diagram

Example
#include<stdio.h>

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 48
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
#include<conio.h>
void main()
{
int i=1;
clrscr( );
do
{
printf(“%d\t”,i);
i++;
}while(i<=5);
}
When the above code is compiled and executed, it produces the following result

1 2 3 4 5

3. for loop
A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
Syntax:
for( initialization; condition; increment/decrement/update)
{
statement block;
}
statement y;

Here is the flow of control in a 'for' loop −

 The initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to put a
statement here, as long as a semicolon appears.

 Next, the condition is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and the flow of control jumps to
the next statement just after the 'for' loop.
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 49
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 After the body of the 'for' loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control
variables. This statement can be left blank, as long as a semicolon appears after
the condition.

 The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the 'for' loop terminates.

Flow Diagram:

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for( i=1; i<=5; i++)
{

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 50
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf(“%d\t”,i);
}
}
When the above code is compiled and executed, it produces the following result

1 2 3 4 5

Nested loops
C programming allows us to use one loop inside another loop. The following section
shows few examples to illustrate the concept.

Syntax for nested for loop

for ( initialization; condition; increment/decrement/update)

for ( initialization; condition; increment/decrement/update)

statement(s);

statement(s);

Syntax for nested while loop

while(condition)

while(condition)

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 51
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
statement(s);

statement(s);

Syntax for nested do-while loop


do
{
statement(s);
do
{
statement(s);
}while(condition);
}while(condition);
Note: you can put any type of loop inside any other type of loop. For example, a 'for'
loop can be inside a 'while' loop or vice versa.

2.3 JUMP STATEMENTS:


Jump statements cause an unconditional jump to another statement elsewhere in the code.
They are used primarily to interrupt switch statements and loops. The jump statements
are:
1. break statement
2. continue statement

1. break statement :
The break statement in C programming has the following two usages −

 When a break statement is encountered inside a loop, the loop is immediately


terminated and the program control resumes at the next statement following the
loop.
 It can be used to terminate a case in the switch statement.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 52
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
If you are using nested loops, the break statement will stop the execution of the innermost
loop and start executing the next line of code after the block.

Syntax
break;
Flow Diagram

Example
#include<stdio.h>
void main()
{
int i=0;
while(i<=10)
{
if(i= = 5)
{
break;
}
printf(“\t%d”,i);
i=i+1;
}
}
When the above code is compiled and executed, it produces the following result

0 1 2 3 4

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 53
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
2. continue statement :
The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place,
skipping any code in between.

Syntax :
continue;
Flow Diagram

Example
#include<stdio.h>
void main()
{
int i=0;
while(i<10)
{
i=i+1;
if(i= = 5)
continue;
printf(“\t%d”,i);
}
}
When the above code is compiled and executed, it produces the following result

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 54
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1 2 3 4 6 7 8 9 10

Problem Solving:

1. Write a C program to generate electricity bill.

#include <stdio.h>

main()

float a=0,u;

system("cls");

printf("Enter the number of units");

scanf("%f", &u);

if(u<=50)

a= u* 0.75;

else if(u >50 && u <=100)

a=0.75 * 50 + 0.85*(u-50);

else if(u >100 && u <200)

a=(0.75*50) + (0.85*50 )+ (1.5 *(u-100));


Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 55
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
}

else if(u >200 && u <300)

a=(0.75*50) + (0.85*50 )+ (1.5 *100) + (2.20 *(u-200));

else

a=(0.75*50) + (0.85*50 )+ (1.5 *100) + (2.20 * 100) +(3.0*(u-300));

a=a+(0.2*a);

printf("The total electricity bill is %f", a);

getch();

Output:

Enter the number of units100

The total electricity bill is 96.000000

2. Write a C program to simulate a calculator using switch case.

#include"stdio.h"

main()

int a,b;
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 56
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
char ch;

clrscr();

printf("\n Enter two values:");

scanf("%d%d",&a,&b);

printf("\n Enter Ur choice:");

printf("\n Enter + for Addition:");

printf("\n Enter - for Subtraction:");

printf("\n Enter * for Multiplication:");

printf("\n Enter / for Division:");

printf("\n Enter %% for Mod:\n");

ch=getche();

switch(ch)

case '+':printf("\n Addition is:%d",a+b);

break;

case '-': printf("\n Subtraction is:%d",a-b);

break;

case '*':printf("\n Multiplication is:%d",a*b);

break;

case '/':printf("\n Division is:%f",(float)a/b);

break;
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 57
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
case '%':printf("\n Mod value is:%d",a%b);

break;

default: printf("\n Enter Correct choice, The choice must be +,-,*,/ and %");

getch();

Output:

Enter two values: 6 7

Enter Ur choice:

Enter + for Addition:

Enter - for Subtraction:

Enter * for Multiplication:

Enter / for Division:

Enter % for Mod:

Division is: 0.857143

3. Implement C code to find out the roots of the quadratic equation.

#include"stdio.h"

#include"math.h"

main()

{
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 58
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
float a,b,c,d,r1,r2;

clrscr();

printf("\n Enter three values");

scanf("%f%f%f",&a,&b,&c);

d=b*b-4*a*c;

if(d==0)

r1=r2=-b/(2*a);

printf("\n Roots are equal");

printf("\n r1=%f and r2=%f",r1,r2);

else if(d<0)

printf("\n Roots are imaginary:");

r1=-b/(2*a);

r2=sqrt(-d)/(2*a);

printf("\n r1=%f+i%f",r1,r2);

printf("\n r2=%f-i%f",r1,r2);

else

{
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 59
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf("\n Roots are real:");

r1=(-b+sqrt(d))/(2*a);

r2=(-b-sqrt(d))/(2*a);

printf("\n r1=%f",r1);

printf("\n r2=%f",r2);

getch();

Output:

Enter three values 1 2 3

Roots are imaginary:

r1=-1.000000+i1.414214

r2=-1.000000-i1.414214

4. Develop C program to Check a number is palindrome or not.

#include<stdio.h>

void main()

int n,s=0,k;

clrscr();

printf("Enter an integer:");

scanf("%d",&n);
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 60
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
k=n;

while(n>0)

s=s*10+n%10;

n/=10;

if(k==s)

printf("\n%d is Palindrome",k);

else

printf("\n%d is Not a Palindrome",k);

getch();

Output:

Enter an integer: 121

121 is Palindrome

5. Write a C program to find out given number is prime or not.

#include<stdio.h>

void main()

int n,c=0,i;

clrscr();
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 61
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf("\nEnter an Integer:");

scanf("%d",&n);

for(i=1;i<=n;i++)

if(n%i==0)

c++;

if(c==2) //use c!=2 for Non-Prime number checking

printf("%d is Prime Number",n);

else

printf("%d is Not a Prime Number",n);

getch();

Output:

Enter an Integer: 7

7 is Prime Number

Assignment Cum Tutorial Questions

2.1. Simple Sequential Programs & Conditional Statements:

Objective Type Questions:

1. What will be the output of the following code?

int x = 10;
if (x < 15)
printf("Less");
else
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 62
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf("More");

a) Less
b) More
c) Error
d) None

Answer: a) Less

2. Which of the following is the correct syntax of the if statement?

a) if condition { }
b) if (condition) { }
c) if [condition] { }
d) if condition:

Answer: b) if (condition) { }

3. The switch statement works with:

a) int
b) char
c) enum
d) All of the above

Answer: d) All of the above


Descriptive Questions:

[Link] Short Answer Questions: BL

1. What is a conditional statement in C? L1

2. Differentiate between if and if-else. L2


What is the purpose of a switch statement?
3. L2

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 63
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

4. Can we use multiple else if blocks in a program? Explain briefly. L3

5. When should you prefer a switch over if-else? L4

[Link] Long Answer Questions : BL

1. Explain the working of if, if-else, and else-if ladder with examples. L2

2. Write a program to find the greatest of three numbers using else-if ladder. L3
Discuss the switch statement in C. Mention its syntax, working, and
3. limitations with an example. L4

4. Compare and contrast if-else and switch statements. L3

5. Explain the concept of nested if statements with a practical example. L2

2.2. Loops: for, while, do-while:

Objective Type Questions:

1. What is the output of the following code?

int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 3);

a) 1 2 3
b) 0 1 2
c) 2 3 4
d) Infinite loop

Answer: a) 1 2 3

2. Which loop is guaranteed to execute at least once?


Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 64
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
a) for
b) while
c) do-while
d) All of the above

Answer: c) do-while

3. The loop that is best when the number of iterations is known is:

a) for
b) while
c) do-while
d) switch

Answer: a) for

Descriptive Questions:

[Link] Short Answer Questions: BL


Classify the iteration statements in C
1. L2
Write the syntax of a for loop.
3. L1
Write the syntax of a do-while loop.
4. L2
How many times will the loop run? int i = 1;
while(i <= 3) {
5. i++; L3

[Link] Long Answer Questions: BL


Explain different types of iteration statements in C with proper syntax?
1. L2
Compare while and do-while loops with syntax and examples.
2. L3
Write a program to check whether a number is prime using a while loop.
3. L3

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 65
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
2.3. Unconditional Branching: break and continue:

Objective Type Questions:

1. What will be the output?

int i;
for(i=0; i<5; i++) {
if(i==3)
break;
printf("%d ", i);
}

a) 0 1 2 3 4
b) 0 1 2
c) 0 1 2 3
d) 1 2 3

Answer: b) 0 1 2

2. What does the continue statement do in a loop?

a) Stops the loop completely


b) Skips the next iteration
c) Skips the remaining part of the loop body and starts next iteration
d) None of the above

Answer: c) Skips the remaining part of the loop body and starts next iteration

3. Which of the following is true about break?

a) It skips the rest of the loop body


b) It ends the loop immediately
c) It returns control to the calling function
d) None of the above

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 66
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Answer: b) It ends the loop immediately

Descriptive Questions:

[Link] Short Answer Questions: BL


What is the use of the break statement?
1. L2
How does continue work inside a loop?
2. L2
Differentiate between break and continue.
3. L3

[Link] Long Answer Questions: BL


Explain the purpose of break statement with proper syntax and example.
1. L2
Explain the purpose of break statement with proper syntax and example.
2. L2

UNIT-III
ARRAYS AND STRINGS
Syllabus

5.1 Arrays
3.1.1 Introduction
3.1.2 Declaration and Initialization of 1D array with Example Program
3.1.3 Declaration and Initialization of 2D arrays with example program

5.2 Memory Model


3.2.1 Storage of Memory elements
3.2.2 Base address
3.2.3 Accessing array elements

5.3 Example Programs


3.3.1 Find Min and Max of 1-D array
3.3.2 Linear search on 1D array
3.3.3 Addition of two matrices

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 67
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
5.4 Strings
3.4.1 Introduction
3.4.2 Declaration and Initialization of strings
3.4.3 Reading and displaying strings with terminal
3.4.4 String handling functions
3.4.5 2D character arrays with strings
3.4.6 Program to concatenate two strings without built in functions
3.1 Arrays
In C programming, an array is a collection of elements of the same data type, stored in
contiguous memory locations, and accessed using a single name with an index.
Ex: int mark1 = 85, mark2 = 90, mark3 = 78; // Tedious and limited without array
int marks[3]= {85,92,78}

3.1.1 Introduction
An array is a fixed-size sequenced collection of elements of the same data type. It is
simply a grouping of like-type [Link] array is a sequenced collection of related data
items that shares a common name. An array can be used to represent a list of numbers or
a list of name.
For e.g.: int salary [50];
 Arrays can be used to:
1. To store list of employees in an organization.
2. Store Table of daily rainfall data.
3. To store list of products and their cost.
4. To store list of customers and their telephone numbers.
 Types of arrays:
1. One-dimensional Array.
2. Two-dimensional Array.
3. Multi-dimensional Array.

3.1.2 Declaration and Initialization of 1D Arrays


 Declaration of 1D Array
A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted variable or a one-dimensional [Link] must

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 68
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
be declared before they are used so that the compiler can allocate space for them in
memory. The general form of array declaration is:
datatype variable name [size];
The datatype specifies the type of element that will be contained in the array such as int,
floatand char.
The size indicates the maximum number of elements that can be stored inside the array.
Ex: float height [50];
Above example declaresan array with name height containing 50 real elements. Any
subscripts 0 to 49 are valid.
The C language treats character strings simply as array of characters. The size in a
character that the string can hold.
Char name [6];
Above declaration is a character array with name as “name”which can hold a maximum
of 5 characters.
Consider a string “SRGEC”
Each character of the string is treated as an element of the array name and is stored in
the memory as follows:
S
R
G
E
C
‘\0’
 Initialization of 1D Array
After an array is declared, its elements must be initialized. Otherwise, they will
contain“garbage”. An array can be initialized at either of the following stages:
 At Compile time.
 At run time.
 Compile time initialization
We can initialize the elements of arrays in the same way as the ordinary variables when
theyare declared. The general form of initialization of array is:
datatype array-name[size]={list of values};

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 69
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Ex: int number [3] = {0, 0, 0};
Above example will declare the variable “number” as an array of size 3 and will assign
zero to each [Link] number of values in the list is less than the number of
elements, then only that many elements willbe initialized. The remaining elements will be
set to zero [Link] arrays may beinitialized in a similar manner.
Compile time initialization may be partial. The number of initializers may be less than
thedeclared size. In such cases, the remaining elements are initialized to zero, if the array
type is numeric,NULL if the type is char.
 Run time initialization
An array can be explicitly initialized at run time. This approach is usually applied for
initializinglarge arrays.
Ex: int n [3];
scanf (“%d %d %d”,&n[0],&n[1],&n[2]);
 Accessing a 1D array
The array elements of 1D array can be accessed by using the following syntax
printf (“%d %d %d”,n[0],n[1],n[2]);

 Example Program for One-Dimensional Array


#include<stdio.h>
main ()
{
int a [10],i,n;
printf (“Enter n value\n”);
scanf (“%d”,&n);
printf (“Enter Array A values\n”);
for (i=0;i<n;i++)
scanf (“%d”,&a[i]);
printf (“Output\n”);
for (i=0;i<n;i++)
printf (“%d\n”,a[i]);
}

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 70
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
3.1.3 Declaration and Initialization of 2D Arrays
 Declaration of 2D Array
C allows us to define table of values using two-dimensional arrays. Two-
dimensionalarrays aredeclared as follows
datatype array_name[row_size][column_size];

 Initializing 2D Arrays at compile time


Like one-dimensional arrays, two-dimensional array may be initialized by following their
declaration with a list of initial values enclosed in braces.
Ex: int table [2][3] = {0,0,0,1,1,1};
The initialization is done row by row. The equivalent statement is:
int table[2][3]={{0,0,0},{1,1,1}};
We can also initialize a two-dimensional array as
int table[2][3]={{0,0,0},
{1,1,1}
};
Note: we need not specify the size of the first dimension.
Ex: int table [][3] ={0,0,0,1,1,1};
 Initializing 2D Arrays at run time
The 2-dimensional arrays can initialized using two looping statements called Outer loop-
forindicating rows, Inner loop- for indicating columns.
Ex: for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf (“%d”,&x[i][j]); /*reading values into 2x2 marix*/
}
}
will initialize the elements of 2x2 matrix at run-time.
 Accessing a 2D array
The array elements of 2D array can be accessed by using the following syntax

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 71
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf (“%d ”,n[i][j]);
}
}
Example Program for Two-Dimensional Array
#include<stdio.h>
main()
{
int a[10][10],i,j,m,n;
printf(“Enter row and column value\n”);
scanf(“%d %d”,&n,&m);
printf(“Enter Array A values\n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
scanf(“%d”,&a[i][j]);
}
printf(“Output\n”);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
printf(“%d\t”,a[i][j]);
printf(“\n”);
}
}

3.2 Memory Models


3.2.1 Storage of Memory Elements
All arrays are the contiguous block of memory locations. By default, the lowest position

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 72
R -23
23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
of the array stores the first element, and the highest position stored the last data. In C, the
array is declared by specifying the element's type and the total length of array required to
store the data.
3.2.2 Base Address
Base address of an array is the address value of the starting point of the array. It is usually
the address of the first
st element of the array.
In a single dimensional array, the address of an element of an array says A[i] is calculated
using the following formula
Address of A[i]=B+W*(i–LB)
Where,
B is the base address of the array,
W is the size of each element in bytes,
i is the subscript of an element whose address is to be found and
LB is the Lower limit / Lower Bound of subscript (if not specified assume 0).
Similarly, in the case of a two
two-dimensional array, the address of an element
lement of any array
say A[i][j] may be calculated in 2 methods depending upon what type of ordering the
array follows.
In case of Row Major System, the address of the location is calculated using equation
Row Major: Address of A[i][j] =B+W*[N*(i−Lr) +(j−Lc)]

While in case of Column Major System, the address of the location is calculated using the
equation.
Column Major: Address of A[i][j] =B+W*[(i–Lr) +M*(j−Lc)]

where,
B = Base address
i = Row subscript of an element whose address is to be found
j = Column subscript of an element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of the matrix, if not given assume 0 (zero)

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE 5-26 Page 73


AS&A A. Y: 2025
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Lc = Lower limit of column/start column index of the matrix, if not given assume 0
(zero)
M = Number of rows of the given matrix
N = Number of columns of the given matrix.
3.2.3 Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of
the element within square brackets after the name of the array.
For example:double salary = balance [9];
The above statement will take 10th element from the array “balance” and assign that
value to salaryvariable.
3.3 Example Programs
3.3.1 Implement C program to Find the min and max of a 1-D integer array
#include <stdio.h>
int main()
{
int arr[100];
int i,max,min,size;
printf (“Enter size of the array: “);
scanf(“%d”,&size);
printf(“Enter elements in the array: “);
for (i=0;i<size;i++)
{
scanf(“%d”,&arr[i]);
}
max =arr[0];
min =arr[0];
for (i=1;i<size;i++)
{
if(arr[i] >max)
{
max=arr[i];
}

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 74
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
if(arr[i] <min)
{
min=arr[i];
}
}
printf(“Maximum element =%d\n”,max);
printf(“Minimum element =%d\n”,min);
return 0;
}
3.3.2 Write a C program to Perform linear search on1D array
#include <stdio.h>
intmain()
{
intarray[100],search,i, number;
printf("Enter the number of elements in array\n");
scanf("%d",&number);
printf("Enter %d numbers\n", number);
for(i=0;i< number ;i++)
scanf("%d",&array[i]);
printf("Enter the number to search\n");
scanf("%d",&search);
for(i=0;i< number ;i++)
{
if( array[i]== search )/* if required element found */
{
printf("%d is present at location %d.\n",search,i);
break;
}
}
if(i==number )
printf("%d is not present in array.\n", search);
return0;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 75
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
}
3.3.3 Develop C program to find out Addition of two matrices
#include<stdio.h>
main()
{
int a[10][10],b[10][10],c[10][10],i,j,n,m;
clrscr();
printf("Enter [Link] rows and columns\n");
scanf("%d %d",&n,&m);
printf("Enter values in matrix A\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter values in matrix B\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&b[i][j]);
}
}
for(i=0;i<n;i++)
{
c[i][j]=0;
for(j=0;j<m;j++)
{
c[i][j]=a[i][j]+b[i][j];
}

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 76
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
}
printf("Sum of Matrices\n");
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
printf("%4d",c[i][j]);
}
printf("\n");
}
getch();
}
3.4 Strings
3.4.1 Introduction
A string is a sequence of characters that is treated as a single data item. Any group
ofcharacters defined between double quotation marks is a string constant.
Ex: “Well Done”
Character strings are used to build meaningful and readable programs. The common
operationsperformed on character strings include:
 Reading and Writing strings.
 Combining strings together.
 Copying one string to another.
 Comparing strings for equality.
 Extracting a portion of a string.
3.4.2 Declaration and Initialization of string
 Declaration of string
C does not support strings as a datatype. It allows us to represent strings as character
[Link] general form of declaration of string variable is:
char string_name[size];
The size determines the number of characters in the string name.
Ex: char name[10];
When the compiler assigns a character string to a character array, it automatically

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 77
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
supplies a null character („\0‟) at the end of the string. The size should be equal to the
maximum number of characters in the string plus one.
 Initialization of String
Character arrays may be initialized when they are declared. C permits a character array to
be initialized in either of following two forms:
char name [15] =”ANDHRA PRADESH”;
char name[15]={‘A’,’N’,’D’,’H’,’R’,’A’,’ ‘,’P’,’R’,’A’,’D’,’E’,’S’,’H’,’\0’};
Note: When we initialize a character array, we must supply explicitly the NULL
terminator.
C permits us to initialize a character array without specifying the number of elements.
Ex: char name [ ] = {‘A’,’N’,’D’,’H’,’R’,’A’,’\0’};
The statement defines the array name as a seven element array.
We can also declare the size much larger than the string size in the initialize.
Ex: char name [10] =”ANDHRA”;
Computer creates a character array of size 10, places the value “ANDHRA” in it.
Terminated with the null character, and initializes all other elements to NULL.
A N D H R A \0 \0 \0 \0

 The following declaration is illegal.

Ex: char name[6]=”ANDHRA”;


Size should be greater than number of characters
 We cannot separate the initialization from declaration.

Ex: char name[10];


name=”ANDHRA”;
 An array name cannot be used as the left operand of an assignment operator.

Ex: char name[10]=”ANDHRA”;


char name1[10];
name1=name;/*Error*/

3.4.3 Reading and Displaying of strings from terminal


 Reading of strings from terminal
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 78
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
The input function scanfcan be used with %s format specification to read in a string of
characters.
Ex: char name[10];
scanf(“%s”, name);
The disadvantage with the scanffunction is that it terminates its input on the first white
space it finds. A white space includes blanks, tabs, carriage returns, form feeds and new
lines.
Ex: Pavani sri
The only string “Pavani” will be read into the array name
 Displaying of string to terminal
The printffunction with %s format is used to print strings to the screen. The format %s is
canbe used to display an array of characters that is terminated by the null character.
Ex: printf(“%s”, name);
Above statement displays the entire contents of the array” name”
 Program to display and read string with terminal
#include<stdio.h>
main()
{
char word1[40],word2[40],word3[40],word4[40];
clrscr();
printf("ENTER THE TEXT.\n");
scanf("%s %s",word1,word2);
scanf("%s",word3);
scanf("%s",word4);
printf("\n");
printf("Word1= %s \n Word2= %s\n",word1,word2 );
printf("Word3= %s \n Word4= %s\n",word3,word4 );
getch();
}
3.4.4 String Handling Functions
The C-library supports a large number of string-handling functions that can be used to
carry out many of the string manipulations. Following are the most commonly used string

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 79
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
handling functions.
Function Action
strcat() concatenates two strings.
strcmp() compares two strings.
strcpy() copies one string over another.
strlen() finds the length of a string.
strupr() string characters in uppercase.
strlwr() string characters in lowercase.
strrev() reverse a string.
 strcat() function
The strcat function joins two strings together. It takes the following form:
strcat( string1, string2);
Note: string1 and string2 are character arrays.
When the function strcat is executed, string2 is appended to string1.
Ex: Str1=
V E R Y \0

Str2=
G O O D \0

Execution of the statement strcat(str1,str2); will result in


Str1=
V E R Y G O O D \0

Str2=
G O O D \0

strcat() function may also append a string constant to a string variable.


Ex:strcat(str1,”GOOD”); is valid statement.

C permits nesting of strcat() functions.


Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 80
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Ex:strcat(strcat(str1, str2), str3);
 strcmp () function
Compares the two strings identified by the arguments and has a value“ 0”, if they are
equal. If they are not equal, it has the numeric difference between the first non-matching
characters in the strings. It takes the form:
strcmp(string1,string2);
string1, string2 may be string variables or string constants. Examples are:
strcmp(name1,name2);
strcmp(name1,”john”);
strcmp(“rom”,”ram”);
 strcpy() function
Copies one string over another. It takes the following form:
strcpy (string1,string2);
Assigns the contents of string2 to string1. The string2 may be a character array variable
or a string constant.
Ex: strcpy(city, “DELHI”);
The above line of code will assign the string “DELHI” to the string variable “city”.
 strlen() function
This function counts and returns the number of characters in a string. It takes the form:
n=strlen(string);
Where, n is an integer variable, which receives the value of the length of the string
 strupr() function
Thestrupr() function returns string characters in uppercase.
strupr(string);
 strlwr() function
The strlwr() function returns string characters in lowercase
strlwr(string);
 strrev() function
The strrev() function returns reverse of the given string.
strrev(string);
3.4.5 2D Character arrays with strings
2D character arrays are very similar to 2D integer arrays. We store the elements and

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 81
R -23
23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
perform other operations in a similar manner. A 2D character array is more like a String
array.. It allows us to store multiple strings under the same name.
 Declaration
A 2D character array is declared in the following manner
char name[5][10];
The order of the subscripts is important during declaration. The first
subscript [5] represents the number of Strings that we want our array to contain and the
second subscript [10] represents the length of each String. This is static memory
allocation.
 Initialization
Initialization of the 2D character array occurs in this manner
char name[5][10] ={“tree”,”bowl”,”hat”,”mice”,”toon”};
In memory allocation it will be represented as below:

3.4.6 Write a C program to concatenate two strings without built


built-in functions
#include <stdio.h>
#include <string.h>
int main()
{
char Str1[100], Str2[100];
int i, j;
printf("
printf("\n Please Enter the First String : ");
gets(Str1);
printf("
printf("\n Please Enter the Second : ");
gets(Str2);
for (i = 0; Str1[i]!='\0'; i++);

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE 5-26 Page 82


AS&A A. Y: 2025
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
for (j = 0; Str2[j]!='\0'; j++, i++)
{
Str1[i] = Str2[j];
}
Str1[i] = '\0';
printf("\n After the Concatenate = %s", Str1);
return 0;
}
Assignment Cum Tutorial Questions
Short Answer Questions
What is the base address of an array, and why is it important?
1 L1
What is list (1-D array)? How its elements can be accessed? L1
2
Define 2-D array with proper syntax. L1
3
How is a specific element accessed in a 2D array L1
4
Define String. How to insert and access a string at a specific position. L1
5
Write the syntax for strlwr() and strupr(). L1
6
Define a string in the context of programming L1
7
Write the syntax for strcpy().Give an example L1
8
Can we copy an array using the assignment operator? Justify your answer. L1
9
Identify various string handling functions L1
10

3.1 Arrays
3.1.1 Introduction to arrays
Objective Questions
1. Which of this best describes an array? [L1]
a) A data structure that shows a hierarchical behavior
b) Container of objects of similar types

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 83
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
c) Arrays are immutable once initialized
d) Array is not a data structure
Descriptive Questions
[Link] Questions BL

1 Explain in detail about the need of arrays with advantages and L2


mention the types of arrays
3.1.2 Declaration and Initialization of 1D array

Objective Questions

1. What is the correct way to initialize an array? [L1]

a) int a[5] = [1,2,3,4,5];

b) int a(5) = [1,2,3,4,5];

c) int a[5] = {1,2,3,4,5};

d) int a[5] = (1,2,3,4,5);

2. An array of integers is declared with name numbers to store 5 different values.


Which of the following is the correct declaration [L2]

a) float numbers [5];

b) int numbers [5];

c) int numbers {5};

d) int numbers(5);

Descriptive Questions
[Link] Questions BL

1 With the help of an example explain the process of declaration and L2


initialization of an 1D array
2 Write a c program to declare an 1D array, initialize it at run time L3
and display the values

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 84
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

3.1.3 Declaration and Initialization of 2D array

Objective Questions

1. A 2D array of integers is declared with name numbers to store in 3 rows and 4


columns. Which of the following is the correct declaration [L2]

a) int numbers [3][4];

b) int numbers [4][3];

c) numbers int [3][4];

d) numbers int [4][3];

2. Consider the following 2D array. What is the value being stored at a[1][1] [L2]

int a[2][2]={{5,10},{15,20}}

a) 5

b) 10

c) 15

d) 20

Descriptive Questions
[Link] Questions BL

1 With the help of an example explain the process of declaration and L2


initialization of an 2D array
2 Write a c program to declare an 2D array, initialize it at run time L3
and display the values

3.2 Memory Models


3.2.1 Storage of Memory Elements
Objective Questions

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 85
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1. When an array for 5 elements to store integers is declared and the size of an
integer is 2 bytes in the system then if the starting address of array is 102, what
will be the address of second element? [L2]
a) 102
b) 100
c) 104
d) 108
3.2.2 Base Address
Objective Questions
1. Which of the following is the correct formula to find address of i th element of an
1D array? [L2]
a) A[i]=B+W*(i–LB)
b) A[i]=B+W*(j–LB)
c) A[i]=B+W*(i+LB)
d) A[i]=B+W*(i–UB)
2. Which of the following is the correct formula to find address of i th element of an
2D array using row major format? [L2]
a) A[i][j] =B+W*[N*(i−Lr) +(j−Lc)]
b) A[i][j] =B+W*[N*(i+Lr) +(j−Lc)]
c) A[i][j] =B+W*[N*(i−Lr) +(j+Lc)]
d) A[i][j] =B+W*[N*(i+Lr) +(j+Lc)]
3. Which of the following is the correct formula to find address of i th element of an
2D array using column major format? [L2]
a) A[i][j] =B+W*[(i–Lr) +M*(j−Lc)]
b) A[i][j] =B+W*[(i+Lr) +M*(j−Lc)]
c) A[i][j] =B+W*[(i–Lr) +M*(j+Lc)]
d) A[i][j] =B+W*[(i+Lr) +M*(j+Lc)]
Descriptive Questions
[Link] Questions BL

1 Explain the memory model of an array and how to calculate the L2


base address?

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 86
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
3.2.3 Accessing Array Elements
Objective Questions
1. Identify the correct statement which represents accessing 5th element from array
named “a” and assigning it to variable “value” [L2]
a) value=a [5];
b) value =a;
c) value =5[a];
d) a[5]=value;
3.3 Example Programs
Descriptive Questions
[Link] Questions BL

1 Write a C Program to find min and max element of an 1D array L3

2 Write a C Program to perform linear search on an 1D array L3

3 Write a C Program to addition of two matrices L3

3.4 Strings
3.4.1 Introduction
Objective Questions
1. A string is generally represented as [L1]

a) A linked list
b) A 1D array of characters
c) A 2D array of characters
d) A union
3.4.2 Declaration and Initialization of strings
Objective Questions
1. Which of the following is the correct way to declare and initialize a string in c?
[L1]

a) char mystring[]=”Hello”;
b) string mystring[]=”hello”
c) string mystring=”hello”

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 87
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
d) char mystring[6] =(‘h’,’e’,’l’,’l’,’o’);
Descriptive Questions
[Link] Questions BL

1 Explain how to declare and initialize a string L2

3.4.3 Reading and Displaying Strings from terminal


Objective Questions
1. Which of the following is the correct way to display a string named name? [L1]

a) printf(“%s”,str);
b) printf(“%f”,&str);
c) printf(“%c”,str);
d) printf(“%d”,str)
Descriptive Questions
3.4.4 String Handling Functions
Objective Questions
1. What is the header file to be used to include string handling functions in c? [L1]

a) stdio.h
b) conio.h
c) math.h
d) string.h
2. Which function is used to compare one string with another? [L1]

a) strcmp()
b) stringcmp()
c) strcompare()
d) strmatch()
3. When strlen() function is called then it returns [L1]

a) The size of the string in kilobytes


b) The number of characters in the string without null terminator and space
c) The number of characters in the string with null terminator and space

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 88
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
d) The number of characters in the string without null terminator and with space
Descriptive Questions
[Link] Questions BL

1 List different types of string handling functions in C and explain L1


them briefly.
2 With the help of example explain how strcat(),strcpy(),strcmp() L2
works
3 With the help of example explain how L2
strlen(),strupr(),strlwr(),strrev() works

3.4.5 2D Character arrays with strings


Objective Questions
1. Which of the following correctly declares a 2D character array to store 5 strings,
each with a maximum length of 9 characters (including null terminator)? [L2]

a) char strings [5][9]


b) char strings [5][10]
c) char strings [9][5]
d) char strings [10][5]
Descriptive Questions

3.4.6 Program to concatenate two strings without built in functions


Descriptive Questions
[Link] Questions BL

1 Write a C program to concatenate two strings without using built L3


in functions

Unit-IV
Pointers & User Defined Data types
Syllabus Content:
4.1 Pointers

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 89
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
4.1.1 Definition, Declaration, initialization
4.1.2 de-referencing and address operators
4.1.3 Pointer Arithmetic
4.1.4 Array manipulation using pointers.
4.1.5 Pointers and Strings
4.2 User Defined Data types: Structures and Unions
4.2.1 Structures: definition, Syntax, initialization and accessing
4.2.2 Nested structures
4.2.3 Array of structures.
4.3 Unions: definition, syntax initialization and accessing
4.4 Differences between structure and union
4.5 Write C program to find out sum of given array elements using Pointers.
4.6 Develop C program to illustrate nested structure concept
4.7 Implement C code to read ‘n’ students information using array of structures concept.

4.8 Learning Material


[Link]
Pointer is one of the most powerful features of C-language, which have number of
advantages.
 Pointers enable us to access a variable that is defined outside the function.
 This is because the memory addresses are global to all functions, whereas local
variable names are meaningful only within the function in which they are declared.
 Pointers reduce the length and complexity of a program. i.e.., pointers are used for
saving memory.
 Pointers provide a way to return more than one value from a function.
 Pointers can be used to pass arrays and strings more conveniently from one function
to another.
 Pointers increase the program execution speed.
 Pointers provide dynamic memory allocations.
4.1.1. Declaration of pointers:
 Pointer is a variable that holds the address of another variable.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 90
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 When we declare a variable, an appropriate memory location is allocated to the
variable by the compiler to hold the value of a variable.
 This memory location will have its own address.
 Consider the statement, int i=10;
This statement tells the C compiler to perform the following actions.
1) Reserves a space in memory to hold the integer value.
2) Associate the name ‘i’ with this memory location.
i  location name
10  value at location
65514 location address
Now we may access the value ’10’ by using either the name ‘i’ or the address
[Link] memory location addresses are simply numbers, they can be assigned to
some variables which can be forced in memory, like another variable. Such variables
that hold memory address are called pointers.
Declaration of pointer:
Syntax: datatype *variable name;
 Like another variables, pointers must be declared before they can be used.
 Datatype is the type of the pointer. It specifies the type of the object that the pointer
can point to.
 Ex: int *x;
 The above statement states that ‘x’ is a pointer variable and is going to contain the
address of a variable which is of integer type.
 We can read as “x is a pointer to int” (or) “x points to an object of type integer”.
 Similarly, float *a;
 It declares ‘a’ as a pointer to a floating-point variable.
Initialization of Pointers:
 Pointers should be initialized either when they are declared or in an assignment.
 A value cannot be assigned to a pointer variable directly as an ordinary variable.
 Instead it must be assigned a value of a variable which is already declared.
Syntax: datatype variable name1;
datatype *variable name = &variable name1; /*Initialization at declaration
time*/

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 91
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
(or)
datatype *variable name;
variable name = &variable name1;
Ex: int a;
int *b=&a;
(or)
int a;
int *b;
b=&a;
 In the above example, ‘a’ is an ordinary integer variable and ‘b’ is a pointer that
points to an integer variable ‘a’.
 The address of the variable ‘a’ is assigned to pointer ‘b’ by using & (address
operator) that mean the variable ‘b’ holds the address of variable ‘a’.
 A pointer may be initialized to ‘0’ (zero), NULL or an address.
 A pointer with the value NULL points to nothing.
 Initializing a pointer ‘0’ (zero) is equivalent to initializing a pointer to NULL, but
NULL is preferred.

 C contains two special operators: ‘&’ and ‘*’.


 The ‘&’ operator has been used to denote the address of the variable in the scanf
function.
 This operator is known as address operator (or) Unary operator that returns the
address of the variable it precedes and it is not restricted to the scanf function.
 It may precede only a variable name (or) array element, never a constant (or)
expression.
For example, int i=10;
int *iptr;
iptr=&i; ----- (1)
(1) Statement assigns the address of ‘i’ to pointer variable ‘iptr’. Variable ‘iptr’
is said to “points to i”.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 92
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 Before a pointer is initialized, it should not be used.
 The ‘*’operator, commonly referred to as the indirection operator (or) dereferencing
operator, returns the value stored at the address that it precedes.
o For example,
 printf(“%d”, *iptr);
 The above statement prints the value of the variable ‘i’, namely 10. Using ‘*’ in this
manner is called dereferencing a pointer.
 The ‘*’ operator is also called “value at address” operator.
 Therefore ‘*iptr’ and ‘i’ both represents the same data item [i.e.., the contents of the
same memory cell].
Accessing a variable through its Pointer:
Once a pointer has been assigned the address of a variable, we can access the
variable using the pointer by placing an indirection operator before the pointer.
Consider the following statements,
int a, *aptr, b;
aptr=&a;
a=5;
b=*aptr;
 The first line declares ‘a’ and ‘b’ as integer variables and ‘p’ as a pointer variable
pointing to an integer.
 The second line assigns the address of ‘a’ to the pointer variable ‘aptr’.
 The third line assigns the value ‘5’ to ‘a’.
 The fourth line contains the indirection operators.
 When the operator ‘*’ is placed before a pointer variable in an expression (on the
right hand side of the equal sign),the pointer returns the value of which the pointer
value is address. In this case, *aptr returns the value of the variable ‘a’. Because aptr
is the address of quantity.
 The ‘*’ can be remembered as ‘value at address’.
 Thus the value of ‘n’ would be ‘5’.
Example:
void main( )
{

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 93
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
int x, y;
int *ptr;
x = 10;
ptr = &x;
y=*ptr;
printf(“value of x is %d”,x);
printf(“%d is stored at address %u \n”,x,&x);
printf(“%d is stored at address %u \n”,*&x,&x);
printf(“%d is stored at address %u \n”, *ptr, ptr);
printf(“%d is stored at address %u \n”,y,& *ptr);
printf(“%d is stored at address %u \n”,ptr,&ptr);
printf(“%d is stored at address %u \n”,y,&y);
*ptr=25;
printf(“\n now x=%d\n”,x);
}
Output:
Value of x is 10
10 is stored at address 4104
10 is stored at address 4104
10 is stored at address 4104
10 is stored at address 4104
4104 is stored at address 4106
10 is stored at address 4108
Now x=25
4.1.2 De-referencing and address
The Dereference Operator (*)
It is used for two purposes with the pointers
1) to declare a pointer, and
2) get the value of a variable using a pointer.
The Address of Operator (&)
It is an "address of" operator which returns the address of any variable. The
statement &var1 represents the address of var1 variable. Since it can be used

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 94
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
anywhere but with the pointers, it is required to use for initializing the pointer with
the address of another variable.
Example:
#include <stdio.h>
int main(void)
{
//normal variable
int num = 100;
//pointer variable
int *ptr;
//pointer initialization
ptr = &num;
//printing the value
printf("value of num = %d\n", *ptr);
//printing the addresses
printf("Address of num: %x\n", &num);
printf("Address of ptr: %x\n", &ptr);
return 0;
}
Output:
value of num = 100
Address of num: 9505c134
Address of ptr: 9505c138
4.1.3 Operations of Pointers/ Pointer Arithmetic
In general, pointers may be used like other variables. So, pointers can be used in
expressions. For example, assume the declarations.
int p=5;
int q=7;
int *xptr, *yptr, Z1, Z2;
The following statements are valid.
xptr=&p;
yptr=&q;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 95
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Z1=(*xptr) * ( *yptr);
*xptr=*xptr+3;
Z2=xptr-yptr;
*yptr=*yptr-1;
 In addition to the ‘*’ and ‘&’ operators, there are only four other arithmetic operators
that may be applied to pointer variables +, ++, - and --.
 A pointer may be incremented (++) or decremented (--), an integer may be added to a
pointer (+ or +=), an integer may be subtracted from a pointer (- or -=), or one
pointer may be subtracted from another pointer provided that they are pointing to the
same array.
 Pointer arithmetic differs from “normal” arithmetic in the manner that it is performed
relative to the base type (such as int, float, char etc..) of the pointer.
 Each time a pointer is incremented, it will point to the next item, as defined by its
base type, beyond the one currently pointed to.
 For example, assume that an integer pointer called ptr contains the address 2000.
 After the statement,ptr++; Executes, ptr++ will have the value 2002, assuming
integers are two bytes long.
 If the system used four bytes to store an integer, then ptr++ will have the value
2004.
 Similarly, if an integer pointer called ‘y’ contains the address 4104,then the
statement
 y+=2;
 Would produce 4112 (4104+2*4) assuming an integer is stored in 4 bytes of
memory.
 The statement y- =2, would set back to 4104.
 In general, incrementing a pointer using the ++ operator, increments the address it
stores by a value equal to sizeof(type) where type is the data type of the variable
pointed to
 (i.e.., 1 byte for char, 2 bytes for int, 4 bytes for float).
 We may not use pointers in multiplication (or) division, or may not take the modulus
of a pointer and two pointers cannot be added.
 A pointer can be assigned to another pointer if both pointers are of the same type.
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 96
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 Otherwise, a cast operator must be used to convert the pointer on the right of the
assignment to the pointer type on the left of the assignment.
 We can apply the increment and decrement operators to either the points itself (or)
the object to which it points to.
 For example, assume that ‘i’ point to an integer that contains the value’3’.
 The statement (*i)++; (note: parentheses are necessary.) will increment the value
pointed by ‘i’.
Ex: main( )
{
int *i,j;
j=3;
i=&j;
printf(“\n Address of j=%u”,i);
(*i)++;
printf(“\n i=%u j=%d”,i,j);
}
Output:
Address of j=65524
I=65524 j=4
 In addition to arithmetic operations, pointers can be compared using relational
operators.
 However, pointer comparisons only make sense of the pointer relate to each other, if
they both point to the same object.

4.1.4 Array Manipulation Using Pointers


Pointers and one-dimensional arrays:
 In C language the elements of an array can be accessed through index. But ‘C’
also provides a special way of array handling through pointers.
 An array name in ‘C’ is very much like a pointer but there is a difference between
each other.
 The pointer is a variable that can appear on the left side of an assignment operator.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 97
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 The array name is a constant and cannot appear on the left side of an assignment
operator.
 When an array is declared, the compiler allocates a base address and a block of
contiguous memory locations to suit the number of elements.
 The first element of an array has the index.
 The array name without an index has special meaning in ‘C’. It represents the
address of the first element of an array.
 The base address is the location of the first element in the array.
 Compiler also defines the array name as a constant pointer to the first element.
Suppose we declare an array as follows:
int a[5]={1,2,3,4,5}
The first elements of a will be stored as follows:
a[0] a[1] a[2] a[3] a[4]

Base address 100 102 104 106 108

 We can also refer elements of an array as follows:


 *a or *(a+0) refers to the zeroeth element of the array i.e..., 1.
 Similarly, *(a+1) refers to the first element of the array i.e....,2 and so on.
This is illustrated by the following program.
void main( )
{
int i;
int x[5]={1,2,3,4,5};
for(i=0;i<n;i++)
printf(“\n x[%d]=%d *(x+%d)=%d”,i,x, *(x+i));
}
Output:
x[0]=1 *(x+0)=1
x[1]=2 *(x+1)=2
x[2]=3 *(x+2)=3
x[3]=4 *(x+3)=4

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 98
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
x[4]=5 *(x+4)=5

Pointers and two-dimensional arrays:


 A two dimensional array can be thought of as a collection of one-dimensional
arrays, each indicating a row.
 Therefore, we can define a two-dimensional array as a pointer to a group of
contiguous one-dimensional arrays.
 The declaration int a[2][3]; can be thought of as a collection of one
dimensional array of 2 elements, each of which is a one dimensional array 3
elements long.
 Imagine ‘a’ to be a one-dimensional array and a[0] refers to first element and
a[1] refers to second element.
 In two-dimensional array, a[0] gives the address of the zeroeth one-dimensional
array and a[1] gives the address of first one-dimensional array.

int a[2][3]={11,12,13,14,15,16}

 The name of the array points to the starting address of the array.
 The element in row1,column2 can be accessed by writing a[1][2].
 Similarly a[1][2] is interpreted as (a[1]+2) would give the address (1006+2).
 Obviously, (1006+2) would give the address 1010. The value of a[1][2] is
given by * (a[1]+2).
 But, a[1] is same as * (a+1). Therefore, value of a[1][2] is * (* (a+1)+2).
 Thus, a[i] points to the ith row of the array and a[i]+j points to the jth element in
the ith row of an array.
 The subscript ‘j’ actually acts as an offset to the base address of the i th row.
 Thus, the following expressions refer to the same element.
a[i][j]
* (a[i]+j)
* (* (a+i)+j)
4.1.5 Pointers and Strings:
We know that a string is a sequence of characters which we save in an array. And
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 99
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
in C programming language the \0 null character marks the end of a string.
Creating a string
In the following example we are creating a string str using char character array of
size 6.
char str[6] = "Hello";
The above string can be represented in memory as follows.

Each character in the string str takes 1 byte of memory space.


Creating a pointer for the string
The variable name of the string str holds the address of the first element of the
array i.e., it points at the starting memory address.
So, we can create a character pointer ptr and store the address of the
string str variable in it. This way, ptr will point at the string str.
In the following code we are assigning the address of the string str to the
pointer ptr.
char *ptr = str;
We can represent the character pointer variable ptr as follows.

The pointer variable ptr is allocated memory address 8000 and it holds the address
of the string variable str i.e., 1000.
Accessing string via pointer
To access and print the elements of the string we can use a loop and check for
the \0 null character.
In the following example we are using while loop to print the characters of the

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 100
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
string variable str.
#include <stdio.h>
int main(void)
{
// string variable
char str[6] = "Hello";
// pointer variable
char *ptr = str;
// print the string
while(*ptr != '\0') {
printf("%c", *ptr);
// move the ptr pointer to the next memory location
ptr++;
}
return 0;
}
 we can access the array elements using pointers.
int arr[5] = {100, 200, 300, 400, 500};
int *ptr = arr;
Where
ptr is an integer pointer which holds the address of the first element. i.e &arr[0]
ptr + 1 points the address of second variable. i.e &arr[1]
Similarly, ptr + 2 holds the address of the third element of the array. i.e. &arr[2]

Example: C Program to Print each array element address and its value using

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 101
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
pointer
#include<stdio.h>
int main()
{
int arr[5] = {100, 200, 300, 400, 500}, i;
int *ptr = arr;
//Address ptr+i
//Value stored at the address *(ptr+i)
for(i = 0; i < 5; i++)
printf("&arr[%d] = %p\t arr[%d] = %d\n",i,ptr+i,i,*(ptr+i));
return 0;
}
Output:
&arr[0] = 0x7fffee2549d0 arr[0] = 100
&arr[1] = 0x7fffee2549d4 arr[1] = 200
&arr[2] = 0x7fffee2549d8 arr[2] = 300
&arr[3] = 0x7fffee2549dc arr[3] = 400
&arr[4] = 0x7fffee2549e0 arr[4] = 500
 The values stored in an array can be manipulates using pointers.
Example2: Program Modifying array elements using the pointer. Let's change the
3rd (index 2) element as 1000.
#include<stdio.h>
int main()
{
int arr[5] = {100, 200, 300, 400, 500}, i;
int *ptr = arr;
//changing 3rd element(300) as 1000.
*(ptr+2) = 1000;
for(i = 0; i < 5; i++)
printf("arr[%d] = %d\n",i,*(ptr+i));
return 0;
}

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 102
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Output:
arr[0] = 100
arr[1] = 200
arr[2] = 1000
arr[3] = 400
arr[4] = 500
Example3: // C program to calculate the sum of array elements using pointers
#include <stdio.h>
int main() {
int arr[100], size;
int *ptr, sum = 0;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter array elements: ");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
// Set address of first array element to *ptr
ptr = arr;
for (int i = 0; i < size; i++) {
sum = sum + *ptr;
ptr++; // Increment pointer by one to get next element
}
printf("The sum of array elements is: %d", sum);
return 0;
}
Output:
Enter the size of the array: 5
Enter array elements: 1 2 3 4 5
The sum of array elements is: 15
4.2 User Defined datatypes
4.2.1 Structure:

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 103
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
A structure is a collection of different data types that are logically grouped
together and referenced under a single name.
 The main use of structure is to represent the different attributes or characteristics of
an entity.
 It creates a format, which may be used to declare many other variables in that format.
 It is a user defined data type.

Syntax of a Structure Definition:


struct structure_name / tag name
{
datatype var_name, var_name1,.........;
datatype var_name,var_name1,..........;
............
............
};

 The keyword struct tells the compiler that a structure type is being defined.
 structure_name (or) tag_name serves as a name that may be used for a particular
template of the structure.
 The data type need not be the same. Different variable types can be separated by a
semicolon.
 The elements of a structure are also referred to as fields (or) members and are
enclosed within curly braces.
 The closing brace is followed by a semicolon.

For example, a structure may contain student’s roll-number, student name, average
marks and any other relevant information about the student. Hence, student’s data
might be represented by the following individual variables.
int roll_no;
char name[20];
int m1,m2,m3,total;
float avg;
These variables can be grouped together into a single structure, using the following
definition.
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 104
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
struct student
{
int roll_no;
char name[20];
int m1,m2,m3,total;
float avg;
};
This construction is often called a structure definition. It simply describes a
format called template to represent information. The structure definition creates a new
data type that is used to declare variables.
The allocation of memory takes place only when the structure variables are
declared. A structure variable is similar to other variables.
Structure variable declaration:
Just as any other variables, structure variables can also be declared using the tag
name. Once you have defined a structure type, you can create variables of that type using
the general form.
struct tag-name var-list;
For example,
struct student s1,s2,s3;
Here s1, s2 and s3 are variables of type ‘struct student’.
Each one of these variables has seven members i.e.., roll no, name, m1, m2, m3,
tot and avg.
It is also allowed to combine the definition of the structure type and structure
variables declaration in one statement.

For example:
struct student struct student
{ {
int roll_no; int roll_no;
char name[20]; char name[20];
int m1, m2, m3, tot; [or] int m1, m2, m3,tot; float
avg; float avg;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 105
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
}s1, s2, s3; };
struct student s1, s2,s3;
Initializing structure variable:
The members of a structure variable can also be initialized in the same way as any other
data types.
The general form of structure Initialization is
struct tag-name variable = {value1, value2,....value n};
The first value in the list is assigned to the first member; the second value in
the list is assigned to the second member and so on.
Example:
struct student
{
int roll_no;
char name[20];
int m1, m2, m3, total;
float avg;
};
main( )
{
struct student s1={101,”sai”,25,30,39};
........
........
}
Accessing structure members:
To access members of the structure, we have to use a dot( . ) operator. A
member of a structure can be accessed using the structure variable name and the member
name separated by the dot( . ) operator.
The dot( . ) operator establish a link between the structure variable and
member.
Syntax: structure_variable. member_name
 The dot operator is also known as structure member operator.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 106
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 The student’s roll number of the structure s1 can be accessed by writing
s1.roll_no.
 Similarly, the student’s name of the structure s2 can be accessed by
writing [Link].
Assigning values to members:
We can assign values to the members of a structure in the following ways:
 strcpy ( [Link], “Siri”);
s1.roll_no=101;
 We can also use scanf( ) or gets( ) to give values.
scanf (“%s”, [Link]); or gets([Link]);
scanf(“%d”, &s1.roll_no);
Operations on Structure variables:-
 Structure Variables in assignment Statements:
One structure can be assigned to another, only when they
are of the same structure type using the assignment operator.
Example: student1=student2;
The value of each member of student2 is assigned to the
corresponding member of student1.
4.2.2 Nested structure:-
When a structure is placed within another structure as its member, then the
resultant structure is called nested structure. This means one structure is defined
within another structure.
Example:-
struct account struct deposit
{ {
int acc no; float amount;
char name[30]; [or] struct amount
float balance; {
}; int acc_no;
struct deposit char name[30];
{ float balance;
}ac;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 107
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
float amount;
struct account ac; }customer;
} customer;

Accessing members of nested structures:-


If a structure member is itself a structure, then a member of the embedded
structure can be accessed by chaining all the concerned structure variables (from
outer most to inner most) with the ( . ) dot operator.
To access the members contained in the inner structure, we would write.
[Link].acc_no;
[Link];
However, nesting can be up to any level. We can nest a structure, within
another structure, which is in still another structure and so on.....
Ex:-
struct loan
{
struct deposit
{
struct account
{
int acc_no;
char name[20];
float balance;
}ac;
float amount;
float years;
}dep;
float amount;
char date[10];
}loan 1;
Example: Develop C program to illustrate nested structure concept.
#include<stdio.h>

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 108
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",[Link],[Link], &[Link], [Link]);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone:
%s",[Link],[Link],[Link],[Link]);
}
Output:
Enter employee information?
Arun
Delhi
110001
1234567890
Printing the employee information....
name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
4.2.3 Array of structures:-

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 109
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
A similar type of structures placed under a common variable is called
array of structures. The array will have individual structures as its elements.
For example, to store the details of 40 students in a class, it would be
required to declare 40 different structure variables from s1 to s40, which is
inconvenient. A better method would be to use an array of structures, each
element of the array representing a structure variable.
An array of structures can be declared in two ways.
struct student struct student
{ {
int roll no; int roll no;
char name[20]; char name[20];
int m1, m2, m3, tot; [or] int m1, m2, m3, tot;
float avg; float avg;
}; }s[40];
struct student s[40];
In the above example, s is a 40 element array of structures of the type
student. All elements of the array s[40] are stored in adjacent memory locations.
Accessing elements in Array of structures:-
Any member of the structure can be accessed using the index number
along with the structure name.
For example:
 To access the details of the student 10, we can use the statement
s[9] since the subscript begins with 0.
 To access the name of 10th student, we write
s[9].name;
 Similarly, if we want to print the marks of the first student. we can
use the printf statement
printf(“%d %d %d”, s[0].m1, s[0].m2, s[0].m3);
Initializing Array of structures:-
We can initialize an array of structures in the same way as a single
structure.
struct student

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 110
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
{
int roll no;
char name[20];
int m1, m2, m3, tot;
float avg;
};
struct student s[2]={ {101, “abc”, 36, 38, 39},
{102, “def”, 37, 25, 40}
};
Here, ‘s’ is an array of 2 elements of type student. Thus, s[0] will be
assigned to the first set of values, s[1] will be assigned the second set of values.
The C compiler will assign the values to its elements to the particular
structure as given below.
For the first record
s[0].roll_no=101;
s[0].name=”abc”;
s[0].m1=36;
s[0].m2=38;
s[0].m3=39;
For the second record
s[1].roll_no=102;
s[1].name=”def”;
s[1].m1=37;
s[1].m2=25;
s[1].m3=40;
Example:-
#include<stdio.h>
#include<conio.h>
struct student
{
int roll_no;
char name[20];

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 111
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
int m1, m2, m3,tot;
}s[10];
void main( )
{
int n, i;
clrscr( );
printf(“Enter no. of students :”);
scanf(“%d”, &n);
for(i=0; i<n; i++)
{
printf(“Enter details of student %d”, i+1);
scanf(“%d %s %d %d %d”, &s[i].roll_no, s[i].name, &s[i].m1,
&s[i].m2, &s[i].m3);
}
for(i=0; i<n; i++)
s[i].tot=s[i].m1+s[i].m2+s[i].m3;
printf(“\n Details of %d students:”,n);
for(i=0; i<n; i++)
{
printf(“%d \t %s \t %d \t %d \t %d \t %d \t”
,s[i].roll_no,s[i].name,s[i].m1,s[i].m2,s[i].m3,s[i].tot);
printf(“\n”);
}
getch( );
}
4.2.4 Array within Structures:
1. C allows structures to contain arrays. So far, the members of structure have been
declared as an ordinary data type such as int, char, float only.
2. C permits members of a structure as an array data type also. We have already used
an array of characters inside a structure. Similarly, we can use one- or two-
dimensional arrays of type int or float.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 112
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

4.3 Unions
A union is a derived data type like a structure whose members share the same
storage space within the computer’s memory.
 The members of a union can be of any type.
 The number of bytes used to store a union must be at least enough to hold the
largest number.
Since, the union stores values of different types in a single location it can handle only one
member and thus one data type at any one time.

Declaration of union; -
The syntax for union is identified to that for a structure, except that the keyword
struct is replaced with the keyword union.
The general form of a union is
union tag_name
{
datatype member-1;
datatype member-2;
..........
..........
}variable1,variable2,.................variable-n;
Example:- union sample
{
char c;
int num;
float f_num;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 113
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
}example;
This declares a variable example of type union sample with three members each with a
different data type.

The fact that only one location is allocated for a union variable, the compiler allocates a
piece of storage thet is large enough to hold the largest variable type in the union.

In the above union declaration, the members f-num requires 4 bytes which is largest
among the members.

1001 1002 1003 1004


|< ch>|
|--num--|
|------------f_num---------|

Accessing union members:-


Union members can be accessed in the same manner as structure members using the dot
(.) operator.
The individual members of example are referred to as
[Link]
[Link]
example.f_num
If the variable of union is pointer then the members can be accessed by using ‘’
operator.
 Only one member of a union can be accessed at a time.
 Only that member which is last written, can be read. At this point other variables
will contain garbage values.
Example:-
#include<stdio.h>
#include<conio.h>
union date

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 114
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
{
char name[20];
int day, month, year;
}person;
void main( )
{
clrscr( );
printf(“\n Enter name: ”);
scanf(“%s”, [Link]);
printf(\n Enter day, month and year”);
scanf(“%d%d%d”, &[Link], &[Link], &[Link]);
printf(“Name and Date of birth”);
printf(“\n %s \t %d - %d - %d”, [Link], [Link],
[Link], [Link]);
getch( );
}
Output:-
Enter name: gopi
Enter day, month and year12 2 2000
Name and Date of birth
╨pi 2000 - 2000 - 2000
Operations on union:-
The operations that can be performed on a union are the following:
 A union variable can be assigned to another union of same type.
 A union variable can be passed to a function as a parameter.
 The address of the union variable can be extracted by using the address operator
(&).

Union Within Structure:


C allows to declare a union with in structure in two ways.
[Link] a Union as member in structure- Method1
[Link] Union element as member in structure- Method2

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 115
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

Example Program:
#include<stdio.h>
#include<conio.h>
union address
{
char dno[20];
char street[20];
char city[20];
};
struct student
{
int roll_no;
char name[20];
int m1,m2,m3,total;
union address A;
};
void main()
{
struct student s;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 116
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
clrscr();
printf("\nEnter the roll no of the student");
scanf("%d",&s.roll_no);
printf("\nEnter the name of the student");
scanf("%s",[Link]);
printf("\nEnter the student three subject marks");
scanf("%d%d%d",&s.m1,&s.m2,&s.m3);
[Link]=s.m1+s.m2+s.m3;
printf("\nThe student total marks is %d",[Link]);
printf("\nEnter the student address");
printf("\nEnter the student [Link]");
scanf("%s",[Link]);
printf("\nThe student [Link] is %s",[Link]);
printf("\nEnter the student street");
scanf("%s",[Link]);
printf("\nThe student street is %s",[Link]);
printf("\nEnter the student city");
scanf("%s",[Link]);
printf("\nThe student city is %s",[Link]);
getch();
}
/*Output:-
Enter the roll no of the student1
Enter the name of the studenthari
Enter the student three subject marks12 13 15
The student total marks is 40
Enter the student address
Enter the student d.no1-2/45
The student [Link] is 1-2/45
Enter the studentstreetbenzcircle
The student street is benzcircle
Enter the student cityvijayawada

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 117
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
The student city is vijayawada */
4.4 Differences Between Structure and Union:

Structures Unions

You can use a struct keyword to define a You can use a union keyword to define a
structure. union.

Every member within structure is assigned a In union, a memory location is shared by all
unique memory location. the data members.

Changing the value of one data member will


Changing the value of one data member will
change the value of other data members in
not affect other data members in structure.
union.

It enables you to initialize several members It enables you to initialize only the first
at once. member of union.

Syntax: Syntax:
struct structure_name union structure_name
{ {
datatype member1; datatype member1;
datatype member2; datatype member2;
}variable_name; }variable_name;

Example: Example:
struct example union example
{ {
int i; int I;
char c; char c;
float f; float f;
} }

The total size of the structure is the sum of The total size of the union is the size of the
the size of every data member. largest data member.

Size of the above structure is Size of the above union is

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 118
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

Size_of(i)+size_of(c)+size_of(f)= max(size_of (i), size_of(c), size_of(f))=


2+1+4=7bytes max(2,1,4)=4bytes

It is mainly used for storing various data It is mainly used for storing one of the many
types. data types that are available.

It occupies space for each and every It occupies space for a member having the
member written in inner parameters. highest size written in inner parameters.

You can access one member at a time in the


You can retrieve any member at a time.
union.

It supports flexible array. It does not support a flexible array.

Classification of datatypes:(Additional Knowledge)

typedef:-
‘typedef’ is a key word that allows the programmer to create new data
type name for an existing data type.
 No new data type is produced but an alternate name is given to a known data
type.
General form of declaring typedef is:-
typedef existing data type new data type;
Example:-
If we want to declare an integer variable, we can use “roll_no” instead of “int”.
typedef int roll_no;
 Structure can also use typedef keyword.
Consider a structure
struct student
{
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 119
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
int roll_no;
char name[20];
};
struct student s1;
 structure variable
If we place typedef before struct in structure definition
typedef struct student
{
int roll_no;
char name[20];
}stud; ----- a new name to type “struct student”.
Here ‘stud’ is not structure variable. It is structure type, that means we can
declare a variable for the student structure by using the below statement.
stud s1;
Instead of
struct student s1;
Enumeration type:- (enum)
An enumeration is a user-defined data type consists of integral constants
and each integral constant is given a name.
The general form of declaring enumeration type:
enum tagname{member 1, member 2,.........member n}variable 1,
variable 2,.........variable n;
[or]
enum tagname
{
member 1,
member 2,
...........,
...........,
member n
} variable 1, variable 2,.........variable n;
The general form of declaring a variable to the enumeration type:

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 120
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
enum tagname variable 1, variable 2,.........variable n;
 The members are integer constants.
 By default, the first member is given the value 0, the second member is given
the value 1 and so on.
 Members within the braces may be initialized. In this case, the next member
given the value one more than the preceding number.
Example:-
enum day{mon, tue, wed, thur, fri, sat};
enum day day 1, day 2, day 3;
day1=mon;
day2=tue;
day3=wed;
Here day 1, day 2, day 3 are variables for the enum type ‘day’.

4.9 Write C program to find out sum of given array elements using Pointers.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50}; // Declare and initialize an array
int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
int sum = 0; // Initialize sum to 0
int *ptr; // Declare a pointer to an integer

ptr = arr; // Point the pointer to the first element of the array (base address)
// Iterate through the array using the pointer
for (int i = 0; i < size; i++) {
sum += *ptr; // Add the value pointed to by ptr to sum
ptr++; // Increment the pointer to point to the next element
}
printf("Sum of array elements: %d\n", sum); // Print the calculated sum
return 0;
}
4.10 Develop C program to illustrate nested structure concept

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 121
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
#include <stdio.h>
#include <string.h>
struct student // Declaration of Outer structure
{
char name[20];
int roll_no;
struct class { // Declaration of Inner structure
char branch[5];
char section;
}c1;
}s1;

int main() {
printf(“Enter student information”);
scanf(“%s%d%s%c”, &[Link], &s1.roll_no, &[Link], &[Link]);
};

printf("Student name : %s\n",


[Link]);
printf("Roll no: %d\n",
s1.roll_no);
printf("Branch : %s\n",
[Link]);
printf("Section : %c\n",
[Link]);
return 0;
}
4.11 Implement C code to read ‘n’ students information using array of structures
concept.
#include <stdio.h>
struct Student { // Define the structure for a student
char name[50];

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 122
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
int rollNumber;
float marks;
}s;
int main() {
int n;
// Get the number of students from the user
printf("Enter the number of students: ");
scanf("%d", &n);
// Loop to read information for each student
for (int i = 0; i < n; i++) {
printf("\nEnter details for Student %d:\n", i + 1);
printf("Enter Name: ");
scanf("%s", s [i].name);
printf("Enter Roll Number: ");
scanf("%d", &s[i].rollNumber);
printf("Enter Marks: ");
scanf("%f", &s[i].marks);
}

// Loop to display information for each student


printf("\n--- Student Information ---\n");
for (int i = 0; i < n; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Name: %s\n", s[i].name);
printf("Roll Number: %d\n", s[i].rollNumber);
printf("Marks: %.2f\n", s[i].marks);
}
return 0;
}

Assignment Cum Tutorial Questions

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 123
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Short answer Questions

[Link] Questions BL

1. Define a Pointer. L1

2. How to declare a pointer variable. L1

3. What are the arithmetic operations that can be performed on Pointers. L1

4. Define a structure. L1

5. Define a union. L1

6. How to initialize a structure. Explain with an example. L1

7. How to initialize a union. Explain with an example. L1

8. What is a Nested Structure? L1

9. Define Array of Structure with an example. L1

10. List any two differences between structure and union. L1

4.1 Pointers
4.1.1 Definition, Declaration, initialization
Objective Questions

1. What is the primary purpose of a pointer in C?


a) To store character data
b) To store the memory address of another variable
c) To perform arithmetic operations on integers
d) To define functions
2. Which of the following correctly declares a pointer to an integer variable x?
a) int *ptr = &x;
b) int ptr = &x;
c) int *ptr = x;
d) int &ptr = x;
3. What will be the output of the following C code snippet?

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 124
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
int a = 10;
int *ptr = &a;
printf("%d", *ptr);
a) &a
b) ptr
c) 10
d) A memory address
4. Which of the following is used to dynamically allocate memory in C?
a) malloc()
b) free()
c) sizeof()
d) printf()
5. What is a NULL pointer?
a) A pointer that points to the first element of an array
b) A pointer that points to a function
c) A pointer that does not point to any valid memory location
d) A pointer that stores the value 0

Descriptive Questions

[Link] Questions BL

1. Explain how to declare, initialize and access a Pointer with proper syntax. L2

2. What is pointer? How to declare and initialize a pointer? What are the
L2
advantages of pointers?
4.1.2 de-referencing and address operators
Objective Questions
6. What does the * operator represent when used with a pointer variable?
a) Address-of operator
b) Dereference operator (value-at operator)
c) Multiplication operator
d) Logical AND operator

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 125
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
7. What does the & operator represent when used with a pointer variable?
a) Address-of operator
b) Dereference operator (value-at operator)
c) Multiplication operator
d) Logical AND operator
Descriptive Questions

[Link] Questions BL

1 Explain about the de-referencing and address operators in pointers L2

4.1.3 Pointer Arithmetic


Objective Questions
8. What is pointer arithmetic?
a) Performing mathematical operations on the values pointed to by pointers
b) Performing mathematical operations on the memory addresses stored in
pointers
c) Converting pointer types to integer types
d) Comparing the values of two pointers
Descriptive Questions

[Link] Questions BL

1 Explain the Arithmetic operations that can be performed on pointer variable. L2

4.1.4 Array manipulation using pointers.


Objective Questions

9. If arr is an array and ptr is a pointer initialized to arr, what does


*(ptr + 2) represent?
a) The address of the third element of arr
b) The value of the third element of arr
c) The address of the second element of arr

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 126
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
d) The value of the second element of arr
Descriptive Questions

[Link] Questions BL

1 Explain how to perform array manipulation with the help of pointers. L2

2 Write a C program to find out sum of given array elements using Pointers. L3

3 Write a C program to access elements of an array using pointers. L3

4.1.5 Pointers and Strings


Objective Questions
10. What does the following C code snippet print?
#include <stdio.h>
int main() {
char str[] = "Hello";
char *ptr = str;
printf("%c", *(ptr + 2));
return 0;
}
a) H
b) e
c) l
d) o
Descriptive Questions

[Link] Questions BL

1 Explain how a string can be accessed using pointers L1

4.2 User Defined Data types


4.2.1 Structures: definition, Syntax, initialization and accessing
Objective Questions
11. What is a structure in C language?

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 127
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
A) A collection of elements of the same data type.
B) A collection of elements of different data types.
C) A mechanism for defining functions within a data type.
D) A way to create dynamic arrays.
12. How are members of a structure accessed using a pointer to that structure?
A) Using the dot operator (.)
B) Using the arrow operator (->)
C) Using the double colon operator (::)
D) Using the dereference operator (*)
13. Which of the following statements about structure members is true?
A) Structure members are always stored in contiguous memory locations.
B) Individual members of a structure can be initialized within the structure type
declaration.
C) Storage class can be assigned to individual members of a structure.
D) Structure members can be of the same structure type (recursive structures).
14. What is the purpose of the typedef keyword when defining structures in C?
A) To declare a new type of structure.
B) To alias an existing structure type with a new name.
C) To prevent the definition of the structure from being modified.
D) To declare a structure as a constant.
15. What is the size of a C structure?
A) It is always a fixed size, like 128 bytes.
B) It is the sum of the sizes of all its members, potentially with padding for
alignment.
C) It is the size of the largest member in the structure.
D) It is determined dynamically at runtime.
Descriptive Questions

[Link] Questions BL

1 Explain how to declare, initialize and access members of the structure.

2 Write a C program using structures to read the employee name, id, salary and

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 128
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
display them.

4.2.2 Nested structures


16. Which of the following statements accurately describes a nested structure in C?
a) A structure defined inside a function.
b) A structure that contains members of different data types.
c) A structure declared as a member of another structure.
d) A structure that can only hold a single value at a time.
17. How are members of an inner (nested) structure accessed in C,
assuming outerStruct is an instance of the outer structure and innerMember is a
member of the inner structure?
a) [Link]
b) outerStruct->innerStruct->innerMember
c) [Link]
d) outerStruct->innerMember
Descriptive Questions

[Link] Questions BL

1 Write a C program using nested structures to read the student details and
display them. Consider student name, roll no as outer structure members and L3
native place, area as inner structure members.

2 Explain the concept of nested Structures. L2

4.2.3 Array of structures.


Objective Questions

18. Which of the following correctly declares an array of 5 Student structures,


where Student is a previously defined structure?
a) struct Student students[5];
b) Student students[5];
c) struct students Student[5];
d) array of struct Student students[5];

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 129
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
19. How do you access the name member of the third element in an array
of Person structures named people?
a) [Link]
b) people[2].name
c) people->name
d) [Link]
Descriptive Questions

[Link] Questions BL

1 Explain the concept of Array of Structures. L2

Implement C code to read ‘n’ students information using array of structures


2
concept. Consider student name, rollno, five subject marks as members and L3
calculate the total marks.

4.2.4 Array within structures


Objective Questions

20. What is the primary advantage of using an array within a structure?


a) It allows for dynamic memory allocation for the array.
b) It simplifies the declaration of multiple variables of the same type.
c) It allows grouping related data, including collections, into a single logical unit.
d) It enables direct manipulation of memory addresses.
21. Consider the following C code snippet.
struct Student {
char name[50];
int marks[5];
};
How would you access the third mark of a Student variable named s1?
a) [Link].3
b) [Link][3]
c) s1->marks
d) [Link]

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 130
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

Descriptive Questions

[Link] Questions BL

1 Explain the concept of Array within Structures. L2

2 Write a C program to create a structure to read student details (Name, Age L3


and marks in three subjects) and display the same.

4.3 Unions: definition, syntax initialization and accessing


Objective Questions

22. Which keyword is used to declare a union in C?


a) struct
b) class
c) union
d) enum
23. What determines the size of a union in C?
a) The sum of the sizes of all its members.
b) The size of its smallest member.
c) The size of its largest member.
d) The size of the first member declared.
24. How many members of a union can hold a value at any given time?
a) All members simultaneously.
b) Only one member at a time.
c) A maximum of two members.
d) It depends on the number of members.
25. Consider the following union declaration:
union Data {
int i;
float f;
char c;
};

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 131
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
If sizeof(int) is 4 bytes, sizeof(float) is 4 bytes, and sizeof(char) is 1 byte, what
is sizeof(union Data)?
a) 9 bytes
b) 1 byte
c) 4 bytes
d) 3 bytes
26. How are members of a union accessed?
a) Using the -> operator for all cases.
b) Using the . operator for union variables and -> for pointers to unions.
c) Using the :: operator.
d) Only through pointers.
Descriptive Questions

[Link] Questions BL

1 Explain how to declare, initialize and access members of the union. L2

4.4 Differences between structure and union


Objective Questions

27. Which of the following statements accurately describes a key difference between
structures and unions in C?
a) Structures allocate memory for all their members separately, while unions
allocate a shared memory location for all their members, equal to the size of the
largest member.
b) Structures allow only one member to be accessed at a time, whereas unions
allow all members to be accessed simultaneously.
c) The size of a structure is always equal to the size of its largest member, while
the size of a union is the sum of the sizes of all its members.
d) Structures are used for memory optimization, while unions are primarily used
for grouping related data of different types.
Descriptive Questions

[Link] Questions BL

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 132
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1 Compare between structures and unions L3

Unit-V
Functions & File Handling
Syllabus:
Functions

5.1 Introduction to Functions


5.1.1 Definition
5.1.2 Syntax and Calling

5.2 Function call return types

5.3 Types of arguments

5.4 Parameter passing techniques


5.4.1 call by value
5.4.2 call by reference

5.5 Recursion

5.6 Modifying parameters inside function using pointers

5.7 Array as parameter to the function

5.8 Scope and lifetime of variables: local and global variables

5.9 Storage classes: auto, static, extern and register.

5.10 File Handling


5.10.1 Definition of file
5.10.2 Types of files
5.10.3 File opening modes
5.10.4 Basic file Operations: open, read/write and close,
5.10.5 File I/O: fscanf(), fprintf(), fgets(), fputs(), fgetc(), fputc(), fread() and
fwrite()
5.10.6 Random access files: fseek(), ftell(), rewind()

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 133
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
5.11 Problem Solving:
5.11.1 Write a C program to find out GCD of given two numbers using
recursion
5.11.2 Develop C program to access file using Random access methods.
5.11.3 Implement C code to illustrate Call by value and Call by reference
mechanisms.
5.1 Introduction to Functions
5.1.1 Definition: A function is a self-contained block of program statements that
performs a particular task.
 We have written ‘C’ programs using three functions namely, main, printf and
scanf.
 Every program must have a main function to indicate where the execution of the
program begins and ends.
 If the program is large and if we write all the statements of that large program in
main itself, the program may become too complex and large.
 As a result, the task of debugging, testing and even understanding will become
very difficult.
 So, the best way to develop a large program is to construct it from smaller pieces
(or) modules.
 A module can be a single function (or) a group of related functions carrying out a
specific task.
 Usually, it is easier to break down a difficult task into a series of smaller tasks and
then to solve those subtasks individually and later combined into a single unit.
 These subtasks are called User-defined functions.

Advantages:
 Using functions one can avoid rewriting the same code again and again.
 It is easy to write a function that does a particular job.
 It facilitates top-down modular programming. That means, the complexity of the
entire program can be divided into simple subtasks and function can be written for
each subtask.
 The length of the source program can be reduced.
 Saves memory space.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 134
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 Easier to write, testing and debugging individual functions.
 It increases program readability.
 A function can be shared by other programs.

General form of a function/Definition of Function :


5.1.2 Syntax:
type function-name(argument list) ----- function header.
{
Local variable declaration;
Statement 1;
Statement 2; function body
..........
..........
Return(expression);
}
Example: Define a function name myFunction() to display the message “I just got
executed!"
void myFunction() //Called Function
{
printf("I just got executed!");
}

 Here, type specifies the type of data that the function returns. A function may
return any type of data except an array.
 The type and argument list are optional.
 An unspecified type is always assumed by the compiler to int. int is the default
type when no type specifier is present.
 A function returns a type other than int, it must be explicitly declared.
 The function-name is any valid identifier.
 The argument list contains receive values from a calling function.
 We have two types of arguments:
 Formal arguments
 Actual arguments
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 135
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 The Formal arguments are defined in the calling function.
 The data which is passed from the calling function to called function are called
the Actual arguments. The actual arguments are passed to the called function
through a function call.
 A function may (or) may not send a value back to the calling function. The value
which is sent to the calling function is the return value of the function. It is
achieved through the return statement.
 The return statement returns a value to the calling function. When the return
statement is encountered the control is immediately passed back to the calling
function.

Characteristics of functions :
 Any function can return only one value.
 Parameter argument list is optional.
 Return statement indicates exit from the function and return to the point from
where the function was invoked.
 A function can call any number of items.
 A call to the function must end with a semicolon.
 Any ‘C’ function cannot be defined in other function.
 When a function is not returning any value, void type can be used as return type.
 ‘C’ allows recursion i.e..., a function can call itself.

Example1: C Program to create and call the user defined function


#include<stdio.h>
#include<conio.h>
void myFunction() //Called Function
{
printf("I just got executed!");
}
int main()
{
myFunction(); // Calling Function
return 0;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 136
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
}
Output:
I just got executed!
5.2 Function call return types (or) Categories of function:
According to the arguments and return values, there are four types of user defined
functions.
1. Functions with no arguments and no return values.
2. Functions with arguments and no return values.
3. Functions with arguments and return values.
4. Functions with no arguments and return values.

Functions with no arguments and no return values :


In this type of function, the called function doesn’t take arguments from the
calling function and it will not give any return value to the calling function.

Syntax:  for function calling:


function name( );
 for function definition:
void fun-name( )
{
local variable declaration;
statements;
.........
.........
}

Example:
// C program to use function with no argument and no return values
#include <stdio.h>
void sum()
{
int x, y;
printf("Enter x and y\n");

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 137
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
scanf("%d %d", &x, &y);
printf("Sum of %d and %d is: %d", x, y, x + y);
}
int main()
{
sum(); // function call
return 0;
}

Functions with arguments and no return values :


In this type of functions, the called function can take the arguments from the
calling function but it will return any values to the calling function.
Syntax :  for function definition:
void fun-name(datatype arg1, datatype arg2,...........)
{
local variable declaration;
statements;
..........
..........
}
 For function calling:
fun-name(arg1, arg2, ..... );

Example:
// C program to use function with argument and no return values
#include <stdio.h>
void sum(int x, int y)
{
printf("Sum of %d and %d is: %d", x, y, x + y);
}
int main()
{

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 138
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
int x, y;
printf("Enter x and y\n");
scanf("%d %d", &x, &y);
sum(x, y);
return 0;
}

Functions with arguments and return values :


In this type of functions, the called function can take the arguments from the
calling function and it will give some return values to the calling function.
Syntax:  for function definition:
return type fun-name(datatype arg1, datatype arg2,...........)
{
local variable declaration;
statements;
..........
..........
}
 For function calling:
var-name= fun-name(arg1, arg2, ..... );

Example:// C program to use function with argument and with return values
#include <stdio.h>
int sum(int x, int y)
{
return x + y;
}
int main()
{
int x, y;
printf("Enter x and y\n");
scanf("%d %d", &x, &y);

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 139
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf("Sum of %d and %d is: %d", x, y, sum(x, y));
return 0;
}
Functions with no arguments and return values :
In this type of functions, the called function returns some value to the calling
function. But it doesn’t take any arguments from the calling function.
Syntax :  for function definition:
return type fun-name( )
{
local variable declaration;
statements;
..........
..........
return(exp);
}
 For function calling:
var-name= fun-name( );

Example : // C program to use function with no argument and with return values
#include <stdio.h>
int sum()
{
int x, y, s = 0;
printf("Enter x and y\n");
scanf("%d %d", &x, &y);
s = x + y;
return s;
}
int main()
{
printf("Sum of x and y is %d", sum());
return 0;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 140
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
}
5.3 Types of Arguments:
Basically, there are two types of arguments:
1. Actual arguments
2. Formal arguments
The variables declared in the function prototype or definition are known as Formal
arguments and the values that are passed to the called function from the main function are
known as Actual arguments. The following code snippet shows the types of arguments in
C.

Example: C Program to Demonstrate Types of Arguments


# include <stdio.h>
int add (int x, int y)// Here x,y are Formal Arguments
{
return ( x + y );
}
int main()
{
int x, y, z;
x = 5;
y = 5;
z = add(x,y); // Here x,y are Actual Arguments
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 141
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
return 0;
}
Note: Regarding types of arguments, The actual and formal argument names need not be
same but datatypes must match.
Example: C Program to Demonstrate Types of Arguments
# include <stdio.h>
int add (int a, int b)// Here a,b are Formal Arguments
{
return ( a + b );
}
int main()
{
int x, y, z;
x = 5;
y = 5;
z = add(x,y); // Here x,y are Actual Arguments
return 0;
}
5.4 Parameter Passing Techniques
There are two methods to pass the data into the function in C language, i.e.,
1. call by value and
2. call by reference.

5.4.1 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.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 142
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 In call by value method, we cannot modify the value of the actual parameter by
the formal parameter.
 In call by value, different memory is allocated for actual and formal parameters
since the value of the actual parameter is copied into the formal parameter.
 The actual parameter is the argument which is used in the function call whereas
formal parameter is the argument which is used in the function definition.
Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b);
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
5.4.2 Call by reference
 In call by reference, the address of the variable is passed into the function call as
the actual parameter.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 143
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
 In call by reference, the memory allocation is similar for both formal parameters
and actual parameters. All the operations in the function are performed on the
value stored at the address of the actual parameters, and the modified value gets
stored at the same address.
Example: Swapping the values of the two variables
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
}
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
Difference between call by value and call by reference in C
Call by value Call by reference
A copy of the value is passed into the An address of value is passed into the

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 144
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
function function
Changes made inside the function is Changes made inside the function validate
limited to the function only. The values outside of the function also. The values of
of the actual parameters do not change by the actual parameters do change by changing
changing the formal parameters. the formal parameters.
Actual and formal arguments are created Actual and formal arguments are created at
at the different memory location the same memory location
5.5 Recursion:
A function, which invokes itself repeatedly until some condition is satisfied, is
called a recursive function.
 The normal function will be called by main function whenever the function name
is used.
 On the other hand, the recursive function will be called by itself repeatedly, until
some specified condition has been satisfied.
 This technique is used to solve problems whose solution is expressed in termsof
successively applying the same set of steps.
For example:
the factorial of a positive integer number ‘n’ is defined as
n!=n(n-1)(n-2).....1 with 1!=1, 0!=1.
The above formula can also be written as
n!=n(n-1)!
For example 5!=(5)(4!)
=5*4*3!
=5*4*3*2!
=5*4*3*2*1!
=5*4*3*2*1
= 120.
In ‘C’, a recursive function that calculates n! can be written as follows.
int factorial(int n)
{
if(n==1)
return 1;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 145
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
else
return(n*factorial(n-1));
}
/*C program for finding factorial of a given number without recursion*/
#include<stdio.h>
#include<conio.h>
int fact(int);
void main( )
{
int n,f;
clrscr( );
printf(“\n Enter n value”);
scanf(“%d”,&n);
f=fact(n);
printf(“\n The factorial of %d is %d”, n, f);
getch( );
}
int fact(int x)
{
int f;
for(i=0; i<=x; i++)
f=f * i;
return f;
}
/*C program for finding factorial of a given number with recursion*/
#include<stdio.h>
#include<conio.h>
int fact(int);
void main( )
{
int n,f;
clrscr( );

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 146
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf(“\n Enter n value”);
scanf(“%d”,&n);
f=fact(n);
printf(“\n The factorial of %d is %d”, n, f);
getch( );
}
int fact(int x)
{
if(x==0)
return 1;
else if(x==1)
return 1;
else
return(x*fact(x-1));
}
/*C program for generating Fibonacci sequence without recursion*/
#include<stdio.h>
#include<conio.h>
void fib(int);
void main( )
{
int n;
clrscr( );
printf(“\n Enter n value”);
scanf(“%d”,&n);
fib(n);
getch( );
}
void fib(int x)
{
int i, first=0, second=1, next;
for(i=0; i<n; i++)

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 147
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
{
if(n<=1)
next=i;
else
{
next = first + second;
first = second;
second = next;
}
printf(“%d \t”,next);
}
}
/*C program for generating Fibonacci sequence with recursion*/
#include<stdio.h>
#include<conio.h>
int fib(int);
void main( )
{
int n, f;
clrscr( );
printf(“\n Enter n value”);
scanf(“%d”,&n);
for(i=1; i<=n; i++)
{
f=fib(i);
printf(“%d \t”,f);
}
getch( );
}
int fib(int x)
{
if(x==1)

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 148
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
return 0;
else if(x==2)
return 1;
else
return fib(x-1) + fib(x-2);
}
5.6 Modifying Parameters Inside Function Using Pointers
In function body allows to change the actual argument of the variable in the main
function by using pointers. The following example shows to modify the parameters inside
the function using pointers.
Example: C program to modifying parameters inside function using pointers
#include <stdio.h>
void testing(char **s)
{
*s = "hi";
}
int main()
{
char *s = "hello";
testing(&s);
printf("%s\n", s);
}
Output
hi
5.7 Array as Parameter to the Function
In C, there are various general problems which requires passing more than one
variable of the same type to a function. For example, consider a function which sorts the
10 elements in ascending order. Such a function requires 10 numbers to be passed as the
actual parameters from the main function. Here, instead of declaring 10 different numbers
and then passing into the function, we can declare and initialize an array and pass that
into the function. This will resolve all the complexity since the function will now work
for any number of values.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 149
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

As we know that the array_name contains the address of the first element. Here, we must
notice that we need to pass only the name of the array in the function which is intended to
accept an array. The array defined as the formal parameter will automatically refer to the
array specified by the array name defined as an actual parameter.

syntax to pass an 1-D array to the function.


functionname(arrayname);//passing array
Example: C program to pass an array to function and find the minimum number in an
array.
#include<stdio.h>
int minarray(int arr[],int size)
{
int min=arr[0];
int i=0;
for(i=1;i<size;i++)
{
if(min>arr[i])
{
min=arr[i];
}
}//end of for
return min;
}//end of function
int main()
{
int i=0,min=0;
int numbers[]={4,5,7,3,8,9};//declaration of array
min=minarray(numbers,6);//passing array with size
printf("minimum number is %d \n",min);
return 0;
}

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 150
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Output
minimum number is 3
Example: C Program to pass 2-D array as argument to the function
#include <stdio.h>
const int N = 3;

void print(int arr[][N], int m)


{
int i, j;
for (i = 0; i < m; i++)
{
for (j = 0; j < N; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main()
{
int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
print(arr, 3);
return 0;
}
Output
123
456
789
5.8 Scope and Lifetime of a variable:
Scope of the variable: The scope of a variable refers to the parts of the program till
which the value of the variable can be accessed.
Lifetime of the variable: This determines how long the variable will stay alive across

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 151
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
the whole program.
Local and Global Variables:
Local Variable
The variable that is declared in a function or code is called a local variable. The scope of
Local variables is within the defined function only. You cannot use a local variable
outside the function (in which it is declared).
Example: C Program of local variables.
#include <stdio.h>
void person()
{
// Local Variables of the function
int age = 20;
float height = 5.6;
printf("age is %d \n", age);
printf("height is %f", height);
}
int main()
{
person();
return 0;
}
Output:
age is 20
height is 5.600000
Global Variables
The scope of the global variable is the entire program. They are not defined inside any
function and can be used in any function.

Example: Program to use a global variable in C


#include <stdio.h>
// Declaring global variable
int a = 23;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 152
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
void function1()
{
// Function using global variable a
printf("The number is %d \n", a);
}
void function2()
{
// Function using global variable a
printf("The number is %d \n", a);
}
int main()
{
// Calling functions
function1();
function2();
return 0;
}
Output
The number is 23
The number is 23
5.9 Storage Classes
There are four storage classes in C they are as follows
1. Automatic Storage Class

2. Register Storage Class

3. Static Storage Class

4. External Storage Class

Automatic Storage Class:


A variable defined within a function or block with auto specifier belongs to automatic
storage class. All variables defined within a function or block by default belong to
automatic storage class if no storage class is mentioned. Variables having automatic
storage class are local to the block which they are defined in, and get destroyed on exit
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 153
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
from the block.
Example: C program demonstrates the visibility level of auto variables.
#include <stdio.h>
int main( )
{
auto int i = 1
{
auto int i = 2;
{
auto int i = 3;
printf ( "\n%d ", i);
}
printf ( "%d ", i);
}
printf( "%d\n", i);
}

OUTPUT
321
Register Storage Class
The register specifier declares a variable of register storage class. Variables
belonging to register storage class are local to the block which they are defined in, and
get destroyed on exit from the block. A register declaration is equivalent to an auto
declaration, but hints that the declared variable will be accessed frequently; therefore,
they are placed in CPU registers, not in memory. Only a few variables are actually placed
into registers, and only certain types are eligible; the restrictions are implementation-
dependent. However, if a variable is declared register, the unary & (address of) operator
may not be applied to it, explicitly or implicitly. Register variables are also given no
initial value by the compiler.
Example: C Program to demonstrate Register Storage class
#include<stdio.h>
int main()

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 154
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
{
int num1,num2;
register int sum;
printf("\nEnter the Number 1 : ");
scanf("%d",&num1);
printf("\nEnter the Number 2 : ");
scanf("%d",&num2);
sum = num1 + num2;
printf("\nSum of Numbers : %d",sum);
return(0);
}
Static Storage Class
The static specifier gives the declared variable static storage class. Static variables
can be used within function or [Link] global variables, static variables are not visible
outside their function or file, but they maintain their values between calls. The static
specifier has different effects upon local and global variables.
visible only to the function or block in which it is defined. In simple terms, a
static local variable is a local variable that retains its value between function calls. For
example, the following program code defines static variable i at two places in two blocks
inside function staticDemo(). Function staticDemo() is called twice within from main
function. During second call static variables retain their old values and they are not
initialized again in second call of staticDemo().
Example: C Program to demonstrate static storage class.
#include <stdio.h>
void staticDemo()
{
static int i;
{
static int i = 1;
printf("%d ", i);
i++;
}

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 155
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf("%d\n", i);
i++;
}

int main()
{
staticDemo();
staticDemo();
}
Output:
10
21
/* staticdemo.c */
#include <stdio.h>
static int gInt = 1;
static void staticDemo()
{
static int i;
printf("%d ", i);
i++;
printf("%d\n", gInt);
gInt++;
}

int main()
{
staticDemo();
staticDemo();
}
Output:
01
12

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 156
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Static variables have default initial value zero and initialized only once in their lifetime.
External Storage Class
The extern specifier gives the declared variable external storage class. The
principal use of extern is to specify that a variable is declared with external linkage
elsewhere in the program. To understand why this is important, it is necessary to
understand the difference between a declaration and a definition. A declaration declares
the name and type of a variable or function. A definition causes storage to be allocated
for the variable or the body of the function to be defined. The same variable or function
may have many declarations, but there can be only one definition for that variable or
function.

When extern specifier is used with a variable declaration then no storage is allocated to
that variable and it is assumed that the variable has already been defined elsewhere in the
program. When we use extern specifier the variable cannot be initialized because with
extern specifier variable is declared, not defined.

In the following sample C program if you remove extern int x; you will get an error
"Undeclared identifier 'x'" because variable x is defined later than it has been used in
printf. In this example, the extern specifier tells the compiler that variable x has already
been defined and it is declared here for compiler's information.
Example: C Program to demonstrate external storage class
#include <stdio.h>
extern int x=10;
int main()
{
printf("x: %d\n", x);
}
Output
x : 10
510 File Handling
Introduction
When a large volume of data is involved, supplying data through the keyboard

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 157
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
during the execution or displaying the output on the screen is not convenient. The input
data can be stored on disks and the program may access the data from disks for
[Link], the results may be stored on disks. For such applications, files are
needed.
5.10.1 Definition:
A file is a place on the disk where a group of related data is stored. In C, file
manipulations may be done in two ways:
 Low-level I/O using system calls
 High-level I/O using functions from standard I/O library
 The files accessed through the library functions are called Stream
Oriented files and the files accessed with system calls are known as System
Oriented files.
Streams
When a program begins, there are three available streams:
 Standard input (stdin) is the stream where a program gets its input data
 Standard output (stdout) is the stream where a program writes its output
data.
 Standard error (stderr) is another output stream typically used by
programs to output error messages.
5.10.2 Types of Files
There are two types of files in C language which are as follows −
1. Text file
2. Binary File
Text File
1. It contains alphabets and numbers which are easily understood by human beings.
2. An error in a text file can be eliminated when seen.
3. In text file, the text and characters will store one char per byte.
4. For example, the integer value 4567 will occupy 2 bytes in memory, but, it will
occupy 5 bytes in text file.
5. The data format is usually line-oriented. Here, each line is a separate command.
Binary file
1. It contains 1’s and 0’s, which are easily understood by computers.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 158
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
2. The error in a binary file corrupts the file and is not easy to detect.
3. In binary file, the integer value 1245 will occupy 2 bytes in memory and in file.
5.10.3 File Modes:
r opening a file in read mode
w write text mode (truncates file to zero length if it already exits or creates new file)
a append text mode for writing (opens or creates file and sets file pointer to the end-
of-file)
rb read binary mode
wb write binary mode (truncates file to zero length if it already exits or creates new
file)
ab append binary mode for writing (opens or creates file and sets file pointer to the
end-of-file)
r+ read and write text mode
w+ read and write text mode (truncates file to zero length if it already exists or creates
new file)
a+ read and write text mode (opens or creates file and sets file pointer to the end-of-
file)
r+b/rb+ read and write binary mode
w+b/wb+ read and write binary mode (truncates file to zero length if it already exists
or creates new file)
a+b/ab+ read and write binary mode (opens or creates file and sets file pointer to
the end-of-file)

 If the file does not exist and it is opened with read mode (r), the file open fails
and it will return NULL to file pointer.
 If the file is opened with append mode (a), all write operations occur at the end of
the file regardless of the current file position.
 If the file is opened in the update mode (+), output cannot be directly followed by
input and input cannot be directly followed by output without an intervening fseek(),
fsetpos(), rewind(), or fflush().
5.10.4 File Operations
 Files are associated with streams and must be open in order to use it. The

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 159
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
point of I/O within a file is determined by the file position.
 When a file is opened, the file position points to the beginning of the file
unless the file is opened for an append operation - in which case the position
points to the end of the file. The file position indicates where the next operation
(read/write) will occur.
 When a file is closed, no more actions can be taken on it until it is opened
again. Exiting from the main function causes all open files to be closed.
In C, ‘FILE’ is a structure that holds the description of a file and is defined in
stdio.h.
Basic File operations are:
 Opening a File
 Reading from and/or writing into a File
 Closing the File

General form:
FILE *fp;
File Handling Functions:
fopen()---------opening a file
General form
fopen(“filename”,”mode”);
 fopen() returns the file pointer position for successful open and
returns NULL, if the file does not open or the file does not exist.
fclose()-----------closing a file
General form
fclose(file pointer);
fclose() returns zero for successful close and returns EOF (end of file) when error is
encountered in closing a file. By default, all the files opened are closed when the
program is terminated.
It is good to close all the files opened with fopen(), because files can be reopened only if
they are closed.
5.10.5 File I/O operations
The Standard I/O provides variety of functions to handle files. It supports the following

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 160
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
ways of reading from and writing into file:
 zCharacter I/O
 String I/O
 Integer I/O
 Formatted I/O
 Block
I/O

Character I/O
Using character I/O, one character (byte) can be written to or read from a file at a time.
Writing in to a file
 To write into a file, the file must be opened in ‘w’ mode The function
putc() is used to write a byte to a file.
General Form:
putc(ch,fptr);
 This function writes the character ch into a file pointed by the file pointer
fptr. This fptr may be stdout, which represents standard output device, monitor as
a file. On success, the character is returned.
 If an error occurs, the error indicator for the stream is set and EOF is
returned.

Reading from a file


 The function getc() is used to read a byte from a file. This may be a macro
version of fgetc.
General Form:
ch =getc (fptr);
 This function reads a character from the file and it is returned to the
program defined character variable. After reading a character, the pointer is
moved to the next position.
 The fptr may be stdin, which represents a standard input device, keyboard
as a file. On success, the character is returned. If the end-of-file is encountered,
EOF is returned and the end-of-file indicator is set.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 161
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
 If an error occurs, the error indicator for the stream is set and EOF is
returned. The EOF is end of file status flag, which is true if end of file is reached,
otherwise false.
String I/O
Using string I/O, string can be written to, or read from, a file at a time.
Writing a string in to a file
 The function used is fputs(). Writes a string to the specified stream till the
last character is read but does not include the null character. On success, a
nonnegative value is returned. On error, EOF is returned.
General Form:
fputs (str, fptr);
Reading a string from a file

 The function used is fgets(). Reads a line from the specified stream and
stores it into the string pointed to by str. It stops when (n-1) characters are read,
the newline character is read, or the end-of-file is reached, whichever comes first.
The newline character is copied to the string. A null character is appended to the
end of the string.
 On success, a pointer to the string is returned.
 On error, a null pointer is returned.
 If the end-of-file occurs before any characters have been read, the string
remains unchanged.
General Form:
fgets(str,n,fptr);
Numeric I/O
Using numeric I/O, integers can be written to, or read from, a file at a time.
Writing integer in to a file

 The function used is putw(). This function writes an integer to a file. On


success, a nonnegative value is returned. On error, EOF is returned.
General Form:
putw (i, fptr);

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 162
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Reading integer from a file

 The function used is getw(). Reads an integer from the file and assigns it
to the program defined numeric variable at the LHS.
General Form:
i = getw( fptr);
Formatted I/O
The formatted I/O functions can handle a group of data in a single call.
Writing formatted data to a file
 The function fprintf() is used. This function will write the values stored in
the variables into a file pointed by fptr, according to the format specifier specified
in format string.
 On success, the number of characters printed is returned.
 If an error occurred, -1 is returned.
General Form:
fprintf ( fptr, format-string, variable-list);

 The fprintf() function takes the format string specified by the format
argument and applies each following argument to the format specifiers in the
string, in a left to right fashion.
 Each character in the format string is copied to the stream except for
conversion characters which specify a format specifier.

Reading formatted data from the file


 The function used is fscanf().This function will read the formatted data
from the file pointed by fptr, as specified by the format specifiers in format-string
and stores in the variables, whose addresses are given in addresses-list.
 Reading an input field (designated with a conversion specifier) ends when
an incompatible character is met, or the width field is satisfied.
 On success, the number of input fields converted and stored is returned.
 If an input failure occurs, EOF is returned.
General Form:

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 163
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
fscanf( fptr, format-string, addresses-list);
 The fscanf() function takes input in a manner that is specified by the
format argument and stores each input field into the corresponding arguments, in
a left to right fashion.
 Each input field is specified in the format string with a conversion
specifier which specifies how the input is to be stored in the appropriate variable.
 Other characters in the format string specify characters that must be
matched from the input, but are not stored in any of the following arguments. If
the input does not match, the function stops scanning and returns.
 A white space character may match with any white space character such
as space, tab, carriage return, new line, vertical tab, or form feed, or the next
incompatible character.
Block I/O
Block I/O is used to read or write a specified number of bytes. The data handled by
block input/output function will be in ‘raw data format’ (i.e. bytes of data).
Writing in to a file
 The function used is fwrite().Transfers a specified number of bytes
beginning at a specified location in memory to a file.
 Used to write a structure or an array of structures to an output file.
 The function writes data from the array pointed to by ptr to the given
stream. It writes ‘n’ blocks of size ‘size’. The total number of bytes written is
(size*n).
 On success the number of elements written is returned.
 On error the total number of elements successfully written (which may be
zero) is returned.
General Form
fwrite (ptr, size, n, fp);
 ptr pointer to the data block (source)
 size size of each block (number of bytes to be written) n number of
blocks to be written
 fp file pointer (destination)

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 164
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
Reading from a file
 The function used is fread(). Reads data from the given stream into the
variable pointed to by ptr. It reads ‘n’ number of elements of size ‘size’.
 The total number of bytes read is (size*n).
 On success the number of elements read is returned.
 On error or end-of-file, the total number of elements successfully read
(which may be zero) is returned.
General Form
fread (&str, size, n, fp);
 &str destination memory address
 size size of each block (number of bytes to be read) n number of
blocks to be read
 fp file pointer (source)
5.10.6 Random Access to Files
The functions discussed earlier are to be used for reading and writing data
sequentially. In some applications, it may be necessary to access some part of the file
directly.
This can be achieved by using the functions fseek(), ftell() and rewind().
ftell()
 This function takes a file pointer and returns a long int, which corresponds
to the current file pointer position.
 If it is a binary stream, then the value is the number of bytes from the
beginning of the file.
 If it is a text stream, then the value is a value usable by the fseek()
function to return the file position to the current position.
 On success, the current file position is returned.
 On error, the value -1L is returned and error number (errno) is set.
General Form:
n = ftell(fptr);
fseek()

 This function sets the file position to the given offset (specified in long

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 165
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
integer format).
General Form:
fseek( fptr, offset, from_where)
 The argument offset signifies the number of bytes to seek from the given
‘from_where’ position. The argument from_where can be:

SEEK_SET Seeks from the beginning of the file 0

SEEK_CUR Seeks from the current position of 1


File pointer

SEEK_END Seeks from end of the file 2

 On a text stream, from_where should be SEEK_SET and offset should be


either zero or a value returned from ftell().
 The end-of-file indicator is reset. The error indicator is NOT reset.
 On success, zero is returned.
 On error, a nonzero value is returned.
Example
fseek (fp, 0L, 0); Move the file pointer to the beginning.

fseek (fp, 0L, 2); Move the file pointer to the end of file.

fseek (fp, 10L, 0); Move after 10 bytes from the beginning.

fseek (fp, 10L, 1); Move after 10 bytes from the current

fseek (fp, -10L, 1); Move backward 10 bytes from the current

fseek (fp, -10L, 2); Move backward 10 bytes from the EOF.

rewind()

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 166
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

 This function sets the file position to the beginning of the file of the given
stream. The error and end-of-file indicators are reset.
General Form:
rewind(fptr);
Sample Program:
Write a C program to copy contents of one file to another.
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp1,*fp2;
char ch;
fp1=fopen(“example.c”,"r");
fp2=fopen(“copy.c”,"w");
if(fp1==NULL||fp2==NULL)
{
printf("unable to open");
exit(0);
}
do
{
ch=fgetc(fp1);
fputc(ch,fp2);
}while(ch!=EOF);
fcloseall();
printf("\nFile copy operation performed successfully");
}

OUTPUT:

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 167
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
File copy operation performed successfully
//c program to demonstrate the usage of rewind()
void main()
{
FILE *fp;
clrscr();
fp=fopen("[Link]","r");
fseek(fp,8,0);
rewind(fp);
printf("\nThe file content is \n");
while(!feof(fp))
{
printf("%c",fgetc(fp));
printf("\n%c is stored at position %d",fgetc(fp),ftell(fp));
}

}
fclose(fp);
getch();
}
//c program to demonstrate the usage of ftell()
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
clrscr();
fp=fopen("[Link]","r");
printf("\nThe content of text file is");
while(!feof(fp))
{
printf("\n%c is stored at position %d",fgetc(fp),ftell(fp));

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 168
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
}
fclose(fp);
getch();
}
//c program to demonstrate fseek() method
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int n;
char ch;
clrscr();
fp=fopen("[Link]","r");
printf("\nEnter the number of charaters to skip");
scanf("%d",&n); //8
fseek(fp,n,SEEK_SET);
fseek(fp,-4,SEEK_CUR);//four positions backward
while(!feof(fp))// to print the file content
{
ch=fgetc(fp);
printf("%c",ch);
}
fclose(fp);
getch();
}
5.11 Problem Solving
5.11.1 Write a C program to find out GCD of given two numbers using recursion
#include<stdio.h>
int gcd(int a,int b);
void main()
{

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 169
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
int a, b, result;
printf("Enter the two numbers to find their GCD: ");
scanf("%d%d", &a, &b);
result = gcd(a, b);
printf("The GCD of %d and %d is %d.\n", a, b, result);
getch();
}
int gcd(int a,int b)
{
if(a==0)
return b;
else if(b==0)
return a;
else gcd(b, a%b);
}
5.11.2 Develop C program to access file using Random access methods.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("[Link]","r");//open a file for reading
printf("\nThe contents of the file first time:");
while(!feof(fp))
{
ch=fgetc(fp);
printf("%c",ch);
}
rewind(fp);
printf("\nThe contents of the file second time:");
while(!feof(fp)) //processing a file

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 170
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
{
ch=fgetc(fp);
printf("%c",ch);
}
fseek(fp,3,SEEK_CUR);
ch=getc(fp);
printf("\n char at %d location is %c",ftell(fp),ch);
fclose(fp);
getch();
}
5.11.3 Write a C program to swap two integers to illustrate Call by reference
mechanisms.

#include <stdio.h>
void swap(int *num1, int *num2);
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);

// Call the swap function, passing the addresses of a and b


swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
void swap(int *num1, int *num2) {
int temp;
temp = *num1;
*num1 = *num2;
*num2 = temp;

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 171
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
printf("Inside swap function: *num1 = %d, *num2 = %d\n", *num1,
*num2);
}
5.11.4 Write a C program to swap two integers to illustrate Call by value
mechanisms.
#include <stdio.h>
void swapByValue(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf("Inside swapByValue function: a = %d, b = %d\n", a, b);
}
int main() {
int num1 = 10;
int num2 = 20;
printf("Before calling swapByValue: num1 = %d, num2 = %d\n", num1,
num2);
swapByValue(num1, num2);

printf("After calling swapByValue: num1 = %d, num2 = %d\n",


num1, num2);

return 0;
}
Assignment-Cum-Tutorial Questions
Short Answer Questions

[Link] Question BL

1. Define a Function in C. L1

2. List the types of arguments in functions. L1

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 172
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem

3. Define Call by Value mechanism in functions. L1

4. Define Call by reference mechanism in functions. L1

5. Define Recursion. L1

6. Define file in C. List the types of files. L1

7. List the file opening modes in C. L1

8. Explain fopen() with proper syntax. L1

9. Explain ftell() with proper syntax. L1

10. Explain rewind() with proper syntax. L1

5.1 Introduction to Functions


Objective Questions
1. Which of the following is the correct way to declare a function in C? [ ]
a. function_name(return_type argument_type);
b. return_type function_name(argument_type);
c. return_type function_name(argument_type) {}
d. function_name return_type(argument_type);
2. What is the purpose of the return statement in a C function?
a) To declare the function.
b) To call the function.
c) To return a value from the function to the calling code.
d) To define the function.
Descriptive Questions

[Link] Questions BL

1 Explain the proper syntax of a function L2

2 Write a C program to find the average of n numbers using functions. L3

5.2 Function call return types


Objective Questions
3. Which of the following is a valid return type for a C function that does not
return any value?
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 173
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
A. int
B. float
C. void
D. char
4. A function in C can return:
A. Only one value.
B. Multiple values using pointers.
C. Multiple values using arrays.
D. Both B and C.
Descriptive Questions
[Link] Questions BL

Classify the functions with respect to function return calls. Explain each L3
1.
one in detail.

5.3 Types of arguments


Objective Questions
5. In C programming, what are the two main types of arguments used in function
calls?
a) Global arguments and Local arguments
b) Input arguments and Output arguments
c) Actual arguments and Formal arguments
d) Call-by-value arguments and Call-by-reference arguments
Descriptive Questions

[Link] Questions BL

1 Classify the types of arguments in C L3

5.4 Parameter passing techniques


Objective Questions
6. In call by value, what is passed to the function?
a) The memory address of the actual parameter.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 174
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
b) A copy of the value of the actual parameter.
c) A reference to the actual parameter.
d) The name of the actual parameter.
7. To achieve call by reference in C, which of the following is typically used?
a) Direct variable names.
b) Pointers.
c) Global variables.
d) Return values.
Descriptive Questions

[Link] Questions BL

1 Explain about Call by value mechanism in C. Write a C program to


L3
illustrate the Call by value mechanism.

2 Explain about Call by reference mechanism in C. Write a C program to


L3
illustrate the Call by reference mechanism.

5.5 Recursion
Objective Questions
8. A function that calls itself is known as a:
a) Self-calling function
b) Recursive function
c) Iterative function
d) Static function
Descriptive Questions

[Link] Questions BL

Explain the concept of recursion. Write a C program to find out GCD of L3


1
given two numbers using recursion. (10M)

5.6 Modifying parameters inside function using pointers


Objective Questions

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 175
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
9. Which of the following statements is true regarding modifying parameters
using pointers in C?
a) It allows a function to modify a local copy of the variable.
b) It is known as "call by value."
c) It enables a function to directly change the original variable passed from the
caller.
d) It creates a new variable within the function's scope.
10. In the context of modifying parameters using pointers, what does
the * operator signify when used within the function?
a) Address-of operator
b) Dereference operator
c) Multiplication operator
d) Bitwise AND operator

Descriptive Questions

[Link] Questions BL

1 L2
Explain how to modify parameters inside function using pointers

5.7 Array as parameter to the function


Objective Questions
11. When an array is passed as an argument to a function in C, what is actually
passed?
a) A copy of the entire array.
b) The base address (memory address of the first element) of the array.
c) The size of the array.
d) The value of the first element of the array.
Descriptive Questions

[Link] Questions BL

1 Explain how the Arrays can be passed as parameters to the function. L2

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 176
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
5.8 Scope and lifetime of variables: local and global variables
Objective Questions
12. Which of the following statements about local variables in C is true?
a) They can be accessed from any function in the program.
b) Their lifetime extends throughout the entire program execution.
c) They are declared inside a function or a block.
d) They are automatically initialized to zero.
13. What is the scope of a global variable in C?
a) Limited to the function in which it is declared.
b) Limited to the file in which it is declared.
c) Accessible from any function in the entire program after its declaration.
d) Limited to the block in which it is declared.
14. What is the lifetime of a global variable in C?
a) It exists only while the function in which it is used is executing.
b) It exists for the entire duration of the program's execution.
c) It is determined by the static keyword.
d) It is determined by the auto keyword.
Descriptive Questions

[Link] Questions BL

1 Explain about the scope and lifetime of local and global variables L2
in C

5.9 Storage classes: auto, static, extern and register


Objective Questions
15. Which storage class is the default for local variables declared inside a
function?
a) static
b) extern
c) auto
d) register
16. Which storage class allows a variable to retain its value between multiple
function calls?

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 177
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
a) auto
b) extern
c) static
d) register
17. Which storage class is used to declare a variable that is defined in another
source file?
a) auto
b) extern
c) static
d) register
18. Which storage class suggests to the compiler that a variable should be stored
in a CPU register for faster access, though the compiler may ignore this
suggestion?
a) auto
b) extern
c) static
d) register
19. What is the default initial value of a static variable if it is not explicitly
initialized?
a) Garbage value
b) 0
c) Null
d) Undefined
20. What is the scope of a variable declared with the extern storage class?
a) Local to the block
b) Local to the function
c) Global across multiple files
d) Global within a single file
Descriptive Questions

[Link] Questions BL

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 178
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1 Explain about the storage classes: auto, static, extern and register in detail.

5.10 File Handling


5.10.1 Definition of file
Objective Questions
21. In C, what does FILE refer to when handling files?
a) A keyword for representing files
b) A structure that holds information about an opened file
c) A stream for input/output operations
d) A buffered stream
22. Which of the following is the most accurate description of FILE *fp in C file
handling?
a) FILE is a keyword and fp is a variable of FILE type.
b) FILE is a structure, and fp is a pointer to a structure of FILE type.
c) FILE is a stream, and fp is a handle to that stream.
d) FILE is a data type, and fp is an instance of that data type.
Descriptive Questions

[Link] Questions BL

1 Explain the concept of file handling in C. L2

5.10.2 Types of files


Objective Questions
23. What are the types of files in C?
a) Binary file
b) Text file
c) Both Binary and Text files
d) None
Descriptive Questions

[Link] Questions BL

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 179
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
1 L2
List the types of files. Explain them in detail.
5.10.3 File opening modes
Objective Questions
24. Which mode opens a text file for writing, discarding previous contents if the
file exists, and creates the file if it doesn't exist?
a) "r"
b) "a"
c) "w"
d) "r+"
25. Question 2: Which mode opens an existing text file for only reading?
a) "w+"
b) "r"
c) "a+"
d) "rb"
26. What is the purpose of the 'b' character in file opening modes like "rb" or
"wb+"?
a) It indicates a "big" file.
b) It specifies binary mode.
c) It signifies a "buffered" operation.
d) It's used for "block" operations.
27. Which mode opens a text file for appending (writing at the end), and creates
the file if it doesn't exist?
a) "w"
b) "a"
c) "r"
d) "w+"
Descriptive Questions

[Link] Questions BL

1 L2
Explain the File opening modes in C.

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 180
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
5.10.4 Basic file Operations: open, read/write and close
28. What is the correct return type of the fopen() function in C?
a) char
b) int
c) void
d) FILE *
29. When opening a file using fopen(), if an error occurs, what value does it
typically return?
a) EOF
b) NULL
c) 0
d) Depends on the compiler
Descriptive Questions

[Link] Questions BL

1 Explain the basic file operations open, read/write and close with proper L2
syntax.
5.10.5 File I/O: fscanf(), fprintf(), fgets(), fputs(), fgetc(), fputc(), fread() and
fwrite()
Objective Questions
30. Which function is used to write formatted output to a file, similar to printf()?
a) fputs()
b) fprintf()
c) fwrite()
d) fputc()
31. To read a single character from a file, which function would you use?
a) fgets()
b) fread()
c) fgetc()
d) fscanf()
32. What is the primary purpose of fgets()?

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 181
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
a) To read a single character from a file.
b) To read a formatted string from a file.
c) To read a line (including the newline character) from a file.
d) To read a block of binary data from a file.
33. Which function is used to write a string to a file?
a) fprintf()
b) fputc()
c) fputs()
d) fwrite()
34. When working with binary files, which pair of functions is commonly used
for reading and writing blocks of data?
a) fscanf() and fprintf()
b) fgetc() and fputc()
c) fread() and fwrite()
d) fgets() and fputs()
35. What does fputc() return on success?
a) The character written.
b) The file pointer.
c) 0.
d) EOF.
Descriptive Questions

[Link] Questions BL

1 Explain the different types of File input and output (I/O) operations L2
fscanf(), fprintf(), fgets(), fputs(), fgetc(), fputc(), fread() and fwrite() in
detail
2 Write a C program to copy the content of one file to another file. L3

5.10.6 Random access files: fseek(), ftell(), rewind()


Objective Questions
36. Which function is used to set the file position indicator to a specific location
within a file?
a) ftell()
Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 182
R -23 INTRODUCTION TO PROGRAMMING I [Link]-I Sem
b) rewind()
c) fseek()
d) feof()
37. The ftell() function returns:
a) The size of the file in bytes.
b) The current position of the file pointer from the beginning of the file.
c) The number of characters read so far.
d) A pointer to the current file position.
38. What is the purpose of the rewind() function?
a) To move the file pointer to the end of the file.
b) To move the file pointer to the beginning of the file.
c) To close the file.
d) To check if the end of the file has been reached.
Descriptive Questions

[Link] Questions BL

1 Explain the methods of Random access in files fseek (), ftell (), rewind()
L2
with proper syntax. (10M)
List the random access methods of files in C. Develop C program to
2 L3
access file using Random access methods fseek(), ftell() and rewind().

Seshadri Rao Gudlavalleru Engineering College Dept. of ECE AS&A A. Y: 2025-26 Page 183

Common questions

Powered by AI

Understanding file I/O operations in C, such as fopen(), fclose(), fscanf(), fprintf(), getc(), putc(), and managing error handling, is essential for developing robust file handling in applications. This knowledge allows programmers to efficiently open, read, write, and close files, manage file states across different platforms, and ensure data is correctly stored and retrieved in varied formats, preventing data loss and ensuring application reliability .

Algorithmic complexity concepts such as Big Oh notation influence algorithm design by providing a theoretical framework to analyze the performance of algorithms in terms of time and space requirements. It helps developers predict scalability and efficiency under varying input sizes, guiding them to choose or design algorithms that deliver optimal performance, minimizing resource usage in real-world applications, which is critical for developing efficient software solutions .

Implicit type conversion occurs automatically when an operation involves two different types, such as promoting an integer to a float to perform an arithmetic operation, which could lead to loss of data precision if not managed correctly. Explicit type conversion, or casting, allows the programmer to specify the desired data type, giving more control over the changes and ensuring that conversions happen intentionally, which helps prevent unexpected outcomes and logical errors in a program .

Understanding the basic organization and components of a computer, such as the ALU, input-output units, memory, and program counter, is crucial in programming as it provides insights into how data is processed and executed. This knowledge allows programmers to write more efficient code, optimize resource usage, and understand the constraints and capabilities of hardware when developing software solutions .

The different modes of fopen() affect file access and modification by specifying operations allowed on files. Modes like 'r', 'w', 'a', and their binary equivalents (e.g., 'rb', 'wb') determine if a file is opened for reading, writing, or appending, and whether it operates in text or binary mode. These modes directly impact the file position indicator and how data can be read or written, thus dictating the flexibility and restrictions in file operations .

Arrays and pointers are crucial for memory management as they provide ways to handle dynamic storage and efficient access to memory. Arrays enable structured storage of data in contiguous memory locations, making it easier to manage data in bulk operations. Pointers, on the other hand, allow direct manipulation of memory addresses, providing the ability to allocate and deallocate memory dynamically, which is essential for addressing space and performance constraints in programs a .

De-referencing in pointer manipulation allows direct access to the value stored at a specific memory address pointed to by a pointer. This is particularly crucial in array operations, as pointers can traverse and modify array elements more efficiently than using array subscripts. It facilitates operations like dynamic memory allocation, boundary checks, and direct manipulation of aggregate data structures, which are essential for optimizing the performance and flexibility of array operations .

Effective problem-solving strategies in programming include the top-down approach, which involves breaking a problem into smaller, more manageable sub-problems and solving them one by one, and the bottom-up approach, which starts by solving smaller problems and integrating them to solve the larger problem. These strategies differ in their direction of decomposition and how they utilize abstraction and decomposition to manage complexity in software development .

Control structures such as selection statements (if, if-else, switch) and iteration statements (for, while, do-while) enhance the efficiency and readability of a C program by facilitating logical decision making and repeated execution of code blocks with minimal redundancy. They allow programmers to define clear paths for code execution based on given conditions and repetitive tasks, leading to more organized and understandable code .

Structures and unions are both used to group variables under one name. Structures allocate separate memory for each member, preserving all data between operations, whereas unions use a single shared memory space for all members, which can only hold one value at a time. This difference impacts storage by making structures suitable for organizing related data and unions optimal for conserving memory when only one value is needed at a time .

You might also like