100% found this document useful (1 vote)
410 views121 pages

Programming With Problem Solving

Programming for problem solving Notes prepared according to JNTUH syllabus

Uploaded by

stiwari.ace
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
100% found this document useful (1 vote)
410 views121 pages

Programming With Problem Solving

Programming for problem solving Notes prepared according to JNTUH syllabus

Uploaded by

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

PROGRAMMING FOR PROBLEM SOLVING

[R22A0501]
LECTURE NOTES

B.TECH I YEAR – I SEM(R22)


(2023-24)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

MALLA REDDY COLLEGE OF


ENGINEERING & TECHNOLOGY
(Autonomous Institution – UGC, Govt. of India)
Recognized under 2(f) and 12 (B) of UGC ACT 1956
(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified)
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India
Preface
C is a general-purpose programming language that is extremely popular, simple and
flexible. It is machine-independent, structured programming language which is used
extensively in various applications. C was the basic language to write everything from
operating systems (Windows and many others) to complex programs like the Oracle
database, Python interpreter and more.

It is said that 'C' is a god's programming language. One can say, C is a base for the
programming. If you know 'C,' you can easily grasp the knowledge of the other
programming languages that uses the concept of 'C'

'C' is a structured programming language in which program is divided into various


modules. Each module can be written separately and together it forms a single 'C' program.
This structure makes it easy for testing, maintaining and debugging processes.

This digital notes is designed to be a stand-alone introduction to C, even if you've never


programmed before. This notes has been organized to meet syllabi requirements of both
JNTUH and AICTE. It serves as an introductory material to first year students, enabling
them to understand basic concepts of C and updating them on the problem solving ability.

Organization of the book


The content has been divided into five units, as per the syllabus.

Unit I – Introduction to Computer System, Problem Solving with algorithms and flowcharts
Basics of C Language – Structure, Tokens, Data types, Operators, Expressions
Unit II –Control structures and Arrays
Unit III – Modular Programming using functions
Unit IV – Strings, Pointers and Dynamic Memory Management
Unit V – Structures, Unions and Files
We would like to extend our sincere gratitude to Dr. VSK Reddy, Director, Malla Reddy
College of Engineering and Technology (autonomous) and Dr. S. Srinivasa Rao, Principal,
Malla Reddy College of Engineering and Technology, under whose patronage we were able
to write this content. We are also indebted to Dr.S. Shanthi, Head of the Department,
Computer Science and Engineering for her constant support and motivation for our
academic growth. We would also like to acknowledge our colleagues who have provided
their valuable suggestions in preparing this content.
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY
PROGRAMMING FOR PROBLEM SOLVING
L T P C
3 1 - 3
COURSE OBJECTIVES:

The students will be able to

1. Understand the use of computer system in problem solving and to build program logic
with algorithms and flowcharts.
2. To learn the syntax and semantics of C Programming Language
3. To learn the usage of structured programming approach in solving problems
4. To learn the usage of strings and pointers
5. To understand the usage of structures and files.

UNIT - I:
Introduction to Programming:
Compilers, Compiling and executing a program, Representation of Algorithms and Flowcharts
with examples.
Introduction to C Programming Language: Structure of a C Program, I/O: Simple input and
output with scanf() and printf(), Keywords, Identifiers, Constants, Variables, Data types,
Operators, Expressions and precedence, Expression evaluation, Type conversion.

UNIT - II: Conditional Branching and Arrays


Control Structures: if and switch statements, nested if-else, Iteration and loops: use of while,
do-while and for loops, nested loops, use of goto, break and continue statements.
Arrays: one and two dimensional arrays, creating, accessing and manipulating elements of
arrays..

UNIT - III: Designing Structured Programs using Functions:


Functions: Declaring a function, Categories of functions, passing parameters to functions: call
by value, call by reference, Passing arrays to functions, Scope- Local Vs Global, Storage classes,
Recursion with example programs.

UNIT - IV: , Strings and Pointers


Strings: Introduction to strings, Declaration and Initialization, String input/output functions,
String manipulation functions with example programs, Array of Strings
Pointers: Defining pointers, Declaration and Initialization, accessing variables through pointers,
Pointers to arrays, Pointers to functions, Pointers to structures, Command line arguments,
Enumeration data type.
Dynamic memory allocation: Allocating and freeing memory (malloc(), calloc(), realloc() and
free().
UNIT - V: Structures and File Handling in C:
Structures: Defining structures, Declaration and Initialization, Array of structures, unions.
File Handling:
Text and Binary files, Opening and Closing files, File input /output functions, Creating and
Reading and writing text files, Appending data to existing files.

TEXT BOOKS:

1. Jeri R. Hanly and Elliot B.Koffman, Problem solving and Program Design in C 7th Edition,
Pearson.
2. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage Learning, (3rd
Edition).
3. E. Balagurusamy, Computer fundamentals and C, 2nd Edition, McGraw-Hill.

REFERENCE BOOKS:

1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall of
India.
2. Yashavant Kanetkar, Let Us C, 18th Edition, BPB.
3. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
4. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
5. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition.
6. Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill.

COURSE OUTCOMES:

At the end of the course the student will be able to

1.To write algorithms and to draw flowcharts for solving problems.


2. To convert the algorithms/flowcharts to C programs.
3. To code and test a given logic in the C programming language.
4. To decompose a problem into functions and to develop modular reusable code.
5. To use arrays, pointers, strings and structures to write C programs.
CONTENTS

PAGE
S.NO UNIT NAME
NUMBER
UNIT –I Introduction to Problem Solving, Basics of C 6-47

UNIT –II Control Structures and Arrays 48-71

UNIT –III Designing structured programs using Functions 72-91

UNIT –IV Strings and Pointers 92-104

UNIT –V Structures, Unions and Files 105-116


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Introduction to Problem Solving

The computer allows us to do tasks more efficiently, quickly, and accurately than we could by hand. In
order for this powerful machine to be a useful tool, it must be programmed. That is, we must specify what
we want done and how. We do this through programming.

A computer is not intelligent. It cannot analyze a problem and come up with a solution. A human (the
programmer) must analyze the problem, develop the instructions for solving the problem, and then
have the computer carry out the instructions.

Once we have written a solution for the computer, the computer can repeat the solution very quickly
and consistently, again and again. The computer frees people from repetitive and boring tasks.

Steps in developing a solution


Before starting to think about writing any programming code, we must first focus on the problem
statement, that is, on the real-world domain. First we must understand the problem and then we try
solving it. Once we think we have solved it we systematize our solution by writing it out in a more formal
way as a series of steps (an algorithm) that can be followed by another person.

Problem solving requires thinking about the problem at a high level of abstraction while writing
programming language code requires a very low level of abstraction

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 1


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

To write a program for a computer to follow, we must go through a two-phase process: problem solving
and implementation

Problem-Solving Phase
1. Analysis and Specification: Understand (define) the problem and what the solution mustdo.
2. General Solution (Algorithm): Specify the required data and the logical sequences of steps that
solve theproblem.
3. Verify: Follow the steps exactly to see if the solution really does solve theproblem.

Implementation Phase
1. Concrete Solution (Program): Translate the algorithm (the general solution) into a
programminglanguage.
2. Test: Have the computer follow the instructions. Then manually check the results. If you find
errors, analyze the program and the algorithm to determine the source of the errors, and then
makecorrections.

Once a program has been written, it enters a third phase: maintenance.


Maintenance Phase
1. Use: Use theprogram.
2. Maintain: Modify the program to meet changing requirements or to correct any
errors that show up while usingit.

The programmer begins the programming process by analyzing the problem, breaking it into
manageable pieces, and developing a general solution for each piece called an algorithm. The
solutions to the pieces are collected together to form a program that solves the original
problem.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 2


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

INTRODUCTION TO COMPUTING

Computer systems

Computer is a digital electronic device which understands only 0’s and 1’s. It performs
all arithmetic calculations (Addition, multiplication...) and non arithmetic calculations (copy,
choose, move, compare….).
A computer is a system made of two components: Hardware and Software
The computer hardware is the physical equipment. The software is the collection of
programs (instructions) that allow the hardware to do its job. The computer manipulates these
symbols in the desired way by following an intellectual map called program. A program is a
detail set of humanly prepared instructions that directs the computer to
functioninaspecificwaytoproducethedesiredresults.Computerintelligencequotientor
I.Q is zero. It does not have any thinking, arguing or decision-taking power of its own. This
power is intelligently conferred to it by proper programming methods by persons handling it.

Computer Hardware:

The hardware component of the computer system consists of five parts:

1. Inputdevices
2. Central processing unit(CPU)
3. Primary (Main) storage or Immediate Access memory Storage(I.A.S)
4. Outputdevices
5. Auxiliary storage devices or secondary memory or backing storage devices (floppy disk, tape...)

The input device is usually a keyboard where programs and data are entered into the
computer. Examples of the other input devices include a mouse, a pen, or stylus, a touch
screen, or an audio input unit.

The central processing unit (CPU) is responsible for executing instruction such as
arithmetic calculations, comparisons among data, and movement of data inside the system.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 3


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Primary storage is a place where the programs and data are stored are erased when we
turn off a personal computer or when we log off from a time-sharing computer.

The output device is usually a monitor or a printer to show output. If the output is
shown on the monitor, we say we have a soft copy. If a printed on the printer, we say we have
a hard copy.

Auxiliary storage is used for both input and output. It is a place where the programs and
data are stored permanently. When we turn off the computer, our programs and data remain
in the secondary storage, ready for the next time we need them.

Computer Software:

Computer software is divided into two categories: system software and application
software. System software manages the computer resources. It provides the interface between
the hardware and the users but does nothing to directly serve the users need. Application
software is a directly responsible for helping users solves their problem.

System Software:

System software consists of programs that manages the hardware resources of a computer and
perform required information processing tasks. These programs are divided into three classes:
the operating system, system support, and system development.

The operating system provides services such as a user interface, file and database access, and
interface to communication systems such as internet protocols.

System support software provides system utilities and other operating services.

System development software includes the language translators that convert programs into
machine language for execution, debugging tools to ensure that the programs are errorfree.

Application software:

These are divided into two classes: General-purpose software and Application-specific
software

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 4


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

General-purpose software is purchased from a software developer and can be used for more
than one application. Examples like word processor, database managementsystems.

Application-specific software can be used only for its intended purpose. A general ledger
system used by accountants and a material requirements planning system used by a
manufacturing organization are examples.

USER

Figure: Relationship between System software and Application software

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 5


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

UNIT-I
Topics Covered

Introduction to Computing – Compilers- Compiling and executing a progam.


Representation of Algorithms and Flowcharts
Introduction to C – History of C, Features of C, Structure of C Program, Character Set,
Simple Input/Output with scanf() and printf().
C Tokens - keywords, Identifiers, Constants, Data types, Variables. Operators,
Expressions, Precedence and Associativity, Expression Evaluation, Type
conversion

Computer languages

Low Level Language: The only programming language available was machine languages. Each
computer has its own machine language which is made of streams of 0’s and 1’s. The only
language understood by computer hardware is machinelanguage.

1. Middle Level Language: The programs are written using the instructions of CPU is called
Assembly level language. It uses symbols, or mnemonics, to represent the various
machine language instructions. Examples are TASM,MASM

2. High Level Language: In the Assembly level language programmers need to concentrate
on the hardware so it is tedious because each machine instruction had to be individually
coded. So the High level language was developed it is English like language where
instruction typically translates into machine languageinstructions.

Creating and Running Programs

The procedure for turning a program written in C into machine language. These steps
are repeated many times during development to correct errors and make improvements to
thecode.

Writing and Editing Programs:

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 6


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

The software used to write programs is known as text editor. A text editor helps us
enter, change, and store character data. Depending on the editor on our system, we could use
it to write letters write programs.

The main difference between the text processing and program writing is that program are
written using lines of code, while most text processing is done with characters and lines. After
complete a program, we save our file to disk. This file will be input to the compiler; it is known
as a sourcefile.

Compiling Programs:

The code in a source file stored on the disk must be translated into machine language. This is
the job of the compiler. The C compiler is actually two separate programs: The Preprocessor
and thetranslator

The preprocessor reads the source code and prepares it for translator. While preparing the
code, it scans for special instruction known as preprocessor commands. These commands tell
the preprocessor to look for the special code libraries, make substitutions in the code, and in
other ways prepare the code for translation with machine language. The result of
preprocessing is called the translation unit. After the preprocessor has prepared the code for
compilation the translator does the actual work of converting the program into machine
language. An object module is the coding machinelanguage.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 7


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Figure: Building a C Program


Linking Programs:

As we will see late, a C Program is made up of many functions. We write some of these
functions, and they are a part of our source program. However, there are other functions, such
as input/output process and mathematical library functions that exists else where and must be
attached to our program. The linker all of these functions, ours and system’s, into pour final
executable programs.

Executing Programs:
Once our program has been linked, it is ready for execution. To execute a program, we use an
operating system command, such as run, to load the program into primary memory and
execute it. Getting the program into memory is the function of an operating system program
known as the loader. It locates the executable program and reads it into memory. When

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 8


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

everything is loaded, the program takes control and it begins execution. In today’s integrated
development environment, these steps are combined under one mouse click or pull-down
windows.
In typical program execution, the program reads data from processing, either from the user or
from a file. After the program process the data, it prepares the output. Data output can be to
the user monitor or to file. When the program has finished its job, it tells the operating system,
which then removes the program from the memory.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 9


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Algorithms

An algorithm is a step-by-step procedure for solving a problem using pseudocode. The


Pseudocode we present here is particularly useful for developing algorithm that will be
converted to structured C programs.

Features of an algorithm:

Finiteness :An algorithm terminates after a fixed number ofsteps.

Definiteness :Each step of the algorithm is precisely defined.

Effectiveness :All the operations used in the algorithm can be performed exactly in a fixed duration
time.

Input : An algorithm has certain precise inputs before the execution of the algorithm begins.
Output : An algorithm has one or moreoutputs

Pseudo code

Pseudo code is similar to everyday English; Pseudo code is an artificial and informal language
that helps programmers develops algorithms. It is convenient and user-friendly although it is
not an actual computer programming language. Pseudo code programs are not actually
executed on computers. Rather, they merely help the programmers “think out” a program
before attempting to write it in a programming language such asC.

Steps to follow in writing pseudo code:

 Mimic good code and good English. Variable names should be mnemonic, include
comments where it is useful.
 Ignore unnecessary details. Use some convention to group statements.(begin/end,
brackets).
 Take advantage of programming short hands. Using if-else or looping structures is more
concise.
 Consider thecontext.
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 10
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Example 1: An algorithm /Pseudo code to add two numbers.


Step1: start

Step2: Read the two numbers into a,b


Step3: c = a +b

Step4: write/print c

Step5: stop

Example 2: An algorithm /Pseudo code to find whether a given number is odd number or a even
number.

Step1: Start
Step2: Read the numbern
Step3: If (n % 2) = 0 then
write n is even number Go to step 5
Step4: write n is odd number
Step5: Stop

Flow Chart

A flow is a graphical representation of an algorithm or a portion of an algorithm. Flowcharts are


drawn using certain special-purpose symbols such as rectangles, diamonds, ovals, and small
circles as shown below. These symbols are connected by arrows called flowlines. Like pseudo
code, flowchart is useful for developing and representing algorithms, although, pseudo code is
performed by most programmers. Flowcharts clearly visually show how control structures
operate in a program. The most common symbols used in drawing flow charts.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 11


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Example 1: Flowchart for addition of two numbers.


Start

Read a, b

c= a + b

Write c
c cc

Stop

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 12


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Example 2: Flowchart to find whether a given number is odd or even.

INTRODUCTION TO C LANGUAGE
History of C
C is a structured programming language. It is considered a high-level language because it allows the
programmers to concentrate on the problem at hand and not worry about the machine that the
program will be using. C, like modern languages, is derived from ALGOL. The first language to use a
block structure. ALGOL is used in Europe but not in America this leads to the development of
Structured programming languages. In 1967, Martin Richards developed a language called Basic
Combined Programming Language, or BCPL. Ken Thompson followed in 1970 with similar language he
simply called B. B was used to developed the first version of the UNIX, one of the popular network
operating system in use today. Finally, Dennis M. Ritchie developed C, which took many concepts from
ALGOL, BCPL, and B and added the concept of data types.
The history of ‘C’ started in 1972 by the BELL Laboratories, USA., where Dennis
M.Ritchie proposed this language. The growing popularity of ‘C’, the changes in the language
over the years and the creation of compilers by groups not involved in its design, combined to
demonstrate a need for a more precise and more contemporary definition of the language. In
1983, the American National Standards Institute (ANSI) established a committee whose goal

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 13


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

was to produce “An unambiguous and machine- independent definition of the language C”. The
result is the ANSI standard for C.

Structure of a C Program: Every C program contains a number of several building blocks known
as functions. Each function of it performs task independently. A function is subroutine that may
consists one or more statements.

Example of a simple C program:

line 1 /* Program Listing welcome.c A simple programin‘C’*/


line 2 #include<stdio.h>
line 3 main()
line 4 {
line 5 printf (“ Welcome to Cprogramming\n”);
line 6 } /*End of main()*/
Output: Welcome to C Programming

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 14


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Documentation section:

To enhance the readability of the program, programmers can provide comments about the
program in this section. Comments can be used any where in the program but too many
comments are avoided. It is useful for documentation. This gives the clarity of the program can
be followed if it is properly documented. The comments can be inserted with a single
statement or in nested statements.

Examples
// This is a single comment
/*This is a example of

nested comments */

From above example: line 1

/* Program Listing welcome.c A simple program in ‘C’*/

Link Section or Header file section: C program depends upon some header files for function
definition that are used in program. A header file contains the information required by the
compiler when calls to the library functions used in the program occur during compilation. Each
header file by default is extended with .h. The file should be included using #include directive.

Example: line 2

#include<stdio.h> or #include “stdio.h”

In this example <stdio.h> file is included i.e. all the definitions and prototypes of functions
defined in this file are available in the current program. This file is compiled with original
program.

Definition section: Definition section defines all symbolic constants

Ex: # define A 10.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 15


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Global declaration section: This section declares some variables that are used in more than one
function. These variables are known as global variables. These must be declared outside of all
the functions.

Main program section: Every program written in C language must contain main() function.
Empty parenthesis after main is necessary. The function main() is starting point of every ‘C’
program. The execution of the program always begins with the function main(). Except the
main () function, other sections may not be necessary. The program execution starts with the
opening brace ‘ { ‘ and ends with the closing brace ‘ } ‘. Between these two braces the
programmer should declare the declaration part and the executable part.
 Declaration Part: the declaration part declares the entire variables that are used in executable
part. The initialization of variables also done here. The initialization means providing the initial
value to thevariables

 Executable Part: This part contains the statements following the declaration of the variables.
This part contains a set of statements. These statements are enclosed between thebraces.

Examples: line 3, line 4, line 5, line 6


User-defined function: The function defined by the user is called user defined function. These
functions are generally defined after the main() function. They can also be defined before
main() function. This portion in not compulsory.

Features of ‘C’ language

1. Modularity
2. Extendability
3. Portability
4. Efficiency and Speed
5. Flexibility

Modularity: Ability to break down large modules into a manageable sub modules. It is one of
the important features of the structured programming languages. C is a structured
programming language.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 16


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Extendability: Ability to extend an existing software by adding new features is called


extendabiltiy. New features in the form of functions can be added to C language as it supports
modularity.

Portability: Ability to port (install) existing software in different platforms (Unix, Windos etc.) is
called portability. It means that the programs written on one machine can be executed on
different machine with or without minor changes in the program. C programs can be executed
on many machines with little or no change.

Efficiency and speed: C language has rich set of data types and operators making the language
more efficient and fast. The language provides some operators example: increment and
decrement operators) which speed up the execution to large extent. Further, it also provides
user defined data types (example: structures) through which miscellaneous data can be easily
manipulated.

Middle Level Languague: Though C is a high level language often it is called as middle level
language because programs written in c language run at the speeds matching to that of the
programs written in assembly level language. Due to this reason C language is widely used in
developing system software.

Flexibility: ASCII C complier has only 32 keywords. These are the basic building blocks of the
programming language. C is also called as programmers’ language. With 32 keywords a
programmer is able to solve any type of task due to this reason programmers have the
complete control over the language their by gaining the flexibility.

C Tokens:
In a Passage of text, individual words and punctuation marks are called as tokens. In a C
program, the smallest individual units are known as C tokens. The following are different
categories of C tokens.
1) Keywords 2) Identifiers 3) Constants 4) Operators

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 17


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Keywords:
Keywords are also known as reserve words. These keywords are only to be used for their
intended purpose and as identifiers. All the Keywords are lowercase.
Example: auto, char, int, long, goto, return, register…etc
Note: The keywords with at least one uppercase letter can be used as an identifier.

Identifiers:
Identifier allows us to name data and other objects in the program. Different programming
languages use different syntactical rules to form identifiers. In C, the rules for identifiers are
very simple. The only valid names symbols are the capital letter A through Z, the lowercase
letters a through z, the digits 0 and 9, and the underscore. The first character of the identifiers
cannot be a digit. The last rule is that the name we create cannot be keywords. C allows names
to be up to 63 characters long.

Rules of identifiers

1. An identifier must start with a letter or underscore: it may not have a space or a hypen,
or any other special symbol.

2. C is a case-sensitive language - it treats uppercase and lowercase letters distinctly

Variables

A variable is a place holder that occupies some part of the memory which can initialize or
assigned or changed during the execution of the program.

Declaration of variables

Syntax: datatype variable _name(s);

Example: float price;

Here price is a variable which hold a float value.

Initialization of variable

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 18


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Syntax: data type variable_name(s) = value;

Example: int x=5;

Here x is a variable which holds a value=5;

Rules & conventions for naming the variables:

1. Variable should always be declared at the beginning of the functions.


2. A variable name should begin with alphabet or underscore. And the remaining character
can be alphabets digits or underscore.
3. A variable name can’t exceed 31 characters
4. Special characters are not allowed with in the variable name including spaces. Expect
underscore.
5. Keywords cannot be used as variablenames

Conventions
1. Declare variable names in lowercaseletters
2. Variables names should provide a hint on what it is going to hold.

Examples of valid and invalid variables:

Valid variables Invalid variables


int a2; float 1a;
int _a1; int a b c;
double a_b_c; int abc$;
double $abc;

Note: Uninitialized variables contain junk or garbage values.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 19


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Constants A constant is a value that doesn’t change during the execution of a program. These
are generally declared before main function.

Constants

Numeric constants String constant Character constant

Integer constant Real constant

Integer constant: Numeric value without decimal part is called integer constant.
Example: 5, -66

Real constant: Numeric value with decimal part is called as real constant. The precision of a real
value indicates number of digits after decimal point. Example: 5.0, - 98.76…

Character constant: A single character enclosed in single quotes is called as character constant.

Character Set
Alphabet:a-z A-Z
Digits: 0-9
Special characters: $, ?, ; , , …..

Example: ‘a’, ‘5’,

Declaration of a constant

Syntax: const data type constant_name= value;

Example: const float PI=3.14159;

Note: In an 8 bit character set, a character occupies 1 byte, whereas in 16 bit character set, a
character occupies 2 bytes. Character constants have integer values known as ASCII values
(ASCII-American Standard code for Information Interchange).Since each character represents
an integer value, it is also possible to perform arithmetic operations on character constants.
Spacebar is also a character constant.

String constant: A single character or a group of characters enclosed in double quotes is called
string constant.
Example: “5” , “temperature”

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 20


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Note: Character constant occupies 1 byte where as string constant occupies 2 bytes.

Backslash Character constants: C supports some special backslash character constants that are used in
output functions. These are also known as escape sequences.

‘\a’-audible alert(bell) ‘\v’- vertical tab

‘\b’-back space. ‘\’’- single quote.

‘\f’-form feed ‘\”’- double quote.

‘\n’-newline ‘\?’- question mark

‘\r’-carriage return ‘\0’-Null

Data Types

A data type consists of the values it represents and the operations defined upon it. The C
language has defined a set of data types that can be divided into four general categories: void,
integral, floating-point, and derived as shown below

Figure: Data Types

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 21


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Void type:
The void type, designated by the keyword void, has no values and no operations, although
having no values and operations might seem unusual. It can also be used to define that a
function has no return value.

Integral type
The C language has three integral types: Boolean, character, and integer. Integral types cannot
contain a fraction part; they are whole numbers.

 Boolean: Boolean type can represent only two values: true or false. C used integers to
represent the Boolean values: a nonzero number (Positive or negative) was used to
represent true, and zero was used to represent false. The Boolean type, which is
referred to the keyword bool, is stored in memory as 0(false) or1(true).

 Character: A character is any value that can be represented in the computer’s alphabet,
or as it is better known, its character set. An 8-bit character set represent up to
256characters.

 Integer: An integer type is a number without a fraction part. C supports four different
sizes of the integer datatypes:

 Floating-Point Types The C standard recognizes three floating –point types: real,
imaginary, andcomplex.

 Real: The real type holds values that consist of an integral and a fractional part. The C
language supports three different sizes of real types: float, double, and long double.

 Imaginary type: An imaginary number is used extensively in mathematics and


engineering. An imaginary number is a real number multiplied by the square root of-
1. Most C implementations do not support the imaginary type.

 Complex: Complex number is a combination of real and imaginary number.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 22


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

STORAGE SIZE IN BYTES RANGE


FORMAT
DATA TYPE 16 bit 32 bit
SPECIFIER
Compiler Compiler 16 bit 32 bit
-32768 -32768
short int
To To
or 2 2 %hd
32767 32767
signed short int
(-215 to +215 -1) (-215 to +215 -1)
short int
0 to 65535 0 to 65535
or 2 2 %hu
(0 to +216 -1) (0 to +216 -1)
signed short int
-32768 -2,147,843,648
signed int %d
To to
or 2 4 or
32767 2,147,843,647
int %i
(-215 to +215 -1) (-231 to+231-1)
unsigned int 0 to 65535 0 to 4,294,967,295
2 4 %u
(0 to +216 -1) (0 to232-1 )
long int -2,147,843,648 -2,147,843,648
or to to
4 4 %ld
signed long int 2,147,843,647 2,147,843,647
(-231 to+231-1) (-231 to+231-1)
unsigned long int 0 to 4,294,967,295 0 to 4,294,967,295
4 4 %lu
(0 to232-1 ) (0 to232-1 )
-
long longint 922337203685477580
or 8
Not
signed longlong 8 -------- To %Ld
supported
int 922337203685477580
7
(-263 to +263-1)
char or signed -128 to127 -128 to 127
1 1 7 7 7 %c
char (-27to 2 1)
- (-2 to 2 -1)
Unsigned signed 8 8
1 1 0 to 256 (0 to 2 -1) 0 to 256 (0 to 2 -1) %c
char

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 23


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Derived data types:


Derived datatypes are used in ‘C’ to store a set of data values. Arrays, Structures, Union
and pointer are examples for derived data types.

User-defined data types:


The data types defined by the user are known as the user-defined data types. C provides two
identifiers typedef and enum to create new data typenames
typedef:
It allows the user to define an identifier that would represent an existing data type.
The user-defined data type identifier can later be used to declare variables.
Syntax: typedef type identifier;
For Example, the declaration,
typedef int Integer;
makes the name Integer a synonym of int. Now the type Integer can be used in declarations
,type castings,etc like
Integer num1, num2;
Which will be treated by the C compiler as the declaration of num1, num2 as int variables.
“typedef” is more useful with structures and pointers.

Operators:
Operators are C tokens which can join together individual constants, variables, array elements
and functions references. Operators act upon data items called operators.
C operators are classified into following categories:
1. Arithmeticoperators
2. Relationaloperators
3. Logicaloperators
4. Assignmentoperators
5. Increment and decrementoperators
6. Conditionaloperators
7. Bitwiseoperators
8. Specialoperators

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 24


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Arithmetic operators:

Arithmetic operators Meaning

Addition or unary plus


+

Subtraction or unary minus


-

Multiplication
*
/ Division
% Modulo division

 For arithmetic operations, operands must be numericvalues.


 Here modulo division produces remainder of integerdivision
Arithmetic operations are classifiedas
 Integerarithmetic
 Realarithmetic
 Mixed modearithmetic

Integer arithmetic: Both the operands are integer in an integer arithmetic. It always yields an
integer value.
Example: a+b, a-b

Real arithmetic: Both the operands are real in real arithmetic. It yields real value as result. It cannot
be applied to % operator.
Example:
float a=20.0, b= 3.0
a+b= 20.0+3.0=23.000000
a/b=20.0/3.0=6.6666667
a%b=20.0%3.0(invalid expression)
Mixed mode arithmetic: when one is integer and other is real it is known as mixed mode arithmetic.
Here, result will always be real.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 25


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Example:
int a=20.0, b=3;
a+b= 20.0+3=23.0
a/b=20.0/3=6.666667
a%b=20.0%3 (invalid expression)

Relational operators: These operators compare two quantities and depending on their
relation the result will be either true or false

Relational operators Action

< Is less than


<= Is less than or equal to
> Is grater than
>= Is grater than or equal to
== Is equal to
!= Is not equal to

Example

1) 38<4 - result of this operation is 0 (false)


2) 38>4 – result of this operation is 1 (true)

Logical operators:

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 26


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Logical operators Action

&& Logical AND

|| Logical OR

! Logical NOT

Logical expression combines two or more relational expressions.


Logical operators are used to test more than one condition and make decision.
Logical AND: The result of the logical AND expression will be true only when the relational
expressions are true.

Syntax: Exp1 && Exp2

Example: if a=10, b=5, c=15

1. i = (a>b)&&(b<c); The value of i in this expression will be 1.

2. i = (a<b)&&(b<c); The value of i in this expression will be 0.


Logical OR: The result of logical OR expression will be true only when both the relational expressions
are false.

Syntax: Exp1||Exp2 Example:

if a=10, b=5, c=15

1. i = (a<b)||(b<c); The value of i in this expression will be1.

2. i = (a<b)||(b>c); The value of i in this expression will be0.

Logical NOT: the result of the expression will be true, if the expression is false and vice versa.

Syntax: !Exp2

Example: x=20

I = !(x==20) The value of i will be 0. This is because x==20 is true(value1).

Assignment operators:

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 27


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

The operators are used to assign result of an expression to a variable.

Syntax: variable op=exp; OR variable=variable op exp;

Example:

1. a=a+10; or a+=10; adds 10 to a and assigns the value toa.

2. a=a*(b+5) or a*=b+5 multiplies b+5 with a and assigns result toa

Increment and Decrement operators:


These operators are represented as ‘++’ and ‘--’. ‘++’ increments operand by 1 and ‘--’
decrements operand by 1. They are unary operators and take the following form.

Examples:
1. int a=9;
y=++a; The value of y will be 10;
2. int a=9;
y=a++; The value of y will be 9;

Operator Action

a++ Post-increment

++a Pre-increment

a-- Post-decrement

--a Pre-decrement

Conditional operator: It is also known as ternary operator.


Syntax: Exp1 ? Exp2 : Exp3; where exp1,exp2,exp3 are expressions.
Example:
int a=5,b=10,c=15;
y = (a>b) ? b : c;

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 28


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

In the above statement, the expression a>b is evaluated since; it is false value of c will be
assigned to y. so value of y will be 15.

Bitwise operators:

Bitwise operators are similar to that of logical operators except that they work on binary bits.
When bitwise operators are used with variables, they are internally converted to binary
numbers and then bitwise operators are applied on individual bits. Bitwise operators do
manipulation on bits stored in memory. These operators work with char and int data types.
They cannot be used with floating point numbers.

Bitwise operators Action

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< Shift left

>> Shift right

~ (unary) Ones complement

Example: if a=4, b=6;


The equivalent binary value of a is 0000 0100
The equivalent binary value of b is 0000 0110

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 29


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

a) The value of a&b = 0 0 0 0 0 1 0 0


b) The value of a|b= 0 0 0 0 0 1 1 0
c) The value of a^b = 0 0 0 0 0 1 0 1
d) a<<2. It left shifts the binary bits twice. Therefore a= 0 0 0 1 0 0 0 0
e) a>>2. It right shifts the binary bits twice. Therefore a = 0 0 0 0 0 0 0 1
f) ~a. Unary operator which performs logical negation on each bit, 0’s will be converted to
1’s and 1’s to 0’s. Therefore a will become 1 1 1 1 1 0 1 1

Special operators:

There are some special operators available in C such as,

 Comma operator

 Sizeof operator

 Member selection operators ( . and ->)

Comma operator: The comma operator ‘, ’ has the lowest priority among all the operators
available in C. This operator is used to separate the related expressions. The expressions
separated by comma operator need not be included within the parenthesis.

Example: c= (a=5, b=10, a+b);


This expression first assign 5 to a, then assigns 10 to b and finally (5+10) to c.

Sizeof operator: It returns number of bytes the operand occupies. Operand may be a variable,
a constant, or a data type qualifier.

Syntax: sizeof (operand);

Example: y= sizeof (int); here value of y will be 2 bytes

Member operators: These are used to access members of structures and unions.
Example:
Var.member1; // when var is a structure variable.
Var->members2; // when var is a pointer to structure variable.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 30


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Points to be remembered on operators:

 Unary operator: It requires only one operand.


 Binary operator: It requires two operands like a+b, a-b, a*c etc.
 Logical operator: Used to compare two or more operands. Operands may be variable
constants orexpression.
 Assignment operator: Used to combine the results of two or morestatements.
 Conditional operator: Checks the condition and executes the statement depending on
thecondition.
 Bitwise operator: Used to manipulate the data at bit level. It operates on integer only. It
may not be applied to float orreal.

Input/output Functions
Input and output operations on data can be done by using input and output functions. An
input function reads data from keyboard and stores in the variable whereas output function
prints value in the variable on the screen

These functions are classified into two categories.


1. Formatted input/outputfunctions(I/O)
2. Unformatted input/outputfunctions(I/O)

FORMATTED I/O FUNCTIONS


•Formatted functions read and write all types of data values. format specifier are used to
identify the data type to read or written into variables.
Formatted Input function:

Formatted input function accepts an input data that has been arranged in a particular format
through keyboard.

scanf() is the formatted input function

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 31


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

The general form or syntax of the scanf( ) is


scanf("format specifier",&variable);
scanf function consists of two parts.
first part in scanf function is format specifier enclosed within double quotes.
format specifier is used to specify the type of format accepted by the scanf to the specified
variable. format specifier starts with "%" followed on or twocharacters
ex:
%d is for accepting signed integers
Second part in scanf () is list of variables. All variables are preceded with an ampersand(&)
symbol. ampersand is address operator which directs scanf() to store read value at the memory
address of the variable.
format string(Control string): Group of format specifiers are called as format string or control
string. if scanf() has to read multiple values from keyboard then all format specifiers are
grouped to form format string as show below
ex: scanf("%d%%d%d",&v1,&v2,&v3);
The above example reads three integers one by one from keyboard into variable v1,v2,v3
respectively

Formatted Output function: This prints data on the console(output screen).


printf() is the formatted output function.
printf ( ): This function prints all type of data values to the console.
it consists of two sections. first section contains format string and next part contains list for
corresponding variables for specified format string.
Syntax: printf(“format string”,arg1,arg2….argn);
The control string consists of
• Characters that will be printed on the screen as theyappear.
• Format specifiers that define the output format for display each dataitem.
• Escape sequence characters such as \t, \n, \betc.

arg1,arg2…..argn are the list of variables whose values are to be printed onto the screen

Note: The arguments should match in number, order and type with the format specifications.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 32


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Output of Integer Numbers:

List of format specifiers

Format specifier Data type


%hd signed short int Or short int or short
%hu unsigned short int
%d or %i signed int Or int
%u unsigned int
%ld long int or signed long int
%lu unsigned long int
%Ld long long int Or signed long int
%Lu unsigned long long int
%o or %O octal integer
%x or %X Hexa decimal integer
%c char
%f float
%lf double
%Lf long double
%s String(group of characters)
%e Print float value in exponential form.
%g Print using %e or %f whichever is smaller
%e Print float value in exponential form

The format specifier can also contain sub-specifiers: flags, width, .precision and code

% FLAG WIDTH Precision SIZE CODE


MODIFIER

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 33


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

flags Description

Left-justify within the given field width; Right justification is the default (see width sub-
-
specifier).

Forces to preceed the result with a plus or minus sign (+ or -) even for positive
+
numbers. By default, only negative numbers are preceded with a - sign.

width Description

Minimum number of characters to be printed. If the value to be printed is shorter


(number) than this number, the result is padded with blank spaces. The value is not
truncated even if the result is larger.

.precision Description

Separates the fractional part.


.
If the period is specified without an explicit value for precision, 0 is assumed.

Size Allocates no. of positions for fractional part

CODE using conversion symbol for data type


Ex: Output of the number 1234.
#include<stdio.h>

int main ( )

printf("\n%d",1234); //Without field width


printf("\n%6d",1234); // Right alignment
printf("\n%-6d ",1234); //Left alignment
printf("\n%012d",1234); //Padding with Zero

printf("\n%2d",1234); //Overriding the field width value.

return 0;

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 34


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

For floating point number:


The output of a real number may be displayed in two ways:
1. Decimal Notation ex: 2.345, 0.000005, -2.8976, 3456.987etc.
2. Exponential Notation Output of Real Number in decimal notation:%w.pf
Here both w and p are integers.

The integer w indicates the minimum number of positions that are to be used for display of the
value.The integer p indicates the number of digits to be displayed after decimal point
(precision). The value when displayed is rounded to p decimal places & printed right-justified in

#include<stdio.h>
int main()
{
float y= 98.7654;
printf("\n %f", y);
printf("\n%7.4f",y);
printf("\n%7.2f",y);
printf("\n%-7.2f",y);
return 0;
}

Printing of a single character:


The format specification for printing a character is:
#include<stdio.h>
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 35
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

int main()
{
printf(“%c”,’S’);
printf(“\n%3c”,’S’);
printf(“\n%6c”,’S’);
return 0;
}

S
S
S

UNFORMATTED IO FUNCTIONS

INPUT FUNCTIONS
1. getch()

2. getche()

3. getchar()
4. gets()
1. getch():- reads a character from keyboard and it does not require pressing of enterkey after
entering a key, entered character is not displayed onconsole.
charch;
ch=getch();
2. getche():- reads a character from keyboard and it does not require pressing of enterkey after
entering a key, entered character is echoed back on to theconsole.
char ch;
ch=getche();
getch() and getche() are available in the header file conio.h (console input output
header file)

3. getchar():-reads a character from keyboard and it requires pressing of enter key


charch;
ch=getchar();

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 36


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

4. gets():-reads a string fromkeyboard


char ch[10];

gets(ch);

OUTPUT FUNCTIONS:
1. putchar()
2. puts()
3. putch()

1. putchar():-prints a character on to thescreen

char ch;
ch=getchar();
putchar(ch);

2. puts():- prints a string on to thescreen

char ch[10];
gets(ch);
puts(ch);
3. putch():-prints a character on to thescreen

char ch;
ch=getchar();
putch(ch);
Expressions

An expression consists of a single entity such as a constant, a variable, an array element or a


reference to a function or can be a combination of such entities joined together using one or
more operators. An expression can also represent logical condition, that is true or false, which
can be represented using integer value like ‘1’ and ‘0’ respectively. Expressions can be simple or
complex. An operator is a syntactical token that requires an action be taken. An operand is an
object on which an operation isperformed;
A simple expression contains only one operator.
Example: 2+5=7;
A complex expression contains more than one operator.
Example: 2+6*8=50

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 37


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Here a priority comes into picture with precedence. The order in which the operators in a
complex expression are evaluated is determined by a set of priorities known as precedence.
Higher the precedence that expression will be calculated first. If two operators with the same
precedence occur in a complex expression, another attribute of an operator, its associativity,
takes control. Associativity is parsing direction used to evaluate an expression. It can be either
left-to-right or right-to-left.

Note: when two operators having same precedence occur in an expression, their associativity
is left-to-right. We can divide the simple expression into six categories.

Expression
Categories

Primary Postfix Prefix Unary Binary Ternary


Examples:

1. c=a+b*d;
2. x==y;
3. x+=y;
Note: An expression always reduces to single value.

Primary Expressions: A primary expression consists of only one operand with no operator. In c,
the operand in the primary expression can be name, a constant, or a parenthesized expression.
Names: A name is any identifier for a variable, a function or any other object in the language.
The following are examples of some names used as primaryexpressions:
Examples: a, b12, price, calc, INT_MAX, size etc.
Literal constants: A constant is a piece of data whose value can’t change during the execution
of the program.
Examples: 5, 123.98, ‘A’

Parenthetical expressions: Any value enclosed in parentheses must be reducible to a single


value and is therefore a primary expression.

Examples: (2+3+4), (a=23+b*6)

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 38


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Postfix Expressions: The postfix expression consists of one operand following by one operator.
Postfix increments/decrements: The postfix increments and postfix decrements are also
postfix operators. The value of the postfix increment expression is determined before the
variable is increased. For instance, if the variable a contains 4 before the expression is
evaluated, the value of the expression a++ is 4. As a result of evaluating the expression and its
side effect, a contains 5.

x = a (value of expression is a)

Example: x=a++

a = a+1(value of a is incremented by 1)

Note: The operand in a postfix expression must be a variable.

Prefix Expressions: The operator comes before the operand.

Prefix increment/decrement: In C, we have only two prefix operators that form prefix
expressions: prefix increment and prefix decrement. With the prefix operators, the effect takes
place before the expression that contains the operator is evaluated.

a = a +1 (value of a is incremented by 1)

Example: x=++a

x = a( value of expression is a after increment) if

the variable a contains 4 before the expression is evaluated, after evaluation the
value of both a and x will be 5.

Unary Expressions: A unary expression, like a prefix expression, consists of one operand and
one operator. The major difference is a prefix expression needs a variable while unary
expression can have an expression or a variable as the operand.

Sizeof: The sizeof operator tells us the size, in bytes, of a type or a primary expression. On some
PC the size of int is 2 bytes, some mainframes it is 4 bytes, and on super computers it is 16
bytes. It is important to know the exact size of an integer; we can use the sizeof operator with
the integertype.

Note: It is also possible to find the size of primary expression.


MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 39
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Examples: sizeof (-345.23), sizeof(x);

Unary plus/minus: The unary plus and unary minus are what we think of as simply the plus and
minus signs. In C, however, they are actually operators. Because they are operators, they can
be used to compute the arithmetic value of an operand.
Expression Contents of a Before expression Expression value
+a 3 +3
-a 3 -3
+a -5 -5
-a -5 +5
Binary Expressions: These binary expressions are formed by an operand – operator-
operandcombination.
Examples: Any two numbers added, subtracted, multiplied or divided are usually formed in algebraic
notation, which is a binary expression.
Assignment expression: The assignment expression evaluates the operand on the right side of
the operator (=) and places its value in the variable on the left. The assignment expression has
a value and a side effect.
 The value of the total expression is the value of the expression on the right of the
assignment operator(=).
 The side effect places the expression value in the variable on the left of the
assignmentoperator.
Note: The left operand in an assignment expression must be a single variable.
Simple assignment: a = 5, b =x+1, i = i+1
The left variable must be able to receive it; that is, it must be a variable, not a constant. If the
left operand cannot receive a value and we assign one to it,we get a compile error.
Compound assignment: A compound assignment is a shorthand notation for a simple
assignment. It requires that the left operand be repeated as a part of the right expression. Five
compound assignment operators are *=, +=, /=, %=, -=.

Example: x*=y+3 is evaluated as x = x*(y+3)

Precedence and Associativity

Precedence is used to determine the order in which different operators in a complex


expression are evaluated. Associativity is used to determine the order in which operators with

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 40


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

the same precedence are evaluated in a complex expression.

Precedence:

Example: 2+3*7

This expression is actually two binary expressions, with one addition and on multiplication
operators. So the multiplication has the higher priority then 3*7=21 and adds the remaining
21+2=23.

Associativity: Associativity can be left-to-right or right-to-left. Left-to-right associativity


evaluates the expression by starting on the left and moving to the right. Right-to-left
associativity evaluates the expression proceeding from right to left.

Note: Associativity is applied when we have more than one operator of the same precedence
level in an expression.

Left-to-right associativity:

Example: 3 * 8 / 4 % 4 * 5

Here all these operators have the same precedence so associativity from left to right.

((((3 * 8) / 4) % 4) * 5) -> (((24/4) %4) *5) -> ((6%4) * 5) -> (2 *5) -> 10

Right- to-left associativity:


Example: a +=b*=c-= 5
Which is evaluated as (a+=(b*=(c-=5)))
Again is expanded to (a=a+(b=b*(c=c-5)))
If a=3,b=5,c=8
(a=3+(b=(5*(c=8-5))) then c=3,b=15,a=18.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 41


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 42


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Side Effects: In assignment C first evaluates the expression on the right of the assignment
operator and then places the value in the left variable. Changing the value of the left variable is
a side effect.

Example: x =4;

This simple expression has three parts. First, on the right of the assignment operator is
a primary expression that has the value 4. Second, the whole expression (x=4) also has a value
of 4. And third, as a side effect, x receives the value 4.

Let’s modify the expression slightly

x = x+4; the initial value of x is 5 then x=7.

Evaluating Expressions

Expressions without side effects:

Assume the value of the variables a=3,b=4,c=5

a * 4 + b /2 – c * b
Following are the rules:
1. Replace the variable by their values. This gives us the following expression:
3 * 4 +4/2 – 5 * 4
2. Evaluate the highest precedence operators, and replace them with the resulting value.
In the above expression, the operators with the highest precedence are the multiply
and divide. We therefore evaluates them first from the left and replace them with the
resulting values. The expression is now (3 * 4) + (4/2)- (5*4) -> 12 +2– 20
3. Repeat step 2 until the result is obtained.Result=-6

Expressions with side effects:

Considertheexpression --a * (3+b) /2 – c ++ * b


Assume the values of the variables a=3,b=4,c=5;
Following are therules:
1. Calculate the value of the parenthesized expression(3+b)
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 43
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

- -a * 7 /2 –c ++ *b.
2. Evaluate the postfix expression(c++). Remember that as a postfix expression, the value
of c++ is same as the value of c; the increment takes place after the evaluation. The
expression isnow
- -a * 7 /2 – 5 *b.
3. Evaluates the prefix expression (--a) Remember that as a prefix expression, the value of
- -a is the value after the side effect, which means that we first decrement a and then
use its decrementedvalue.
2* 7 /2 – 5 *b
4. The multiply and division are now evaluated using their associativity rule, left to right.
The expression isnow
14 /3 -5 * b-> 7-5 *4 -> 7-20= -13
Note: In C, if a single variable is modified more than once in an expression, the result is
undefined.

Type Conversions or Mixed – Mode Expression

An expression that contains variables and constants of different data types is called as mixed –
modeexpression.
There are 2 types of data conversions that take place in mixed-mode expression.
1. Implicit dataconversion(Coercion)
2. Explicit data conversion(TypeCasting)

1. Implicit data conversion: In this type the control will automatically convert data values
of lower type are converted to the data types of highertypes.

Example program:
#include<stdio.h>
main()
{
int r1=6,r2=4,r3;
float r4=2.3,r5=3.2,r6;

double r7;

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 44


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

r7= (r1 * r4) +(r2 * r5) + 10;

int(6)float(2.3) int(4) float(3.2)int(10)

float(6.00) float(4.00) float(10.0)

float(13.800) + float(13.800) +float(10.0)

float(36.600)

double(r7) (36.00000000)
printf(“\n r7=%lf”,r7);
}
Output: r7=36.00000000

Rule1: when a real value is assigned to an integer variable, the fractional part of the real value
is truncated and only integer part is assigned to a variable.

Rule2: when an integer value say 10 is assigned to float variable, it is stored as 10.0000.

Implicit data conversion between character and integer rvalue.


Example program
#include<stdio.h>
main()
{
char ch= ‘a’,op;
int x=65,y;
y = ch;

int(97) char(a)

printf(“\n ch=%c , y=%d”, ch , y);//Output: ch=a,y=97

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 45


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

op = x;
char(a) int(65)
printf(“\n x=%d, op=%c”, x, op);// Output: x=65,op=A

}
Rule 3: when a character is assigned to an integer variable, the ASCII value of the char is
assigned to variable.

Rule 4: when a valid integer value (0 to 255) is assigned to char variable. Character equivalent
of the integer value is assigned to a variable.

Note: Assigning an integer value into a character variable beyond its range. i.e. less than zero
or greater than 255 leads to logical errors.

2. Explicit data conversion: In this type of data conversion between the output of an
rvalue is forced to act as user specified data type. It refers to the process of changing an
entity of one data type intoanother.

Syntax: lvariable=(data type) rvalue;

Typecasting

Example program for both explicit and implicit conversions


#include<stdio.h>
main()
{
int x=5, y=2;
float z;
z = x / y;

int(5) int(2) implicit dataconversion

float(2.0000) int(2)

printf(“\n %f”, z);

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 46


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Output: 2.0000
z=(float)x/y;

float float(2.5000) explicit data conversion


printf(“\n %f”,z);
Output:2.5000

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 47


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

UNIT-II

Topics Covered
Conditional Branching and Loops: if and switch statements,nested if-else. Iteration and
Loops – Use of while, do-while and for loops, nested loops, use of goto, break and
continue statements.
Arrays – One and two dimensional arrays, creating, accessing and manipulating elements of
arrays.

Control Structures
A program is nothing but the execution of sequence of one or more instructions. Some times it
is desirable to alter the execution of sequence of statements in the program depending upon
certain circumstances. This involves decision making through branching and looping. Control
statements specify the order in which the various instructions in a program are to be executed
by the computer. i.e. they determine the ‘flow of control’ in a program. Various control
statements in C are:
 Selection or decision control statements
 Case control statements
 Repetition or Loop control statements
Selection control statements:- Selection control statements allow the computer to take a
decision as to which statement is to be executed next. Different selection control statements
are:
 If statement
 Conditional operator
 if statement: The if statement is a powerful decision making statement and is used to control
the flow of execution of statements. It can be achieved through different forms of if statement.
a) simple if b) if – else c)nested if-else d) else-if ladder
a) simple if statement: C uses the keyword “if” to execute a set of statements or one
statements when the logical condition istrue.
Syntax: if(condition or expression)
{

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 48


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Statements-block;
}
next statement

It allows the computer to evaluate the expression first and then depending on the value of
expression, the control is transfers to the particular statement. If the expression is true(non-
zero value) then the statement-block is executed and next statement is executed. If the
expression is false(zero), directly next statement is executed without executing the statement-
block. Statement-block may be one or more statements. If more than one statement, then keep
all those statements in compound block({ })

Example:

1. if( age > 60)


printf(“Oldperson”);
2. if( marks>100)
{
printf(“ Invalid marks”);
printf(“ Check your marks once again “);
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 49


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

b) if –else statement: It is an extension of simple if. It takes care of both the true as well as
false conditions. It has two blocks. One is for if and it is executed when the condition is true,
the other block is for else and it is executed when the condition is false. No multiple else
statements are allowed with oneif.
Syntax: if(testcondition)

{
True block statements
}
else
{

False block statements


}

Next statement

Flowchart: false(zero) Expression true(one)

False block stmts True block stmts

If the condition is true then true block statement(s) is executed, otherwise if the condition is
false, then false-block statement(s) is executed. The else cannot be used without if.

Example: if(a%2 ==0)


printf(“ even number”);
else
printf(“odd number”);
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 50
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

c) Nested if-else statement: When a series of decisions are involved, we have to use more than
one if-else in nested form.
Syntax: if( condition-1)
{
if(condition -2)
{
………
if(condition-3)
{
Statement -1
}
else
{
Statement -2
}
}
else
{
Statement-3
}
}
else
{
Statement-4
}
Next statement

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 51


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

In this kind of statements, number of logical conditions is checked for executing various
statements. If any condition is true then associated block will be executed, otherwise it skips
and executes else block statements. We can add repetitively if statements in else block also.

Example: if(a>b)
{
if(a>c)
{
printf(“ ais big”);
else
{
printf(“c is big”);
}
}
else
{
if(c>b)
{
printf(“c is big”);

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 52


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

}
else
{
printf(“ b is big’);
}
}
d) else-if ladder: The else-if ladder is used when multipath decisions areinvolved.
Syntax: if(condition-1)
Statement-1
else if(condition2)
Statement-2
elseif(condition-3)
Statement-3
..
..
..
else
Statement-x
Next statement

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 53


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Example: if(avg>=70)
printf(“distinction”);
elseif(avg>=60)
printf(“ first class”);
else if(avg>=50)
printf(“secondclass”);
else if(avg>=40)
printf(“third class”);
else
printf(“fail”);
Case control statement: At times, the if condition may increase the complexity of the program
when one of many alternatives is to be selected. C has built-in multiway decision statement
known as switch-case. The switch statement requires only one argument variable or
expression. It tests the value of a given variable against a list of case values and when a match is
found, a block of statements associated with that case is executed, if not such match, then
default statement is executed.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 54


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Syntax: switch(variable or expression)


{
Case value 1: block-1
break;
Case value 2: block-2
break;
..
..
..
..
default:default-block
}
next statement

The expression is an integer expression or character. Value-1, value-2 are either integer
constants or character constants. These values should be unique with in a switch statement.
Case labels end with colon ( : ).

The break statement signals the end of a particular case and causes an exit from the switch
statement, transferring the control to the next statement following the switch.

The default is an optional case when present. It will be executed if the value of the expression
doesn’t match with any of the case values. If not present, no action takes place if all matches
fail and control goes to the next statement.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 55


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Example: switch(op)
{
case ‘+’: c=a+b; break;
case ‘-’: c=a-b; break;
case ‘*’: c=a*b; break;
case ‘/’: c=a/b;break;
default: printf(“wrong option”);
}

Loop control statements

Many tasks are needed to be done with the help of a computer and they are repetitive in
nature. Such type of actions can be easily done by using loop control statements.

Example: calculation of salary of employs of an organization for every month.

A loop is defined as a block of statements which are repeatedly executed for certain number of
times to do a specific task.

Steps in loops:-

1. Loop variable: It is a variable used in loop toevaluate.


2. Initialization: It is the step in which starting value or final values are assigned to the loop
variable.
3. Test-condition: It is to check the condition to terminate the loop. It is any relational
expression with the help of logicaloperators.
4. Update statement: It is the numerical value added or subtracted to the loop variable in
each round of theloop.
C language supports three types of loop control statements.

 while
 do-while
 for

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 56


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

 while: This is the simplest looping structure in C. the while is an entry-controlled loop
statement.
Syntax: initial statement
while(test condition)
{
Statement(s)
Update statement
}

Flow chart:
Start

Initialization

Condition

An action or
series of actions

End

The test condition may be any expression, is evaluated and if it is true then the body of the loop
is executed. The test condition is once again executed for updated values, and if it is true the
body of the loop is executed once again. This process is repeated until the test condition is
finally becomes false and control is transferred out of the loop to the next statement. The body
of the loop may contain one or more statements. The braces are needed if the body of the loop
contains more than one statement.

Example:
#include<stdio.h>
main()
{
int i,sum;
i = 1;

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 57


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

sum=0;
while(i<=10)
{
sum = sum + i ;
i + +;
}
printf(“sum=%d”,sum);
}
Here the value, sum of first ten numbers is stored into the variable sum; i is called as loop
variable.

The loop is repeated for ten times to do that process, each time by incrementing the value of i
by one. Once the value of i becomes 11 then the test condition becomes false and the control is
out of theloop.

 do-while: On some occasions it might be necessary to execute the body of the loop before the
test condition is performed. Such situations can be handled by the do-while statement. Do-
while id exit controlled loop statement.
Syntax:initial statement
do
{
Statement(s)
Update statement
} while(test – condition);
Next statement

Flow chart:
Start

(Post-test Loop) Initializatio


n
An action or

series of actions

true Condition

false

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 58


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

The body of the loop is executed first, and then at the end of the loop the test condition is
evaluated, if it is true then the statements are executed once again. The process of execution
continues until the test condition finally becomes false and the control is transferred to the
next statement

Example: main()
{
int i, sum;
i =1;
sum=0;
do
{
sum = sum + i;
i + +;
} while( i<=10);

printf(“Sum=%d”, sum);
}

 The for statement: The for loop entry controlled loop that provides a more concise loop
controlstructure.
Syntax: for( initialization ; test-condition ;increment/decrement)
{
Statement(s)
}
Next statement

The for loop allows to specify three things about the loop in a single line.
i. Setting a loop counter variable to an initial value using assignment statement. Eg:
i=1count=0;

ii. the test condition is a relational expression that determines the number of
iterations desired or it determines when to exit from the loop. If the test condition is
true, the body of the loop is executed, otherwise the loop is terminated and
execution continues with the next statement after theloop.
Eg: i<=10

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 59


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

iii. After evaluating the last statement of the body the loop, the control is transferred
to the increment/decrement statement of the loop. And the new value is again
tested to see whether it satisfies the loop condition ornot.
Eg: i++, ++I, i+=2
 The body of the loop may contain one or more statements. In case there is more than
one statement thenbraces
 The three sections of for loop must be separated by semicolons (;). Initialization and
incr/decr parts may contain more than one statement must be separated by commas.
Example: for(i=1, j=10 ; i<=10 ; i++, j--)
 The test-condition may have any compound relation and the testing need not be limited
only to the loopvariable.
Example: for(i=1; i<20 && sum <100 ; i++)
 It is permissible to use expressions in the assignment statement of initialization and
incr/decrsections.
Example: for( k=(a+b)/2;k>0;k=k/2)
 The sections of for loop my absent depends on requirement in the program. But it leads
to take some extra care about thosesections.
Example:
for( ; ; )
This statement leads to infinite loop or never–ending process.
Nesting of loops: The way if statement can be nested, similarly whiles and for can also be
nested.

Example: for(i=1;i<=3;i++) //outer for loop

{
for(j=1;j<=2;j++) // inner for loop

printf(“\t %d %d”, i,j);

printf(“\n”);

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 60


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

}
Here in this example nested for loop is used, and the total process is executed for 6( 3 * 2)
times. And the output of this example will be: 1 1 1 2

2 1 2 2

3 1 3 2

The way for loops have been nested here, similarly while and do-while can also be nested. Not
only this, a for loop can occur within a while loop, or a while within a for.

Example: Comparison of three loops. Finding the sum of first 10 numbers by using all loop
statements.

Program to write the sum of first 10 numbers by using while loop.


#include<stdio.h>
int main()
{
int i,sum;
sum=0; i=1;
while(i<=10)
{
sum=sum+i;
i++;
}
printf(“Sum of first 10 numbers = %d”, sum);
return 0;
}

Program to write the sum of first 10 numbers by using do-while loop.

#include<stdio.h>
int main()
{
int i,sum;

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 61


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

sum=0;
i=1;
do
{
sum=sum+i;
i++;
}while(i<=10);
printf(“Sum of first 10 numbers = %d”, sum);
return 0;
}
Program to write the sum of first 10 numbers by using for loop.
#include<stdio.h>
int main()
{
int i,sum;
for(i=1,sum=0;i<=10;i++)
{
sum=sum+i;
}
printf(“Sum of first 10 numbers = %d”, sum);
return 0;
}
Jumps in loops: We often come across some situations where we want to make a jumpfrom
one statement to other statement, jump out of a loop or to jump to next iteration of the loop
instantly,. This can be accomplished by the statements like:

 break
 continue
 goto.

The break statement:

 When we want to jump out of a loop instantly without waiting to get back to the
condition test, then the keyword break allows us to dothis.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 62


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

 The break statement provides an early exit from theloop.


 A break is usually associated with an if.
Example: for(i=1;i<=3;i++)
{
for(j=1;j<=5;j++)
{
if(j = =3)
break;
else
printf(“ %d %d”, i, j);
}
printf(“\n”);
}

Output: 1 1 1 2

2 1 2 2

3 1 3 2

In this example when j value equals 5, break takes the control outside the inner for loop
only, since it is placed inside the inner loop.

The continue statement:

 When we want to take the control to the beginning of the loop by passing the
statements inside the loop which are not yet been executed, then the keyword continue
allows us to dothis.
 It causes the next iteration of the loop to begin and it applies only toloops.
 A continue is usually associated with anif.

Example: for(i=1;i<=2;i++)
{
for(j=1;j<=2;j++)
{
if(i = = j)
continue;
else
printf(“ \n%d %d”, i, j);
}
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 63


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Output: 12
21

In this example when i and j values are equal, continue takes the control to the inner for loop
by ignoring rest of the statements in the inner forloop.

The goto statement:

 The goto statement alerts the normal sequence of program execution and control
transfers to some other part of theprogram.
 The goto statement leads the control to go to the particular part of the program by
indicating in its labelname.
Syntax: gotolabel;

Where label is a unique identifier used to label the target statement to which control will be
transferred. The general format of the label statement is:

label : statement;
Example:
void main()
{
int x;
read:
scanf(“%d”,&x);
if(x<0)
goto read;
else
printf(“x=%d”,x);
}

Here read is label, whenever x value entered as negative(x<0) then the control goes to read
label, and once again scanf( ) statement executed to read next value.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 64


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Arrays:
C supports a derived data type known as array that can be used to handle large amounts of data
(multiple values) at atime.

 An array is collection of elements of the same data type, which share a common name.

 Array elements are always stored in contiguous memory locations.

 Each element in the group is referred by its position called index.

 The first element in the array is numbered 0, so the last element is one less than the size of the
array.

 Before using an array its type and dimension must be declared, so that the compiler will know
what kind of an array and size of an array.

Each array element is referred by specifying the array name followed by one or more subscripts,with
each subscript enclosed in square brackets.The value of each subscript must be expressed as a
non-negative integer, variable or expression. The number of subscript determines the dimensionality of
the array. We can use arrays to represent not only list of values but also tables of data in two or more
dimensions. We have different types of arrays based on itsdimensional.


 One-dimensional arrays / Single-dimensional arrays

 Two-dimensional arrays / Double-dimensional arrays


 Multi-dimensional arrays

One – Dimensional arrays:

A list of items can be given one variable name using only one subscript and such a variable is
called one-dimensional array or single-dimensional variable.

Syntax: data-type array-name[size];

The data-type specifies the type of elements such as int, float or char. And the size indicates the maximum
number of elements that can be stored in that array

Eg: int a[5] ; here a is an array containing 5 integer elements.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 65


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

char name[20]; here name is an array containing 20 characters.

Note: C language character strings are as simple as array of characters. And every string should be
terminated by null character (‘\0’).
The computer internally reserves five storage locations for array a in the above example as follows.
Memory address
a[0] 2000
a[1] 2002
a[2] 2004
a[3] 2006
a[4] 2008

These elements may be used in programs just like any other Cvariables.

Eg: x = a [3] + a[2];

Y= a [4] * 2;
Note: C performs no bounds (array size) checking and therefore care should be exercised to ensure that
the array indices are within the declared limits.

Initialization of one-dimensional arrays: After an array is declared its elements must be initialized.
Otherwise they will contain garbage values. An array can be initialized at either of the followingstages.

 At compile time

 At runtime

Compile time initialization:

We can initialize the elements of arrays in the same way as the ordinary variables when they are
declared. The values in the list must and should be separated by comma.

data-type array-name [ size ] = { list of values };

Eg:

 int a[ 6 ] = { 3, 5, 23, 28, 6, 11 }; will initialize the given values to arraya.


 float avg[ 5 ] = { 78.45, 65.92,59.1} will assign the first three elements to 78.45, 65.92 and 59.1
and the remaining two elements to zero.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 66


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

 int counter[ ] = { 1, 1, 1, 1}; here the size is optional, it may be omitted. In such cases the
compiler allocates enough space for all initialized elements.
 char name[ ] = { ‘S’, ‘I’, ‘M’, ‘H’, ‘A’,‘\0’}; here declares the name to be an array of
characters, and is initialized by the string “SIMHA” ending with the null character. And we can do
the same thing in another way also. i.e. we can assign the entire string at a time, not an element
by element asfollows:
char name [ ] = “SIMHA”

 int num[3] = { 10,20,30,40,50 }; will not work. It is illegal in C. i.e. if we have more initializes than
the declared size, the compiler will produce an error.

Run time initialization: An array can be explicitly initialized at run time. At the time of execution array
values can begiven.

Examples:
1)
int a[ 10 ] ;
for ( i=0; i<10;i++)
scanf(“%d”,&a [ i ]);
2)
float x [15];
for( i=0; i<15;i++)
scanf(“%f”, &x [ i ] );
3)
char name[10];
for(i=0;i<5;i++)

scanf(“%c”, &name [ i]);

or

scanf(“ %s”,name);

or
char name[10];
gets(name);

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 67


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

//Example for One dimensional array – Sum of the elements of an array


// Initialize the array elements at compile time

#include<stdio.h>
int main()
{
int i,sum=0;
int a [ 10 ] = { 12, 3, 5, 43, 21, 1, 6, 8, 9, 11};
// Array a is initialized at compile time
/* finding the sum of array a */

for(i=0; i<10; i++)


sum = sum + a[ i ];
printf(“\n Sum of elements of array a is %d”, sum);
return 0;
}

//Example for One dimensional array – Sum of the elements of an array


// Initialize the array elements at run time

#include<stdio.h>
int main()
{
int a[ 10], i, n,sum=0;
printf (“Enter no.of elements :”);
scanf (“%d”, &n);
printf(“Enter %d elements :”,n);
for(i=0; i<n; i++)
scanf(“%d”,&a [i]); // run timeinitialization
/* finding the sum of array a */
for(i=0; i<n; i++)
sum = sum + a[ i ];
printf(“\n Sum of elements of array a is %d”, sum);
return 0;
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 68


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Two - Dimensional Arrays: C allows us to define the data in the form of table of items by using
two-dimensional arrays.
Syntax: data-type array-name[rowsize][columnsize];
Eg: int a[3][4] ; Here a is two dimensional array with row size 3 and column size 4., and the total
elements we can store in this array a is 12 (i.e. 3 * 4).
Each dimension of the array is indexed from zero to its maximum size minus one; the first index
selects the row and the second index selects the column with in that row. Two dimensional arrays are
stored in memory as follows:
Examples: Representation of two dimensional array in memory

[0][0] [0][1] [0][2] [0][3]

[1][0] [1][1] [1][2] [1][3]

[2][0] [2][1] [2][2] [2][3]

Initializing Two Dimensional Arrays: Like on-dimensional arrays, two-dimensional arrays can also be
initialized at compile time and runtime.

Compile time initialization:

Two-dimensional arrays may be initialized by following their declaration with a list of initial
values enclosed in braces. Until and unless we initialize the array explicitly it is having some garbage
values initially.

Eg:-int a [2] [3] = {3, 5, 7, 12, 22, 32};


Here a[0][0] = 3 a[0][1] = 5 a[0][2] = 7

And a[1][0] = 12 a[1][1] = 22 a[1][2] = 32

The initialization can also be done in row by row asfollows.

int a [2] [3] = {

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 69


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

{ 3, 5, 7 } ,
{12, 22, 32 }
};
We can also initialize a two dimensional array in the form of a matrix as follows:

int a[2] [3] ={


{ 3, 5, 7 },
{12, 22, 32 }
};
When the array is completely initialized with all values, explicitly we need not specify the size of the first
dimension (row size). i.e

inta [ ] [ 3] ={

{ 3, 5, 7 },
{12, 22, 32 }
};
If the values are missing in an initialization,they are automatically set to zero.i.e.

int a [2] [3] ={


{ 1, 5, },
{12}
};

So here the first two elements of the first row are initialized by 1 and 5 respectively, the first element of
second row to 12, and all other elements to zero.

Run time Initialization: An array can be explicitly initialized at run time.

Eg: int a [2] [3];


int i,j;
for ( i=0 ; i < 2;i++) // To represent row index ( i= 0,1)
{
for ( j =0 ; j < 3 ; j ++ ) // To represent column index ( j = 0,1,2)
scanf( “ %d”, & a[ i ] [ j ]);
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 70


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Ex: Program to print the multiplication table for first 10 numbers up to the 10 multiples.
#include<stdio.h>

#define ROW 10
#define COLUMN 10
int main()
{ int i,j,r,c,table[ROW][COLUMN];
printf("\n MULTIPLICATION TABLE \n\n");
printf("X|");
for(j=1;j<=COLUMN; j++)
printf("%5d",j);
printf("\n \n\n");
for(i=0;i<ROW;i++)
{
r=i+1;
printf("%d | ",r);
for(j=1;j<=COLUMN;j++)
{
c=j;
table [i][j]= r*c;
printf("%5d",table[i][j]);
}
printf("\n\n");
}
return 0;
}
In the above program the size of the array table is mentioned as ROW and COLUMN (i.e. table[ROW]
[COLUMN]) where these symbolic constants having the values 10 and 10. It is always good practice to
take the size of the array in terms of symbolic constants instead of directly taking the values.

Multi-Dimensional arrays:
C allows arrays of three or more dimensions. The compiler determines the exact limit.

Syntax: data-type array-name[S1][S2][S3]………[Sn]; where Si is the size

of the ithdimension.

Eg: int table [3][4][2]; Here table is the three dimensional array containing 24 integer elements (i.e. 3 *
4 * 2 = 24).

float a[4][2][5][3] a is a multi dimensional array containing 120 elements.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 71


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

UNIT-III
Topics Covered

Functions and Dynamic Memory allocation:


Functions – Declaring a function, Categories of functions, Passing parameters to
functions: call by value, call by reference. Passing arrays to functions. Scope - Local Vs
Global, Storage classes, Recursive functions.

DESIGNING STRUCTURED PROGRAMS

In the preceding chapters, we used only the three non-derived types, void, integral, and floating –
point. These are used to solve only the limited amount of problems. There are six derived data types in
C: Array, Functions, Pointer, Structure, Union, and Enumerated. Breaking a complex problem into
smaller parts (understandable parts). We call each of these parts of a program a module and the
process of subdividing a problem into manageable parts top-down design. In the principle of top-down
design and structured programming, a program is subjected to factoring, that is the program is divided
into main module and its related modules. Each module is in turn divided into sub modules until the
resulting modules cannot be further subdivided. A C program finds itself in a similar fashion as in top-
down structured designing. It cannot handle all the tasks by itself. Instead it requests other program-
like entities – calledfunctions.

Function: Definition

A function is a self-contained block of one or more statements that perform a particular task. Every C
program can be thought of as a collection of these functions, and one of which must be
main( ) function.

The execution of the program always starts and ends with main function and main function can call
other functions. A called function can receive control from a calling function, when the called function
completes its execution it returns the control back to the calling function. The communication between

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 72


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

calling function and called function is by passing parameters at the time of calling.

Advantages of functions in C

 It facilitates top-down modular programming; here the problem can be factored into
understandable and manageablesteps.
 Reusing of the code: The length of the source program can be reduced by using functions at
appropriate places. i.e writing functions avoids rewriting of same code over andover.
 Using functions it becomes easier to write programs and keep track of what they are doing.
 The functions are much easier to understand andtest.
 C comes with rich and valuable set of library functions that makes programmer’s workeasier.

C functions can be classified into two categories.

 Libraryfunctions
 User-definedfunctions
Library functions: The library functions are predefined set of functions. The user can only use these
functions but can’t change or modify them. These functions are already defined, tested and debugged
in C standard library. When the user needs to use library functions, then a call to these functions is
required.

Eg: The basic input and output functions like printf( ) , scanf( ) are defined in the C library header file
stdio.h.

sqrt( ), sin( ), cos( ), tan( ), pow( ), getchar( ), exit( ), toupper( ), strcmp( ), strlen( ) etc., all these are
some C library functions.

User-defined functions: These are defined by the user according to the requirement in the application.
The user can modify and can create any number of functions based on requirement. The user can
certainly understand the internal working of the function.

The difference between library functions and user-defined functions

 The library functions are not required to written by the user, where as user-defined functions
have to develop by the user at the time of writing ofapplication.
 The user can’t modify the meaning of the library functions. But user can modify the user-
definedfunctions.
 The library functions are already tested and debugged, but the user-defined functions need to

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 73


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

be test and debug.


The structure of user-defined function:

Syntax: return-type function-name (argumentslist)

argument declaration

{ Local variable declarations

Executable statement

……

……

……

return (expression or value)

}
 In function structure all parts not essential, it is based on the requirement of the program and
some sections or parts may beabsent.
 Return-type is any data type
 All functions by default return int typedata.
 Function-name can be any name like variables which follows naming conventions of identifiers.
 The arguments list and its associated declaration are optional. These are any valid variable
name separated by commas. There may be any number of variables, any type of variables with
respect to the function calling statement and these variables receive values from calling
function.
 The declaration of local variables is required only when any local variables are used in the
function.
 A function can have any number of executable statements.
 The return is a keyword which is followed by some expression or value. The return statement
returns a value to the calling function and is optional. When there is no return statement, then
no value is being returned to the calling function. We can return only one value at atime.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 74


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Eg: int add( int x, int y) int add(x,y) int add( int x, int y)
{ int x, y; {
int z; ( or ) { (or) return ( x + y );
z = x + y; int z; }
return z; z = x + y;
} return z;
}

 Every user-defined function can have its declaration (also called as function prototyping) and
definition. Some other function can call thisfunction.
 When function calling statement is invoked, the control is transferred to the function definition.
It is then executed and the control is transferred back to the calling function to execute next
statement.
 Any function can call any other function and can call itself(recursion).
 A function can call any number oftimes.
 C permits nesting of functions. Main can call function-1, which calls function-2, which calls
function-3 and soon.

Actual arguments and formal arguments:

 The arguments (parameters) of function calling statement are actual arguments; the
arguments of called function are formal arguments.
 The actual and formal arguments should match in number, type andorder.
 The formal arguments receive values from actual arguments when a function is calling, and by
this a communication between calling function and called function is made.
 When a function call is made, only a copy of the values of actual arguments is passed into the
called function’s formal arguments.
 The values of the actual arguments must be assigned before the function call is made.
 The formal arguments must be valid variable names, but the actual arguments may be variable
names, expressions, or constants.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 75


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Eg: //program for addition of two numbers using function

#include <stdio.h>
int main()
{
int a, b, c;
int add(int,int); // function declaration orprototyping
printf(“Enter two values“);
scanf(“%d%d”, &a, &b);
c=add(a,b); //function call statement
printf(“ addition of a, b is %d”,c);
return 0;
}
int add( int x,inty) // add function definition
{
int z;
z = x + y;
return z;
}

In the above program:


 a, b are actualarguments
 x, y are formalarguments
 main( ) is callingfunction.
 add( ) is calledfunction
The values of a, b are passed into x, y respectively when function is invoked and a, b values remains
same.

return statement:-

 Functions uses return statement to return a value to the calling function. And exit from the
called function is done by the return statement.
 The return statement returns only one value at a time. There may be more than one return
statement in a function, but it returns only one value.
 The value returned by the called function is collected by the calling function.
 Return statement with out any value will return value one.

 Eg: return; this returns 1 to the calling function

 Absence of return statement indicates that no value is returned, such functions return type is
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 76
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

void (i.e returning nothing).


Eg: return; return(9*3); return (a + b); return c;

Function prototype:
 Function prototyping is nothing but function declaration; it consists of function’s return type,
name, and arguments list withtype.
 When a function is defined, the function header in the definition must be same like its
prototypedeclaration.
 The function prototype statement is terminated bysemicolon.
 A prototype statement helps the compiler to check the return type and arguments type of
thefunction.
 The prototype of library functions is given in the respective header files, those we include by
using #include pre-processor directive.
Eg: int add( int,int); voiddisplay(charc); float average(float, float,float);

Category of functions: A function depending on whether the arguments are present or not, and a
value is returned or not may belong to one of the following categories.

1. Functions without arguments and without returnvalues.


2. Functions with arguments and without returnvalues.
3. Functions without arguments and with returnvalues.
4. Functions with arguments and with returnvalues.

1. Functions without arguments and without returnvalues:


 When a function has no arguments, it does not receive any data from calling function.
 When a function does not return any value, the calling function doesn’t receive any data
from called function.
 There is no data transfer in between the calling function and calledfunction.
 This type of functions may be useful to print some messages, draw a set of lines, etc.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 77


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Eg:
#include<stdio.h>
void displayline();
void message ();
int main()
{
displayline( );
message( );
displayline( );
return 0;
}
void displayline ( ) // no arguments and no return type for display line
{
int i;
for(i=1; i<=80; i++)
printf(“-“);
printf(“\n”);
}
void message( )
{
printf(“ ** TRY TO UNDERSTAND THE LANGUAGE **** \n ”);
printf(“ ***NOT TO BYHARD THE LANGUAGE ***** \n ”);
}

OUTPUT: -
** TRY TO UNDERSTAND THE LANGUAGE ****
***NOT TO BYHARD THE LANGUAGE *****
-

2. Functions with arguments and without returnvalues:

 The nature of data communication between the calling function and the called function is
with arguments but no return values.
 One-way data communication between calling function and called function through
arguments.
 The control is transferred to the called function by passing some arguments, after
performing the task; the control is back to the calling function without returning any value.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 78


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Eg: #include<stdio.h>
void displayline(char);
void message(char);
int main( )
{
char name[30] = “DENNIS RITCHIE”;
char ch = ‘-’;
displayline( ch);
message( name);
displayline( ch);
return 0;
}

void displayline (char x ) // with arguments and no return type for displayline
{
int i;
for(i=1; i<=80; i++)
printf(“%c”, x);
printf(“\n”);
}

void message(char str[30]) // with arguments and no returntype


{
printf(“ \t \t”);
printf(“ %s”, str);
printf(“\n”);
}

OUTPUT: -
DENNIS RITCHIE
-

3. Functions without arguments and with return values:


 The function is called without passing any arguments, but after performing the task, it returns
some value to the callingfunction.
 One-way data communication between calling function and called function through
returnstatement.
 The control is transferred to the called function without passing any arguments,after
performing the task; the control is back to the calling function by passing some value.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 79


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Eg:
#include<stdio.h>
int factorial();
int main( )
{
int f;
f = factorial( );
printf(“ \n Factorial f = %d”, f);
return 0;
}

int factorial( ) // without arguments, but returns some value.


{
int i, f =1,n;
printf(“ enter a value“);
scanf(“%d”, &n);
for(i=1; i<=n;i++)
f= f * i ;
return f;
}
OUTPUT:
enter a value 4
Factorial f =24

4. Functions with arguments and with return values:-


 Two-way data communication between calling function and called function is by passing
arguments and sending back somevalue.
 The control is transferred to the called function by passing some arguments, after performing
the task; the control is back to the calling function by returning some value.
 At the time of function calling the actual arguments are dumped into formal arguments.
Eg:
#include<stdio.h>
int factorial (intx);
int main()
{
int n,f;
int factorial(int); // function declaration or prototyping
printf(“ enter a value“);
scanf(“%d”, &n);
f =factorial(n); // function calling statement
printf(“ \n Factorial f = %d”,f);
return 0;
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 80


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

int factorial(intx) // function definition with argument, with return value.


{
int i, f =1;
for(i=1; i<=x;i++)
f= f * i;
return f;
}

Parameter passing techniques:


Parameter passing is a technique used to pass data to a function. Data are passed to a
function using one of two techniques: pass by value (call by value) and pass by reference (call by
reference).

1. Call by value:

 In call by value mechanism a copy of the data is sent to the function. That is the values of actual
arguments are being copied into formal arguments. And ensures that the original data in the
calling function cannot bechanged.
 Memory is allocated temporarily for formal parameters and localvariables.
 Whatever the modifications are done for formal parameters will not affect the
actualparameters.
2. Call by Reference:

 In call by reference mechanism the address of the data rather than a copy is sent to the
function. That is the address of actual arguments is being passed into formal arguments.
The called function can change the original data in the callingfunction.
 When we pass the addresses, the receiving parameters should be pointers to hold these
addresses.

 What ever the modifications are done for formal parameters will directly affect the actual
parameters.
 C language does not have a true call by reference and it is stimulated by call by address.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 81


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Eg:// program for call by value mechanism


#include<stdio.h>
int main( )
{
int a, b;
void swap(int, int);// function declaration or prototyping
printf(“ enter two values “);
scanf(“%d %d”, &a, &b);
swap(a,b); // function calling statement
printf(“ Values after swap function call are:“);
printf(“ a= %d \t b = %d ”, a, b);
return 0;
}
void swap( int x,inty) // functiondefinition.
{
int temp;
temp = x;
x = y;
y = temp;
}
OUTPUT:- enter two values 10 20
Values after swap function call are: a=10 b=20

Here the copy of the actual data a, b is sent to formal parameters of swap function, in swap function
these are swapped but the changes made to x, y are not affect the values of a, b in main function.
Because the copy the data is sent but not original location.

Eg: // program for call by reference mechanism #include<stdio.h>


int main( )
{
int a, b;
void swap(int, int); // function declaration or prototyping
printf(“ enter two values “);
scanf(“%d %d”, &a, &b);
swap(&a, &b); // function calling statement
printf(“ Values after swap function call are: “);
printf(“ a= %d \t b = %d ”, a, b);
return 0;
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 82


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

void swap( int *x,int*y) // functiondefinition.


{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
OUTPUT:- enter two values 10 20
Values after swap function callare: a=20 b=10

Here the address of the actual data (&a, &b) is sent to formal parameters ( *x, *y) of swap function, in
swap function instead of creating temporary memory locations for x and y, the same memory locations
of a, b referenced by x, y. So changes made to x, y are directly affects a, b in main function. So finally
swapped values are stored in a, b.

Passing Arrays as a parameters to a function


An array can be passed as a parameter to a function.
Syntax: return type function_name( data type*array_pointer);
or
return type function_name( data type array_name[size]);
Example: void sum(int *a);
Where a is a formal parameter which holds the starting address of the array passed as a parameter to the
function sum
Or
void sum( int a[10]);

Program for passing an array as argument to a function


#include<stdio.h>
void sum(int *a, int n);
int main()
{
int a[10], i, n;
printf(“Enter the size of the array”);
scanf(“%d”, &n);
printf(“Enter %d elements”,n); for(i=0; i<n; i++)
scanf(“%d”,&a[i]); sum(a,n);
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 83


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

void sum(int *a, int n)


{
int i, sum = 0;
for(i=0; i<n; i++)
sum += a[i];
printf(“Sum : %d”, sum);
}

Scope - Local and Global variables

A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed.
There are three places where variables can be declared in C programming language −

 Inside a function or a block which is called local variables.


 Outside of all functions which is called global variables.
 In the definition of function parameters which are called formal parameters.

Local Variables

Variables that are declared inside a function or block are called local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to
functions outside their own.
The following example shows how local variables are used. Here all the variables a, b, and c are local
to main() function.

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

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 84


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Global Variables

Global variables are defined outside a function, usually on top of the program. Global variables hold
their values throughout the lifetime of your program and they can be accessed inside any of the
functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is available for use
throughout your entire program after its declaration.
The following program show how global variables are used in a program.

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

A program can have same name for local and global variables but the value of local variable inside a
function will take preference
#include <stdio.h>
int g = 20; /* global variable declaration */
int main ( )
{
int g = 10; /* local variable declaration */
printf ("value of g = %d\n", g);
return 0;
}

When the above code is compiled and executed, it produces the following result − value of g = 10
Formal Parameters:
Formal parameters are treated as local variables with-in a function and they take precedence over
global variables.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 85


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Storage classes:

All the variables in C, not only to have a data type, they also have a “Storage classes”. The storage
class of variable tells the compiler that:
(a) The storage area of the variable: there are basically two kinds of locations in a computer where
such variables or values to be kept, “Memory and CPU Registers. The storage class of a
variable determines in which of these two locations the value is stored.
(b) The initial value of the variable if not initialized.
(c) The scope of the variable(active) that in which functions the value of the variable would be

available.
(d) Life of the variable (alive) that is how long the variable would be active or exist in the
program, i.ethe longevity of the variable.

There are four storage classes in C:

1. Automatic variables.
2. Register variables.
3. Static variables.
4. External variables.

1. Automatic storage classes variables: The features of automatic storage classes variablesare:
Storage :Memory
Initial value : Garbage value or unpredictable value.
Scope : Local to the block in which it isdefined.
Life time : Until end of function or end of block where it isdefined.
 Automatic variables are declared inside a function in which they are to be utilized. They are
created when the function is called and destroyed automatically when the function is exited.

 Automatic variables are local to thefunction.


 We use the keyword auto to declare automatic storageclasses.
 The default storage class of a variable is automatic storage class.

Ex: int x; it implies that auto intx;

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 86


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

 Because of the scope of the automatic variables,they are also referred to local or
internal variables.
Ex: 1.
#include<stdio.h>
main ( )
{
auto int i; int j;
printf (“\n %d \t %d”, i, j);
}
Output: some garbage values, because they are not initialized to any value. A variable j without having
any storage class is by default automatic. So both i, j are automatic variable.

Ex: 2.
#include<stdio.h>
main ( )
{
auto int a = 1;
{
auto int a =2;
{
auto int a = 3;
printf(“a =%d”,a);
}
printf(“ \n a = %d”, a);
}
printf(“ \n a = %d”, a );
}
Output: 3
2
1
2. Register variables:
The features of a variable defined to be of Register storage class are:
Storage : Registers
Initial value : Garbage value or unpredictablevalue.
Scope : Local to the block in which it isdefined.
Lifetime : Until end of function orblock.
1. A variable stored in CPU Register can always be accessed faster than the one whichis stored
inmemory.
2. If a variable is used at many placed in a program, then it is better to declare it as register variable.
Ex:- loop countervariables.
3. We can use the keyword “register” to declare registervariables.
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 87
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

We cannot use register class for all types of variables, because CPU registers in a micro computer are
usually 16- bit registers and therefore cannot hold a float value or a double value which require 4
and 8 bytes respectively. However C will automatically convert register variables into non register
variables once the limit is reached.
Ex:-
#include<stdio.h>
main ( )
{
register int i;
for(i = 1; i < = 10; i++)
printf(“\n %d”, i);
}

3. Static variables:The features of static storage class variable are:

Storage : Memory
Initial value : Zero
Scope : Global (may be internal static or external static)
Lifetime : Value of the variable persists between different function call.

 Static variables persist until the end of theprogram.


 A static variable may be either an initial type or an external type, depending on the place
ofdeclaration.
 We can use the keyword “static” to declare a variable as staticvariable.
 A static variable is initialized onlyonce.
 The difference between auto variables and static variables don’t disappear when the function is
no longer active. These values persist, but auto variables disappear when the function is no
longeractive.
Ex:-
#include<stdio.h>
void Display ( );
main ( )
{
int i;
for(i = 1; i < = 3; i++)
Display ( );
}
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 88
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

void Display ( )
{
static int x = 0; x = x +1;
printf(“x = %d \n”, x);
}
Output:- x =1
x =2
x =3
4. External variables:- The features of a variable whose storage class has been defined as external
are as follows:
Storage : Memory
Initial value : Zero
Scope : Global
Life time : As long as the program’s execution doesn’t come to an end.

1. External variables are declared outside of the allfunctions.


2. The external variables are both alive and active throughout the entireprogram.
3. They may be declared using the keyword“extern”.
4. The external variables are also known as global variables. These variables can be accessed by
any function in theprogram.
5. In case, both external and auto variables are declared with the same name, in a program the
first priority is given to the autovariable.
6. Use external storage class only these variables which are being used by almost all the functions
in the program. This would avoid unnecessary passing of the variables as arguments when
making a functioncall.
Ex:-
#include<stdio.h>
int i = 10;
void display();
main ( )
{
int i = 20;
printf(“\n %d”,i);
display ( );
}
void display()
{
printf (“\n%d”,i);
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 89


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Output: 20
10
Recursion:

 When a function calls itself, then that process is called as recursion and that function is called
as recursive function.
 Recursive functions can be used to solve problems where the solution is expressed in terms of
successively applying the same solution to subsets of theproblems.
 Every recursive functions must has to have two basicproperties:
( i ) A termination condition called anchor step to avoid infinite process.
(ii) A repetition statement called recurrence step to repeat the function calling process.
 Recursion is of two types. Direct recursion and indirect recursion.
 When a function calls itself, then it is direct recursion. But when function-1 calls function-2 and
in turn function-2 calls function-1 then it is indirect recursion.

Eg: To calculate the factorial value of number 4,the recursion processis as follows.
#include<stdio.h>
int main()
{
int n, f;
intfactorial(int); // function declaration or prototyping
n = 4;
f =factorial(n); // function calling statement
printf(“ \n Factorial f = %d”,f);
return 0;
}

int factorial(intx) //function definition with argument, with return value.


{
int f;
if( (x = = 1) || (x = = 0))
return 1;
else
return (x * factorial ( x - 1) );
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 90


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Anchor step: if( (x = = 1) || (x = = 0))


Recurrence step: return (x * factorial ( x - 1))
x * factorial ( x - 1) is processed asfollows:
4 * factorial( 3 )
3* factorial ( 2 )
2* factorial ( 1)
1
4* 3 * 2 * 1 =24

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 91


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

UNIT – IV
Topics Covered

Strings – Introduction to strings, declaration and Initialization, String Input / Output functions,
String manipulation functions, Array of strings
Pointers – Defining Pointer, declaration and Initialization, accessing variables through
pointers, pointers to arrays, pointers to functions, pointers to structures, command line
arguments, enumeration data type
Dynamic Memory allocation: Allocating and freeing memory(malloc(), calloc(), realloc()
and free()

Strings

A string is an array of characters. (Or) A string is a one-dimensional array of characters


terminated by a null character (‘\0’).
Eg: “INDIA” “WELCOME”
Each character of the string occupies one-byte of memory. The characters of the string are stored in
contiguous memory locations.
Declaration and Initialization of Strings
Syntax: char string-name[size]; Eg:
char city[20];
Character arrays (strings) may be initializing when they are declared (compile time initialization).
Eg:
 We can initialize a character array as element by element and last character should be the nullcharacter.
char city [10] = { ‘H’, ‘Y’, ‘D’, ‘E’, ‘R’, ‘A’, ‘B’, ‘A’, ‘D’, ‘\0’ };

 We can initialize a character array as total string at atime.


char city [10] = “HYDERABAD”;
 We can initialize a character array with out specifying the size, the compiler automatically
determines thesize.
char city [ ] = “HYDERABAD”;
The memory representation of this character array is as follows:
0 1 2 3 4 5 6 7 8 9

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 92


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

H Y D E R A B A D \0

3010 3011 3012 3013 3014 3015 3016 3017 3018 3019
Reading Strings:-
 The input function scanf ( ) can be used with %s format specification to read astring.

 Eg: charname[30];
scanf(“%s”, name);
 The scanf() function to read multi word strings is doesn’t consider white spaces. It
terminatestheinputstringatfirstoccurrenceofwhitespace.Somultiwordstringscan’t read by using
scanf()function.
Eg: char city[30];
scanf(“%s”,city);

If the input string is “NEW DELHI”, then the variable city can store only “NEW”, it ignores the rest
because white space is occurred after NEW.

 To read multi word strings, we can use gets( ) function orgetchar( ) function repeatedly.
 Eg: char city[20];
gets(city);
if the input string is “NEW DELHI”, then name contains total string “NEW DELHI”.
(Or)
inti=0;
char city[20], ch;
do
{
ch=getchar();
name[ i ]=ch;
i++;
} while(ch != ‘ \n’);
 C language doesn’t allow operators that work on stings directly. I.e. assignment, arithmetic,
equality operator etc doesn’t work withstrings.
Eg:char s1[10],s2[10];
s1 =“WELCOME” Invalid
s1==s2 Invalid

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 93


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

s1+s2 Invalid

Writing of strings to screen


 Theprintf()functionwith%sspecificationisusedtoprintstringstothescreen.
Eg:printf(”%s”,city);
 We can also specify the precision with which the array isdisplayed.
Eg:char name[ ] =” RADHAKRISHNA”;
printf(“%s”,name); RADHA KRISHNA
printf(“%14s”,name); RADHA KRISHNA
printf(“ % 5s”, name); RADHAKRISHNA
printf(“ %14.5s”,name); RADHA
printf(“ %-14.5s”, name); RADHA
printf(“ %.3s”,name); RAD

We can also print strings by using puts () function and putchar () functionrepeatedly
Eg: puts(name)
OR
for(i=0;name[i]!=’\0’;i++)
{
putchar(name[i]);
}
PROGRAM TO READ A STRING AND PRINT IT
#include<stdio.h>
int main()
{
char ch, city[20]; int i;
printf("Enter a city name ");
i=0;
do
{
ch=getchar();
city[i]=ch;
i++;
}while(ch!='\n');
i=i-1;
city[i]='\0';
printf("The city is :");
puts(city);
return 0;
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 94


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

String handling functions


Operators can’t work with strings directly. So to manipulate strings we have a large number of string
handling functions in C standard library and the responsible header file is “string.h”. Some of those
functions are:
strcpy ( ), strcmp ( ), strcat ( ), strlen ( ), strrev ( ) etc.

strcpy( ): It is to copy one string into another, and it returns the resultant string.

Syntax: strcpy( string1,string2);


String2 is copied into string1.
Eg: char city1[10] =“HYDERABAD”;
char city2[12] = “BANGLORE”;
strcpy (city1,city2);
Here city2 is copied intocity1. Socity1= “BANGLORE” and city2=”BANGLORE”. The size of the array city1
should be large enough to receive the contents ofcity2.

strcmp( ): It is to compare two strings to check their equality. If they are equal it returns zero,
otherwise it returns the numeric difference between the first non matching characters in the strings.
(i.e. +ve if first one is greater, -ve if first one is lesser).
Syntax: strcmp (string1,string2);

Eg: char city1[10] =“HYDERABAD”;


char city2[12] = “BANGLORE”;
strcmp (city1,city2);
Here city1 and city2 are compared, and returns the numeric difference between ASCII value of ‘H’ and
ASCII value of ‘B’ as they are not equal.
strcmp(“RAM”,ROM”); It returns some –ve value.
strcmp(“RAM”,RAM”): It returns 0 as they are equal.

strcat( ):This function is used to join two strings together, and it returns the resultant string.

Syntax: strcat( string1,string2);

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 95


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

String1 is appended with string2 by removing the null character of string1 and string2 remains
unchanged. The resultant string is stored in string1.

Eg: char city1[10] = “HELLO”;

char city2[12] =“WORLD”;

strcat (city1,city2);
Here city2 is appended to city1. So city1= “HELLOWORLD” and city2=”WORLD”.

strlen(): It is to find out the length of the given string and it returns an integer value, that is the number
of characters in the given string. It takes only oneparameter
Syntax: strlen(string1);
It gives the length of string1.

Eg:char city[10] = “HYDERABAD”;

strlen(city); it gives the value9.

strrev( ): This function is to find out the reverse of a givenstring.


Syntax: strrev(string);

Eg: char city[10] =“HYDERABAD”;


strrev(city); it give the string “DABAREDYH”

Array of Strings
We have array of integers, array of floating point numbers, etc. Similarly we have array of strings also.
Collection of strings is represented using array of strings.

Declaration:
char arr[row][col]; where,
arr - name of thearray
row - represents number of strings

col - represents size of each string

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 96


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Initialization:-
char arr[row][col] = { list of strings };

Example:-
char city[5][10]={“DELHI”, “CHENNAI”, “BANGALORE”,“HYDERABAD”,“MUMBAI” };

D E L H I \0
C H E N N A I \0
B A N G A L O R E \0
H Y D E R A B A D \0
M U M B A I \0

In the above storage representation memory is wasted due to the fixed length for all strings
#include<stdio.h>
int main()
{
int i;
char ch_arr[3][10] = {"spike",
"tom",
"jerry"
};
for(i = 0; i < 3; i++)
{
printf("string = %s \n", ch_arr[i]);
}
return 0;
}

POINTERS:

Pointer: A Pointer is a variable which can store the address of another variable

Syntax for declaring a Pointer

dataype*var_name

datatype is the pointer's base type; it must be a valid C data type and var-name isthe name of the
pointervariable

Example: int *p;  Pointer to an integer


float *q;  Pointer to a float
char *r;  Pointer to achar
a. we define a pointervariable

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 97


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

b. assign the address of a variable to apointer


c. access the value at the address available in the pointervariable

Example Program for declaring and accessing value using a Pointer


#include<stdio.h>
int main()
{
int i = 10, *p;
p = &i;
printf(“Value of i through pointer p : %d”, *p);
return 0;
}

Benefits of using pointers are


b. Pointers can be used to return multiple values from a function via functionarguments.
c. Pointers allow arguments to be passed byreference
d. Pointers allow passing arrays and strings as arguments to functions moreefficiently
e. Pointers allow C to support dynamic memorymanagement.

Arithmetic operations that can be performed on pointers

i. Like normal variables, pointer variables can be used inexpressions.

Example: x= (*p1) + (*p2);

ii. C language allows us to add integers to pointers and to subtract integersfrom


pointers

Example: If p1, p2 are two pointer variables then operations such as p1+4, p2 - 2, p1 - p2
can be performed

iii. Pointers can also be compared using relationaloperators.

Example: p1>p2, p1==p2, p1! =p2 are valid operations

iv. Pointerconstantsshouldnotbeusedindivisionormultiplication.Also,two pointers


cannot beadded.

Example: p1/p2, p1*p2, p1/3, p1+p2 are invalid operations.

v. Pointer increments and scalefactor: when a pointer is incremented, its values is


increased by length of data type that it points to. This length is called scale factor.

Example: If the address of p1 is 1002. After using p1=p1+1, the value becomes 1004 but
not 1003.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 98


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Pointer to array:
Elements of an array can be accessed through a pointer also. We can declare a pointer variable and
store the address of the first element of the array in the pointer variable. All the elements of the
array can be accessed through the pointer.
Example: int arr[10] = {1,2,3,4,5};
int *ptr =arr;
In the above example, arr is an integer array, ptr is an integer pointer in which address of the first
element of the array is stored

Program to access the elements of an array through pointer


#include<stdio.h>
int main()
{
int arr[5] = { 1, 2, 3, 4,5}; // integerarray
int *ptr=arr; // pointer ptr storing the address of the first element of arr
for(i=0;i<5;i++)
printf("%d\n", *ptr); // accessing elements of array through pointer variable
return 0;
}

Pointers to Functions
A function, like a variable has a type and address location in the memory. It is therefore possible to
declare a pointer to a function, which can then be used as an argument in another function .
A pointer to a function can be declared as follows.
Syntax: datatype (*fptr)();
fptr is a pointer to a function which returns type value
A function pointer can be made to point to a specific function by assigning the name of the function to
the pointer
Example:
int multiply(int a,intb); function declaration
int(*fptr)(int,int); pointer to afunction
fptr=multiply; assigning address of multiply tofptr
n=(*fptr)(a,b); function call using pointerfptr

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 99


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Program showing Pointer to a Function


#include<stdio.h>
int multiply(int a, int b);
{
return a * b;
}
int main( )
{
int a, b, c;
int (*fptr)(int,int);
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
fptr = multiply;
c = (*fptr)(a,b);
printf(“Result : %d”,c);
return 0;
}

Pointers to Structures:

Pointer is a variable that holds address of another data variable. We can also define pointer to
structure. That is we can declare a pointer as a structure variable and store the address of a structure
variable in the pointer of the same structure. Now, Structure members can be accessed using the
pointer variable.

Eg:
struct book
{
char name[20];
char author[20];
int pages;
};
struct book *ptr;

Here ptr is a pointer variable to the structure book. We can access the members of the structure by
using ptr variable and is accomplished by indirect member selector operator (->) or structure pointer
operator.
i,e ptr->name, ptr->author, ptr->pages.

/*Example for pointer to structure*/


struct book
{

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 100


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

car name[20];
char author[20];
int pages;
};

int main()
{
struct book b1 = {“let us c”,”kanetkar”,100};
struct book *ptr;
ptr=&b1;
printf(“\n%s by %s of %d pages”,b1.name,b1.author,b1.pages);
printf(“”\n %s by %s of %d pages”, ptr->name, ptr->author, ptr->pages);
return 0;
}
In the above example ptr is a variable, which is used to hold the address of structure variable. The
structure members can be accessed using the indirect selector operator.
*ptr->rno is same as (*ptr).rno.

The parenthesis around *ptr are necessary, because the member operator, has a higher precedence
than the operator “*”.

Command Line Arguments:


Arguments passed to the main function are known as Command Line Arguments. Command
line arguments are given after the name of the program during the execution of the program in a
command-line shell. To pass command line arguments, main() is defined with two arguments
first argument is the number of command line arguments and second is list of
command-line arguments.

int main(int argc, char *argv[ ])


{
……..
}
argc (argument count) is int and stores number of command-line arguments passed by the user
including the name of the program. So if we pass a value to a program, value of argc would be 2 (one
for argument and one for program name) The value of argc should be non negative.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 101


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

argv(argument vector) is array of character pointers listing all the arguments.


If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain pointers to
strings.
argv[0] is the name of the program , after that till argv[argc-1] every element is command line
arguments.
Example:
int main(int argc, char* argv[ ])
{
printf(“You have entered %d arguments\n”,argc);
for (int i = 0; i<argc; ++i)
printf(“%s”,argv[i]);
return 0;
}

Dynamic MemoryManagement
Dynamic allocation: Dynamic memory allocation is the process ofallocating memory during execution
time.
Dynamic Memory Allocation Functions in C:
This allocation technique uses predefined functions to allocate and release memory for data during
execution time.

Function Syntax

malloc () Void * malloc (size_t);

calloc () Void * calloc (int number, size_t );

realloc () Void * realloc (pointer_name, size_t);

free () free (pointer_name);

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 102


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

1. malloc( ):

 malloc( ) function is used to allocate space in memory during the execution of


theprogram.
 It does not initialize the memory allocated duringexecution.
 It carries garbagevalue.
 It returns null pointer if it couldn’t be able to allocate requested amount of memory.

2. calloc( ) : calloc( ) function is also like malloc( ), but calloc( ) initializes the allocated memory
tozero.

3. realloc( ):
 realloc ( ) function modifies the allocated memory size by malloc( )and calloc( )
functions to newsize.
 If enough space doesn’t exist in memory of current block to extend, new block is
allocated for the fullsize of reallocation,then copies the existing data to new block and
then frees the oldblock.
4. free ( ):
free ( ) function frees the allocated memory by malloc ( ) and calloc ( ) functions and returns
the memory to the system
Example:

Program to allocate memory for an array dynamically, store and access its values
#include<stdio.h>
#include<stdlib.h>
int main( )
{
int *a, i, n;
printf(“Enter the size of the array”);
scanf(“%d”,&n);
a = (int *) calloc(n , sizeof(int));
printf(“Enter %d elements into the array”);
for(i=0; i<n;i++)
scanf(“%d”,&a[i]);
printf(“\nElements of the array”); for(i=0;i<n;i++)
printf(“%d ”,a[i]);
free(a);
return 0;
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 103


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Difference between static memory allocation and dynamic memory allocation

Static Memory Allocation Dynamic Memory Allocation

It is the process of allocating memory at It is the process of allocating memory


compile time. during execution of program
Fixed number of bytes will be allocated Memory is allocated as and when it is needed.
The memory is allocated in memory stack The memory is allocated from free memory
pool (heap).
Execution is faster Execution slow
Memory is allocated either in stack area or Memory is allocated only in heap area
data area
Ex: Arrays Ex: Dynamic arrays, Linked List, Trees

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 104


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

UNIT-V

Topics Covered

Structures and Unions – Defining structures, Declaration and initialization, arrays of


structures, unions
Files –Text files and Binary files, Opening and closing files, File input / output functions.
Creating, Reading and writing text files. Appending data to existing files.

Structures
Structure is a collection of logically related elements of different data types.

Structure is a mechanism for packing data of different types. It is a convenient tool for handling a group of
logically related data items.

Eg: It can be used to represent a set of attributes, such as student-name, roll-number, and marks. We use a
structure to represent all these different data elements.

Declaration of a structure: A structure is declared as follows:

Syntax:
struct tag-name
{
Datatype member-1;
Dattype member-2;
:
:
Datatype member-n;
};
Eg: struct student
{
int rno;
char name[20];
int tm;
float avg;
};

 Here “struct” is a keyword used to declare astructure.


 Tag-name is the name given to structuredeclared.
 Member-1, member-2,….member-n are elements or fields of the structure, each member may belong to

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 105


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

different datatype.
 Structure declaration should be terminated bysemicolon.
 Structure declaration doesn’t get any space for its members, it simply describes a format called template
to represent theinformation.
 Memory allocated only after declaring structurevariables.
 Structure variables can be declared using tag-name asfollows:

Declaring a structure variable:


Syntax:
struct tag-name variable-1,variable-2, ............... variable-N;

Eg: struct student s1, s2, s3;

Here student is a structure and it is having 4 different members which are logically related.
And s1, s2 and s3 are three structure variables.

 It is also allowed to combine both the template declaration and structure variables declaration in
one statement. The declaration is asfollows:
struct student
{
int rno;
char name[20];
int tm;
float avg;
}s1,s2;

 Tag-name is optional in structure declaration. When tag-name is absent then structure variables
should be created in structure declaration itself, beforesemicolon.

Individual members of the structure cannot be initialized within structure declaration.


struct student
{
int rno =28;
char name[20]=“SUN”; Invalid
int tm =500;
flaot avg =90;
};

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 106


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Accessing the members of the structure:

Members of the structure can be accessed by writing structure variable name with member selection
operator (dot operator . ) and member name.
Syntax
structure variable . member;
Eg: s1. rno=28;
s1 . tm = 500;

Structure Initialization:

Like any other data type, a structure variable can be initialized. We can initialize a structure at
compile time and also we can initialize the structure members at run time.
 Compiletime initialization: One way to initialize structure members is direct initialization. struct
student s1 = { 28, “ SUN”, 500, 90};

Here, when initializing the structure directly like above, and then the order should be
maintained. That is the order of assigning values is same as the order of members declared in the
structure.

 And other way to initialize the structure members as follows:


struct student s1;
s1.rno =28;
strcpy (s1.name,”SUN”); s1.tm=500;
s1.avg =90;

 We can initialize structu remember satrun time by conside ring thes can statement as follows:
scanf (“%d%s%d%f”, &s1.rno, s1.name, &s1.tm,&s1,avg);

/* Example for structure declaration and initialization */

#include<stdio.h>
struct student
{
int rno;
char name[20];
int tm;
float avg;
};

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 107


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

int main()
{
struct student s1 = { 28,"SUN",450,89};
printf("\n Roll Number : %d",s1.rno);
printf("\n Name : %s",s1.name);
printf("\n Total : %d",s1.tm);
printf("\n Average: %f", s1.avg);
return 0;
}

Output:-
Roll Number: 28 Name:
SUN Total: 450
Average: 89.000000

Comparison and Copying of structure variables:

 We can copy one structure variable into another; it can be achieved by copying individual
members or entire structure at a time by using assignment statement.
Eg: struct student s1, s2;
s2 =s1;
 Comparison of structure variables for their equality and inequality purpose by using equality
operator
(==), and inequality operator (!=) is not allowed in all compilers. If it is necessary to compare two
structure variables then it is to follow individual structure member’scomparison

Array of structures

 We can declare an array of structures, where each element of the array represents a structure

variable.
 Eg: The total marks and average marks analysis of the marks report obtained by a class of 60
students is asfollow:
struct students[60];

Here s is an array of 60 elements to the structure student, or simply s is an array of structures.

 Array of structures allowed us to create an array of similar type of elements which themselves
are a collection of dissimilar datatype.
In an array of structures all elements of the array are stored in adjacent memory locations

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 108


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Eg /* Calculating the total marks of 3 students */

#include<stdio.h>
struct marks
{
int m1;
int m2;
int m3;
int m4;
};
int main( )
{
int sum=0, i;
struct marks s[3] = { {56,67,78,59}, {60,50,70,80}, {52,62,72,82} };
for(i=0;i<3;i++)
{
sum=0;
sum = sum + s[i].m1 + s[i].m2 + s[i].m3 + s[i].m4;
printf(“\n Total marks of %d = %d”, s[i], sum);
}
return 0;
}

Union:
Union is a concept borrowed from structures and therefore follows the same syntax as structures.
Union is a group of logically related data values of different type with the common name. And we
can use . (dot) operator to access individual members of a union as in structures.

Ex:
union
{
int m;
float x;
char c;
}code;

code.m=10;
code.x=12.05;
code.c=’A’;

However, there is major distinction between the union and structure is in terms of storage. In
structures each member has its own storage location, whereas all the members of a union use the
same location. Union can handle only one member at a time.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 109


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Ex: structure, union declarations are as follows:


struct item1 union item2
{ {
int m; intm;
floatx; floatx;
char c; charc;
} code1; } code2;

Differences between structure and union:

Structure Union
Collection of values of different Collection of values of different data types
datatypes
Declaration: Declaration:
struct <tag name> union <tag name>
{ {
Datatype1 member1; Datatype1 member1;
Datatype2 member2; Datatype2 member2;
. .
. .
. .
Datatype-nmembers- n; Datatype-n members-n;
}; };
The memory allocated for structure is The memory allocated for union is equal to
equal to its member’s total size. its member size, which allocation (Memory
(Memory is allocated only when a is allocated only when a union
structure variable is defined). variable is defined).
struct item1 union item2
{ {
Int m; float x; Int m; float x; char c;
char c; }u;
}s;
Memory allocated for s is 2+4+1=7 bytes. Memory allocated for u is 4 bytes

All the members can be accessed at a Only member can be accessed at a time.
time.

Values assigned to one member will not Values assigned to one member May cause
cause the change in other members. the change in value of other members.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 110


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

The usage of structure is efficient when The usage of union is efficient when
all Members are actively used in the members of it are not required to be
program accessed at the same time.

FILES
A File is a collection of records that can be accessed through the set of library functions. Record is
nothing but collection of fields of related data items. These files are stored on the disk and can be
accessed through file-handling functions provided by the C-standard library.

RollNo Name Total Marks Average


101 Pavan 450 70
102 Laxman 400 66
103 Dinesh 433 68
104 Simha 500 80
105 Sun 540 82

Eg: Here a file called “STUDENT.DAT” which is having 5 students’ records. And every record is
collection of 4 fields.

Types of I/O:There are numerous library functions available for I/O. these can be classified into two
broad categories:

a) Console I/O b) file I/O

Console I/O: Functions to receive input from keyboard and write output to VDU (monitor). The
screen and keyboard are called a console. Console I/O functions can be further classified into two
categories – formatted console I/O and unformatted console I/O. The basic difference between them
is that the formatted functions allow the input and output to be formatted as per requirements. The
different console I/O functions are as follows:

Formatted functions: The input function scanf( ) and the output function printf( ) are called
formatted console I/O functions. By using the format specifiers and escape sequence characters we
can use these functions to read/print required format ofinformation.

Unformatted functions:- The input functions like getch( ), getche( ), getchar( ) and gets( ) are called
unformatted input functions and putch( ),putchar( ), and puts( ) are unformatted output functions.
Each and every function is having its own syntax andmeaning.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 111


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

File I/O: Sometimes it is necessary to store the data in a manner that can be later retrieved and
displayed either in a part or in whole. This medium is usually a “file” on the disk. File I/O can be
handled by using different functions.

Formatted functions: The file input function fscanf( ) and the file output function fprintf( ) are called
formatted file I/O functions.

Unformatted functions: The input functions like getc( ), getw( ), and fread( ) are called unformatted
file input functions and putc( ), putw( ), and fwrite( ) functions are unformatted file output functions.
Each and every function is having its own syntax andmeaning.

File streams:- Stream is either reading or writing of data. The streams are designed to allow the user
to access the files efficiently. A stream is a file or physical device like key board, printer, monitor,
etc., The FILE object uses these devices. When a C program is started, the operating system is
responsible for opening three streams:standard input stream(stdin),standard output
stream (stdout), standard error(stderr).Normally the stdin is connected to the keyboard, the stdout
and stderr are connected to the monitor.

Text files and Binary files: C uses two types of files, text files and binary files.

Text files:- Text file is a file consists of a sequence of characters divided into lines with each line
terminated by a new line(‘\n’). A text file is writing using text stream. We can read and write text files
using different input/output functions. Formatted input/output (scanf/printf), character input/output
(getchar/putchar), and string input/output (gets/puts) functions. And these functions can work with
only text files. A text file contains only textual information like alphabets, digits, and special symbols.
In actuality the ASCII codes of these characters are stored in text files.

Ex: A good example of text file is any C program file.


Binary files: A binary file is a collection of data stored in the internal format of the computer. Unlike
text files, the data do not need to be reformatted as they are read and write rather, the data is stored in
the file in the same format that they are stored in memory. Binary files are read and write using binary
streams known as block input/output functions. Simply a binary file is merely a collection of bytes.
This collection might be a compiled version of a C program or music data stored in a wave file or a
picture stored in a graphic file.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 112


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Differences between Text and Binary files:

The major characteristics of text files are:


1. All data in a text file are human-readable graphiccharacters.
2. Each line of data ends with a newlinecharacter.
3. There is a special character called end-of-file (EOF) marker at the end of thefile. The
Major characteristics of binary filesare:

1. Data is stored in the same format as that is stored inmemory.


2. There are no lines or new linecharacters.
3. There is an end-of-filemarker.

Basic operations on files: The file consists of large, amount of data, which can be read or modified
depending on the requirement. The basic operations that can be performed on files are:

a) Opening a file: A file has to be opened before to read and write operations. This can be achieved
through fopen() function.
Syntax: FILE*fp;
fp=fopen(filename,mode);
Here is a pointer pointing to the file“filename”,which can be opened in specified mode. The fopen()
performs three tasks:
i) It searches the disk for opening the file.
ii) If file exists, it opens that file, if the file is not existing this function returns NULL in case of read
mode. In case of write mode, it creates a new file and in case of append mode it opens that
file for updating.
iii) It locates a file pointer pointing to the first character of thefile.
Ex: FILE *fp;
fp = fopen(“sample.txt”, ”r”);
if (fp==NULL)
printf(“file does not exist”);
else
{
.................
}
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 113
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

b)Reading/writing a file: Once the file is opened, the associated file pointer points to the starting of
the file. If the file is opened in writing mode, then we can write information by using different
functionslike:
putc ( ): Putting a character in to the file. It works with only character data type. One character
at a time can write into a file.
Ex: char ch =’a’;
putc (ch,fp);
putw ( ): putting or writing of an integer value to a file.
Ex: int x = 5;
putw(x,fp);
fprintf(): writing a group of values into a file.
Syntax:
fprintf (file pointer, ”control string”, list of arguments);
Ex: fprintf (fp, ”%s %d %d ”, name, rno,marks);
If the file is opened in reading mode, then we can read information from the file, i.e. using some
functions like:
getc ( ): getting a character from the file, or reading the file information character by character at a
time, upto the end of the file by using this function.
Ex: char ch;
ch = getc (fp);
getw( ): getting or reading integer value from a file. Ex: intx;
x = getw (fp);
fscanf ( ): This function is used to read the information from a file record-wise. It is used to read
more values at atime.
Ex: fscanf(fp,”%s%d%d”, name, &no,&marks);
Among all the above different file i/o functions, fscanf() and fprintf() are called as formatted i/o
functions. Printf and scanf are also called as formatted i/o functions.
c) closing a file: After reading/writing a file ,it is needed to close that file .fclose() is used to close a
file. It closes only one file at atime.
fclose (fp):-close a file which is pointed by fp.
fcloseall ( ):-close all opened files at a time.

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 114


DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

Different modes to open a file: The tasks performed by fopen() function when a file is opened in each of
these modes are as follows:
1. ”r” (Read) mode: opens the file that already exists for reading only. If the file doesn’t exist it
returnsNULL.
2. ”w”(write) mode: File is opened for writing, if the file exists its contents are over written
and if the file doesn’t exists , then a new file is created.It returns NULL if it is unable to open the
file.
f1=fopen(“sample.txt”, ”w”);
3. ”a”(append) mode: searches for the file, if it exists then appending new contents at the end
of the file.If a file doesn’t exist then a file with a specified name is created and ready to get
append oradd.
f1 = fopen (“sample.txt”, ”a”);
4. ”r+” (Read & write mode): This is for both reading and writing the data. If the file doesn’t
exist then it returnsNULL.
5. ”a+” (Append & Read) mode: The file can be read as well as data can beappended.
The two modes of binary files are:
1. “rb” (read binary) mode: Binary file is opened for readingonly.
2. “wb” (write binary) mode: Binary file opened for writingonly.

NOTE: While opening the file in text mode we can use either “r” or “rt”/ “w” or “wt”, but since text mode
is the default mode we usually drop the “t”.
/* PROGRAM TO COPY ONE FILE INTO ANOTHER FILE */
#include <stdio.h>
int main()
{
FILE *fs,*ft; char ch;
fs=fopen("sample.txt","r");
if (fs==NULL)
{
puts("cannot open source file\n");
exit(1);
}
ft=fopen("sample1.txt","w");
if (ft==NULL)
{
puts("cannot open target file");
exit(1);
MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 115
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING Programming for Problem Solving

}
while((ch=fgetc(fs))!=EOF)
fputc(ch,ft);
fclose(fs);
fclose(ft);
return 0;
}

/* EXAMPLE PROGRAM FOR ACCESSING BINARY FILES USING fwrite( ) , fread( ) FUNCTIONS */
#include<stdio.h>
int main()
{
int i,n;
FILE *fp1,*fp2,*fp3;
struct employ
{
char name[20];
int eno;
int bsal;
};
struct employ e[3];
fp1=fopen("EMP.DAT","wb");
for(i=0;i<3;i++)
{
printf("\n Enter name, num, and basic pay \n");
scanf("%s%d%d",e[i].name,&e[i].eno,e[i].bsal);
}
fwrite(&e,sizeof(e),3,fp1);
fclose(fp1);
fp1=fopen("EMP.DAT","rb");
fread(&e,sizeof(e),3,fp1);
for(i=0;i<3;i++)
{
printf("\n Name:%s",e[i].name);
printf("\n Number :%s",e[i].eno);
printf("\n basic pay :%s",e[i].bsal);
}
fclose(fp1);
return 0;
}

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY 116

You might also like