Computer Programming
Computer Programming
COMPUTER APPLICATIONS
COMPUTER PROGRAMMING
MCA612/MCA617
Kiran Gurbani
CHANDIGARH UNIVERSITY
Institute of Distance and Online Learning
Course Development Committee
Chairman
Prof. (Dr.) R.S. Bawa
Vice Chancellor, Chandigarh University, Punjab
Advisors
Prof. (Dr.) Bharat Bhushan, Director, IGNOU
Prof. (Dr.) Majulika Srivastava, Director, CIQA, IGNOU
Programme Coordinators & Editing Team
Master of Business Administration (MBA) Bachelor of Business Administration (BBA)
Co-ordinator - Prof. Pragya Sharma Co-ordinator - Dr. Rupali Arora
Master of Computer Applications (MCA) Bachelor of Computer Applications (BCA)
Co-ordinator - Dr. Deepti Rani Sindhu Co-ordinator - Dr. Raju Kumar
Master of Commerce (M.Com.) Bachelor of Commerce (B.Com.)
Co-ordinator - Dr. Shashi Singhal Co-ordinator - Dr. Minakshi Garg
Master of Arts (Psychology) Bachelor of Science (Travel & Tourism Management)
Co-ordinator - Dr. Samerjeet Kaur Co-ordinator - Dr. Shikha Sharma
Master of Arts (English) Bachelor of Arts (General)
Co-ordinator - Dr. Ashita Chadha Co-ordinator - Ms. Neeraj Gohlan
Master of Arts (Mass Communication and Bachelor of Arts (Mass Communication and
Journalism) Journalism)
Co-ordinator - Dr. Chanchal Sachdeva Suri Co-ordinator - Dr. Kamaljit Kaur
Academic and Administrative Management
Course Objectives:
To develop programming logic, use of programming instructions, syntax and program
structure.
To analyze the foundation of complex programming languages like C++ etc.
To practice the techniques for the development and application of problem-solving skills.
Syllabus
1 C Basics and Control structure:
1. Write a program that reads two nos. from key board and gives their addition, subtraction,
multiplication, division and modulo
2. The distance between two cities (In KM) is input through key board. Write a program to
convert and print this distance in meters, feet, inches and centimeters.
3. Write a C program to perform post and pre-increment, post and pre-decrement operations.
4. Write a program which implements the working of all Bit-wise operators
5. Write a program to select and print the largest of the three nos. using Nested-If-Else
statement.
6. Write a program to perform arithmetic operations using switch case.
7. Write a program to find sum of all integers greater than 100 & less than 200 and are
divisible by 5.
8. Write a C program to implement
x x2 x3
ex 1 ,
1! 2! 3!
2. Arrays, Strings, Functions and Structure:
1. Write a program to perform various matrix operations, Addition, Subtraction,
Multiplication, Transpose using switch-case statement
2. Programs based on string handling
3. Write a program using function to implement Pascal Triangle
4. Write a program that used user defined function Swap ( ) and interchange the value of
two variable.
5. Write a function prime that return 1 if it’s argument is prime and return 0 otherwise
6. Define a structure type, personal, that would contain person name, date of joining and
salary. Using this structure, write a program to read this information for one person
from the key screen.
7. Define a structure called cricket that will describe the following information: (a) Player
name (b) Team name (c) Batting average
Text Books:
1. Balaguruswamy (2017 ).Programming in ANSI C. New Delhi: McGraw-Hill.
2. Kanetkar, Y. (2014), Programming in C ANSI standard. New Delhi: BPB Publications.
3. Gottfried (2005).Programming with C. New York: Tata McGraw-Hill.
Reference Books:
1. Harrow K., Jones J. (1996). Problem Solving with C. London: Pearson Education.
2. Jeri R., Hanly, Koffman E.P. (2000). Problem Solving and Program Design in C. 3rd
Ed. Boston: Addison Wesley.
CONTENTS
Unit 2 Fundamentals of C 29 – 60
Structure:
1.0 Learning Objectives
1.1 Introduction
1.2 Basic Block Diagrams
1.3 Interconnection between Functional Components
1.4 Algorithm Flowcharts
1.5 Machines and Knowledge about Problem Solving
1.6 Stages of Program Development Process
1.7 Importance of Discipline in Programming
1.8 Summary
1.9 Key Words/Abbreviations
1.10 Learning Activity
1.11 Unit End Questions (MCQ and Descriptive)
1.12 References
1.1 Introduction
Being a modern-day kid you must have used, seen, or read about computers. This is because
they are an integral part of our everyday existence. Be it school, banks, shops, railway stations,
hospital or your own home, computers are present everywhere, making our work easier and faster
for us. As they are such integral parts of our lives, we must know what they are and how they
function. Let us start with defining the term computer formally.
Types of Computers:
Computers can be generally classified by size and power as follows, though there is considerable
overlap:
Personal computer: A small, single-user computer based on a microprocessor.
Workstation: A powerful, single-user computer. A workstation is like a personal
computer, but it has a more powerful microprocessor and, in general, a higher-quality
monitor.
Minicomputer: A multi-user computer capable of supporting up to hundreds of users
simultaneously.
Mainframe: A powerful multi-user computer capable of supporting many hundreds or
thousands of users simultaneously.
Supercomputer: An extremely fast computer that can perform hundreds of millions of
instructions per second.
Minicomputer
It is a midsize computer. In the past decade, the distinction between large minicomputers and
small mainframes has blurred, however, as has the distinction between small minicomputers and
workstations. But in general, a minicomputer is a multiprocessing system capable of supporting
from up to 200 users simultaneously.
Workstation
It is a type of computer used for engineering applications (CAD/CAM), desktop publishing,
software development, and other types of applications that require a moderate amount of computing
power and relatively high quality graphics capabilities. Workstations generally come with a large,
high-resolution graphics screen, at large amount of RAM, built-in network support, and a graphical
user interface. Most workstations also have a mass storage device such as a disk drive, but a special
type of workstation, called a diskless workstation, comes without a disk drive. The most common
operating systems for workstations are UNIX and Windows NT. Like personal computers, most
workstations are single-user computers. However, workstations are typically linked together to
form a local-area network, although they can also be used as stand-alone systems.
Personal Computer
It can be defined as a small, relatively inexpensive computer designed for an individual user.
In price, personal computers range anywhere from a few hundred pounds to over five thousand
pounds. All are based on the microprocessor technology that enables manufacturers to put an entire
CPU on one chip. Businesses use personal computers for word processing, accounting, desktop
publishing, and for running spreadsheet and database management applications. At home, the most
popular use for personal computers is for playing games and recently for surfing the Internet.
Personal computers first appeared in the late 1970s. One of the first and most popular personal
computers was the Apple II, introduced in 1977 by Apple Computer. During the late 1970s and
early 1980s, new models and competing operating systems seemed to appear daily. Then, in 1981,
IBM entered the fray with its first personal computer, known as the IBM PC. The IBM PC quickly
became the personal computer of choice, and most other personal computer manufacturers fell by
the wayside. P.C. is short for personal computer or IBM PC. One of the few companies to survive
IBM’s onslaught was Apple Computer, which remains a major player in the personal computer
marketplace. Other companies adjusted to IBM’s dominance by building IBM clones, computers
that were internally almost the same as the IBM PC, but that cost less. Because IBM clones used
the same microprocessors as IBM PCs, they were capable of running the same software. Over the
years, IBM has lost much of its influence in directing the evolution of PCs. Therefore, after the
release of the first PC by IBM the term PC increasingly came to mean IBM or IBM-compatible
personal computers, to the exclusion of other types of personal computers, such as Macintoshes. In
recent years, the term PC has become more and more difficult to pin down. In general, though, it
applies to any personal computer based on an Intel microprocessor, or on an Intel-compatible
microprocessor. For nearly every other component, including the operating system, there are several
options, all of which fall under the rubric of PC.
Today, the world of personal computers is basically divided between Apple Macintoshes and
PCs. The principal characteristics of personal computers are that they are single-user systems and
are based on microprocessors. However, although personal computers are designed as single-user
systems, it is common to link them together to form a network. In terms of power, there is great
variety. At the high end, the distinction between personal computers and workstations has faded.
High-end models of the Macintosh and PC offer the same computing power and graphics capability
as low-end workstations by Sun Microsystems, Hewlett-Packard, and DEC.
Tower Model
The term refers to a computer in which the power supply, motherboard, and mass storage
devices are stacked on top of each other in a cabinet. This is in contrast to desktop models, in which
these components are housed in a more compact box. The main advantage of tower models is that
there are fewer space constraints, which makes installation of additional storage devices easier.
Desktop Model
A computer designed to fit comfortably on top of a desk, typically with the monitor sitting on
top of the computer. Desktop model computers are broad and low, whereas tower model computers
are narrow and tall. Because of their shape, desktop model computers are generally limited to three
internal mass storage devices. Desktop models designed to be very small are sometimes referred to
as slimline models.
Notebook Computer
An extremely lightweight personal computer. Notebook computers typically weigh less than
6 pounds and are small enough to fit easily in a briefcase. Aside from size, the principal difference
between a notebook computer and a personal computer is the display screen. Notebook computers
use a variety of techniques, known as flat-panel technologies, to produce a lightweight and non-
bulky display screen. The quality of notebook display screens varies considerably. In terms of
computing power, modern notebook computers are nearly equivalent to personal computers. They
have the same CPUs, memory capacity, and disk drives. However, all this power in a small package
is expensive. Notebook computers cost about twice as much as equivalent regular-sized computers.
Notebook computers come with battery packs that enable you to run them without plugging them
in. However, the batteries need to be recharged every few hours.
Laptop Computer
A small, portable computer — small enough that it can sit on your lap. Nowadays, laptop
computers are more frequently called notebook computers.
Subnotebook Computer
A portable computer that is slightly lighter and smaller than a full-sized notebook computer.
Typically, subnotebook computers have a smaller keyboard and screen, but are otherwise equivalent
to notebook computers.
Hand-held Computer
A portable computer that is small enough to be held in one’s hand. Although extremely
convenient to carry, hand-held computers have not replaced notebook computers because of their
small keyboards and screens. The most popular hand-held computers are those that are specifically
designed to provide PIM (personal information manager) functions, such as a calendar and address
book. Some manufacturers are trying to solve the small keyboard problem by replacing the keyboard
with an electronic pen. However, these pen-based devices rely on handwriting recognition
technologies, which are still in their infancy. Hand-held computers are also called PDAs, palmtops
and pocket computers.
Palmtop
A small computer that literally fits in your palm. Compared to full-size computers, palmtops
are severely limited, but they are practical for certain functions such as phone books and calendars.
Palmtops that use a pen rather than a keyboard for input are often called hand-held computers or
PDAs. Because of their small size, most palmtop computers do not include disk drives. However,
many contain PCMCIA slots in which you can insert disk drives, modems, memory, and other
devices. Palmtops are also called PDAs, hand-held computers and pocket computers.
PDA
Short for personal digital assistant, a handheld device that combines computing, telephone/
fax, and networking features. A typical PDA can function as a cellular phone, fax sender, and
personal organizer. Unlike portable computers, most PDAs are pen-based, using a stylus rather
than a keyboard for input. This means that they also incorporate handwriting recognition features.
Some PDAs can also react to voice input by using voice recognition technologies. The field of PDA
was pioneered by Apple Computer, which introduced the Newton MessagePad in 1993. Shortly
thereafter, several other manufacturers offered similar products. To date, PDAs have had only
modest success in the marketplace, due to their high price tags and limited applications. However,
many experts believe that PDAs will eventually become common gadgets.
PDAs are also called palmtops, hand-held computers and pocket computers.
Input-Process-Output Model
Computer input is the data entered by the user for the storage, processing, and manipulation and
the output obtained after processing it, based on user’s instructions is called information. Raw
facts and figures which can be processed using arithmetic and logical operations to obtain information
are called data.
Logical operations — Examples include comparison operations like greater than, less
than, equal to, opposite, etc.
The corresponding figure for an actual computer looks something like this —
Memory Section
bus. A bus is a transmission path, made of a set of conducting wires over which data or information
in the form of electric signals, is passed from one component to another in a computer. The bus can
be of three types – Address bus, Data bus and Control Bus.
Following figure shows the connection of various functional components:
The address bus carries the address location of the data or instruction. The data bus carries
data from one component to another and the control bus carries the control signals. The system bus
is the common communication path that carries signals to/from CPU, main memory and input/
output devices. The input/output devices communicate with the system bus through the controller
circuit which helps in managing various input/output devices attached to the computer.
Characteristics of Computer
To understand why computers are such an important part of our lives, let us look at some of its
characteristics —
Speed — Typically, a computer can carry out 3-4 million instructions per second.
Accuracy — Computers exhibit a very high degree of accuracy. Errors that may occur
are usually due to inaccurate data, wrong instructions or bug in chips – all human errors.
Reliability — Computers can carry out same type of work repeatedly without throwing
up errors due to tiredness or boredom, which are very common among humans.
Versatility — Computers can carry out a wide range of work from data entry and ticket
booking to complex mathematical calculations and continuous astronomical
observations. If you can input the necessary data with correct instructions, computer
will do the processing.
Storage Capacity — Computers can store a very large amount of data at a fraction of
cost of traditional storage of files. Also, data is safe from normal wear and tear associated
with paper.
Definition of Algorithm
To write a logical step-by-step method to solve the problem is called algorithm, in other
words, an algorithm is a procedure for solving problems. In order to solve a mathematical or computer
problem, this is the first step of the procedure. An algorithm includes calculations, reasoning and
data processing. Algorithms can be presented by natural languages, pseudo code and flowcharts,
etc.
Definition of Flowchart
A flowchart is the graphical or pictorial representation of an algorithm with the help of different
symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms, we
can easily understand a program. The main purpose of a flowchart is to analyze different processes.
Several standard graphics are applied in a flowchart:
Terminal Box – Start/End
Input/Output
Process/Instruction
Decision
Connector / Arrow
The graphics above represent different part of a flowchart. The process in a flowchart can be
expressed through boxes and arrows with different sizes and colours. In a flowchart, we can easily
highlight a certain element and the relationships between each part.
Algorithm Flowchart
It is a procedure for solving problems. It is a graphic representation of a process.
The process is shown in step-by-step instruction. The process is shown in block-by-block
information diagram.
It is complex and difficult to understand. It is intuitive and easy to understand.
It is convenient to debug errors. It is hard to debug errors.
The solution is showcased in natural language. The solution is showcased in pictorial format.
It is somewhat easier to solve complex problem. It is hard to solve complex problem.
It costs more time to create an algorithm. It costs less time to create a flowchart.
Characteristics of Algorithm
Finiteness
Not all procedures can be called an algorithm. An algorithm should have the following
characteristics:
Unambiguous: Algorithm should be clear and unambiguous. Each of its steps (or
phases), and their inputs/outputs should be clear and must lead to only one meaning.
Input: An algorithm should have 0 or more well-defined inputs.
Output: An algorithm should have 1 or more well-defined outputs, and should match
the desired output.
Finiteness: Algorithms must terminate after a finite number of steps.
Feasibility: Should be feasible with the available resources.
Independent: An algorithm should have step-by-step directions, which should be
independent of any programming code.
Algorithms are mainly used for mathematical and computer programs, whilst flowcharts can
be used to describe all sorts of processes: business, educational, personal and of course algorithms.
So flowcharts are often used as a program planning tool to visually organize the step-by-step process
of a program. Here are some examples:
Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Step 4: If X is less than 20 then go back to step 2.
Flowchart:
Start
Initialize x = 0
Increment x by 1
Print x
YES
x > 20
No
End
Algorithm:
Step 1: Read temperature in Fahrenheit,
Step 2: Calculate temperature with formula C=5/9*(F-32),
Step 3: Print C,
Flowchart:
Fig. 1.6: Flowchart for Converting Temperature from Fahrenheit (ºF) to Celsius (!)
Algorithm:
Step 1: Input grades of 4 courses M1, M2, M3 and M4,
Step 2: Calculate the average grade with formula “Grade=(M1+M2+M3+M4)/4”
Step 3: If the average grade is less than 60, print “FAIL”, else print “PASS”.
Flowchart:
Fig. 1.7: Flowchart to Determine whether a Student passed the Exam or Not
Image Recognition
Remember how Facebook automatically tags your friends accurately when you upload a group
picture? Facebook started using machine learning to record the faces of the millions of Facebook
users and store them and identifies them with the faces in the picture you upload.
This face recognition technique from Facebook is just one application of machine learning in
image recognition. There are a lot of other applications in assembly lines in factories, in healthcare
applications and it has also been tested out with the driverless cars.
Customer Segmentation
This has been widely used by the marketing departments across all businesses. Customer
retention, churn prediction and lead generation have always been a major challenge for all marketers
but with the advancements in machine learning, marketers can now eliminate the guesswork and
get real-time, accurate results in customer segmentation from the past and current data. Marketers
can now get the complete analysis of each segment’s behaviour which can be leveraged in their
marketing campaigns for more specific results.
Customer Service
Customer service is yet another department that every company will have no matter the size
and the volume of the business. With the machine learning technology, businesses can now analyse
the past data from the customer support and provide better services to the customers while also
reducing the manpower.
Product Recommendations
This is majorly used in the e-commerce service sectors where the websites use machine learning
to tempt the customers in buying more things. Remember the section of ‘Also Bought’ in many
popular e-commerce websites where you will be displayed related items for the things you just
added to a cart?
This has been widely used by almost all online shopping websites where, based on the customer
historical data of the individual customer and the total gathered data, the top predicted things that
the customer will most likely buy will be displayed in the home page and in some sections of the
product pages too.
Machine learning can definitely make a major impact in solving the business problems if the
right approach and the right set of data are used.
Problem Definition:
The first step in the process of program development is the thorough understanding and
identification of the problem for which is the program or software is to be developed.
In this step the problem has to be defined formally.
All the factors like Input/output, processing requirement, memory requirements, error
handling, interfacing with other programs have to be taken into consideration in this
stage.
Program Design:
The next stage is the program design. The software developer makes use of tools like
algorithms and flowcharts to develop the design of the program.
Algorithm
Flowchart
Coding:
Once the design process is complete, the actual computer program is written, i.e. the
instructions are written in a computer language.
Coding is generally a very small part of the entire program development process and
also a less time consuming activity in reality.
In this process all the syntax errors, i.e., errors related to spelling, missing commas,
undefined labels etc. are eliminated.
For effective coding some of the guidelines which are applied are :
Use of meaningful names and labels of variables,
Debugging:
At this stage the errors in the programs are detected and corrected.
This stage of program development is an important process. Debugging is also known
as program validation.
Some common errors which might occur in the programs include:
Uninitialization of variables.
Reversing of order of operands.
Confusion of numbers and characters.
Testing:
The program is tested on a number of suitable test cases.
A test plan of the program has to be done at the stage of the program design itself.
This ensures a thorough understanding of the specifications.
The most trivial and the most special cases should be identified and tested.
It is always useful to include the maximum and minimum values of all variables as test
data.
Documentation:
Documentation is a very essential step in the program development.
Documentation help the users and the people who maintain the software.
This ensures that future modification if required can be done easily. Also it is required
during redesigning and maintenance.
Maintenance:
Updating and correction of the program for changed conditions and field experience is
accounted for in maintenance.
Maintenance becomes essential in following situations:
Change in specification,
Change in equipment,
Errors which are found during the actual execution of the program.
CU IDOL SELF LEARNING MATERIAL (SLM)
22 Computer Programming
1. Indentation
The code must be indented properly. Use tabspaces for indentation. Web developers can use 4
or 8 spaces instead of tabspace for web publishing (For example publishing a post in sanfoundry.com).
Indentation level 0 -> align to column 1
Indentation level 1 -> indent by 1 tab to the right of indentation level 0
Indentation level n+1 -> indent by 1 tab to the right of indentation level n
Indentation levels in a switch statement is to align the “switch” and “case” labels in the same
column. For example:
switch(var){
case’t’:
avar=10;
break;
case’u’:
avar=20;
break;
default:
break;
}
This applies to all non-function statement blocks (if, switch, for, while, do). E.g.:
switch(var){
case’t’:
avar=10;
break;
case’u’:
avar=20;
break;
default:
break;
}
However, there is one special case, namely functions: they have the opening brace at the
beginning of the next line.
1.8 Summary
An electronic data processing device, which requires input raw data for processing and
generates the output in desired form. It stores the data in its memory which can be
accessed any number of times for reference from its memory. It is made up of a lot of
electronics, software and mechanical parts.
A computer is divided into three basic units namely:
1. Input Unit
2. Central Processing Unit
3. Output Unit
Characteristics of Computer
1. Speed
2. Accuracy
3. Reliability
4. Versatility
5. Storage Capacity
Problem
It is a systematic approach to find and implement the solution to a problem.
5. Testing
6. Maintenance
1.12 References
1. https://www.includehelp.com/basics/computer-definition-parts-functions-and-its-
advantages.aspx
2. https://www.techoschool.com/MCA/Computer-Concepts-and-Programming-in-C/UNIT-
1-Basics-Of-Programming_Concept-of-Algorithm-and-Flowchart
3. http://newhorizonindia.edu/nhc_kasturinagar/wp-content/uploads/2018/07/PROBLEM-
SOLVING-TECHNIQUES-USING-C.pdf
4. Introduction to Computing Explorations in Language, Logic, and Machines by David
Evans
5. Introduction to computers by Rutendo Makaha
UNIT 2 FUNDAMENTALS OF C
Structure:
2.1 Introduction
C is a powerful general-purpose programming language. It is fast, portable and available in all
platforms.
If you are new to programming, C is a good choice to start your programming journey.
C was the basics language to write everything from operating systems (Windows and many
others) to complex programs like the Oracle database, Git, 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’.
It is essential to have a background in computer memory mechanisms because it is an important
aspect when dealing with the C programming language.
ANSI Committee
ISO Committee
C language has evolved from three different structured languages ALGOL, BCPL and B
Language. It uses many concepts from these languages and introduced many new concepts such as
data types, structure pointer.
In 1988, the language was formalized by American National Standard Institute (ANSI).
In 1990, a version of C language was approved by the International Standard Organization
(ISO) and that version of C is also referred to as C89.
Features of C language:
C is a structured programming language, which means that it allows you to develop programs
using well defined control structures (you will learn about control structures in the articles to
come), and provides modularity (breaking the task into multiple sub tasks that are simple enough to
understand and to reuse).
C is often called a middle-level language because it combines the best elements of low-level
or machine language with high-level languages.
Portable Structured
Simple
Mid-level
Memory
Management C Language Rich Library
Extensible
Pointers
Faster Recursion
(1) C is a Case Sensitive Language: Case sensitivity indicates that it differtiates the
characters either upper case or lower case based on their ASCII value.
(2) C is Mother of all Languages: C is mother of all languages because from C language
BASIC language is invented and from BASIC language Visual Basic and VB. Net
languages are invented. From C language C++, VC++, C#, J#, JAVA languages are
invented.
(3) Portable: C is highly portable this means that programs once written can be run on
another machines with little or no modification. if we write C program in turbo C we
can run same program in Borland or ANSI C without any modification on windows
platform as well as we can Run on gcc complier on Linux Platform.
(4) C is a Structured Programming Language: C is a structured programming language
since it follows fixed structure for writing any program, which should have compulsory
main() function in the structure.
(17) Efficient and Fast: Programs written in C are efficient and fast. This is due to its
variety of data type and powerful operators.
(18) Extensible: In C language, new features can be added by the programmer, hence it is
extensible.
(19) Recursion: In C, we can call the function within the function. It provides code
reusability for every function.
The C programming language is used for developing system applications that forms a major
portion of operating systems such as Windows, UNIX and Linux. Below are some examples of C
being used.
Database systems
Graphics packages
Word processors
Spreadsheets
Operating system development
Compilers and assemblers
Network drivers
Interpreters
4. In the Global Declaration section the variable used in more than one function can be
declared in Global section. Functions can be declared in this section.
5. Every C program consist of one or more function, one of which must be called the
main( ) function. The program will always begin by executing the main( ) function,
which may access other functions. Any other function definitions must be defined
separately, either ahead of or after main( ) function.
Output:
Programming is fun.
2.4 Comments
Comments are user defined help can be written anywhere in the program. Comments can be
written in documentation section. Comment section is not Executable by the compiler.
It is comment section, comments can be Single line comment or Multiline comment
The Single line comment can be written by // (double slash)
Example of Single Line Comment
// program to print hello
Example of Multiline comment
comment can be written by
/* ———
—————— */
# include<math.h>
#include<stdlib.h>
# is preprocessor directive which gives direction to the compiler that include specified header
file from Library to main( ) function program.
Header File Description
#include<stdio.h> It is standard input output header files, consist of standard input function
scanf() and standard output function printf()
#include<conio.h> It is console input output header file, consist of clrscr() function to clear
screen and getch() function to get character to see the output on screen.
#include<math.h> It is Math Medical Header File consist of all mathematical functions,
sin( ), cos( ), tan( ), sqrt( ).
#include<stdlib.h It is Standard Library File consist of Exit( ) function
#include<string.h> It is String Header File consist of string functions, strcmp( ), strlen( ),
strcpy( ), strrev( ), strcat( ).
#include<Ctype.h> All character handling functions are defined in this header file.functionsIt
consist of islower( ), isupper( ), isdigit( )
Data Types
Inbuilt Data Types User Defined Data Types
Numeric Structure
int long
non-numeric Union
character boolean
3. char – characters stored like type char, It stores single character, Sixe is 1 byte.
4. void: void is used for:
To specify the return type of a function when it is not returning any value.
To indicate an empty argument list to a function
2.7 Constants
Constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal.
There are enumeration constants as well. Constants are treated just like regular variables
except that their values cannot be modified after their definition.
You use a named constant when you want to assign a useful name for a value that will never
be changed during a program’s execution.
There are two simple ways in C to define constants:
Using #define preprocessor
Using const keyword
Constants
Numeric Character
Constants Constants
Single
Integer Real String
Character
Constants Constants Constants Constants
Integer Constants
An integer constant is an integer quantity which contains a sequence of digits. It should not
have a decimal point. Blanks and commas are not allowed within an integer constant. An integer
constant can be either +ve or -ve. The constant must lie within the range of the declared data type
(including qualifiers long, short, etc.).
Example of valid integer constants: 976 8987 5 -25 etc.
Example of invalid integer constants: 78.43 7-8 89,76 etc.
An integer constant can be either Decimal, Hexa Decimal or Octal. See the table below to
understand how these three different constants are defined in C.
Character Constant
A character constant is a character which is enclosed in single quotes. A character constant is
of size 1 byte and can contain only 1 character. A character can be an alphabet like a,b,A,C etc or a
special character like &,^, $, #,@ etc or a single digit from 0 through 9. It can also be an escape
sequence character like space ‘ ‘ or a null character ‘\o’ or a new line ‘\n’ etc.
Example: ‘A’ ‘a’ ‘b’ ‘8’ ‘#’ etc.
Each character has a corresponding ASCII value. ASCII value is the numeric code of a
particular character and is stored inside the machine’s character set.
String Constants
(a) A string constant is a collection of characters enclosed in double quotations “ “
(b) It may contain alphabets, digits, special characters and blank space.
Symbolic Constants
A symbolic constant is a name that substitutes for a sequence of characters. The characters
may represent a numeric constant, a character constant or a string constant. Thus, a symbolic constant
allows a name to appear in place of a numeric constant, a character constant or a string.
When a program is compiled, each occurrence of a symbolic constant is replaced by its
corresponding character sequence. Symbolic constants are usually defined at the beginning of a
program.
The symbolic constants may then appear later in the program in place of the numeric constants,
character constants, etc. that the symbolic constants represent. A symbolic constant is defined by
writing
#define name text
where name represents a symbolic name, typically written in uppercase letters, and text represents
the sequence of characters that is associated with the symbolic name.
Since a symbolic constant definition is not a true C statement, text does not end with a
semicolon. Moreover, if text were to end with a semicolon, this semicolon would be treated as
though it were a part of the numeric constant, character constant or string constant that is substituted
for the symbolic name.
Preprocessor is also called Macro Definition.
# define max 100
Hence # is a preprocessor directive which directs to the compiler that identifier max as a
token replaced with the string 100.
Hence in the program each occurrence of max is automatically replaced by 100.
Examples:
# define true 1
# define false 0
# define EoF – 1
# define product (x, y) ((x) * (y))
printf Function
The printf function writes data to standard output (usually, the terminal).
printf( ) function is available in stdio.h (standard input output header file)
Syntax of print() function:
printf(control_string,arg1,arg2,arg3,..., argn);
where control_string refers to a character string containing formatting information, and arg1, arg2,
etc., are arguments that represent the individual output data items.
The purpose of printf() is to display messages and values on the standard output using format
specifiers.
The general format of printf() is
(1) printf(<msg>); only for displaying the message.
(2) printf(<format string>, arguments); only for displaying the value of argument or variable
(3) printf(<format string><msg>,arguments)Displaying the message along with the value
of argument or variable.
Always the format string is defined within the ” ” ( double quotes)
Example 1:
printf(“Welcome to C programming”);
Will display
Welcome to C programming
printf() does not automatically print a new line. The programmer has to explicitly do it, by including
the \n in the format string.
scanf Function
The scanf function reads data from standard input (usually, the terminal).
scanf( ) function is available in stdio.h (standard input output header file)
For inputting values to your program you can either use getchar() or scanf(). The getchar()
returns a single character from a standard input device, the function does not require any argument
and it is restricted in the sense that only one character can be read-in at a time and no float/string
values can be read and the scanf() function allows more flexible input.
Syntax of scanf() is:
scanf(control_string, arg1, arg2, arg3, ..., argn);
where control_string refers to a character string containing certain required formatting information,
and arg1, arg2, etc., are arguments that represent the individual input data items.
Example:
scanf(”%d”, &n);
where the variable n has been declared as an integer.
The & is mandatory and stands for “address of”.
scanf(”%d %d”, &a, &b);
where a,b are integers.
2.9 Variables
Variable is a place holder which occupies memory space to store variable value, or a constant
value, integer, float, character, string value.
In C, all variables must be declared before they are used in executable statements.
In C language all variables are to be declared first in local declaration section, i.e., at the
beginning of scope.
Variable Definition
Declaring and Initializing C Variable:
Variables should be declared in the C program before to use.
Memory space is not allocated for a variable while declaration. It happens only on
variable definition.
Variable initialization means assigning a value to the variable.
1. Local Variable in C:
The scope of local variables will be within the function only.
These variables are declared within the function and can’t be accessed outside the
function.
2. Global Variable in C:
The scope of global variables will be throughout the program. These variables can be
accessed from anywhere in the program.
This variable is defined outside the main function. So that, this variable is visible to
main function and all other sub-functions.
Storage classes
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope and
lifetime of a variable.
Every time a variable is defined, its type is mentioned. Along with it, its ‘storage class’
is also required. In other words, not only do all variables have a data type, they also
have a ‘storage class’, i.e., Scope.
Most of the variables defined have only data type and a default storage class is used. If
the storage class of a variable is not specified in its declaration, the compiler will assume
a storage class depending on the context in which the variable is used.
In C programming language, a variable name identifies some physical location within
the computer where the variable’s value is stored.
There are basically two kinds of locations in a computer — Memory and CPU registers.
It is the variable’s storage class that determines in which of these two locations the
value is stored.
The storage class of a variable also signifies:
(a) Where it will be stored.
(b) What will be the initial value; default value
(c) What is the scope; availability
(d) What is the life, i.e., how long would the variable exist.
There are 4 types of storage class:
1. Automatic storage class (Local)
2. External storage class (Global)
2. Static storage class
4. Register storage class
The scope and life of the variable is local to the block it’s defined. The moment the control
comes out of the block in which the variable is defined, the variable and its value is forever lost.
Syntax:
int main()
{
int n; // n is a local varible to main() function
... .. ...
}
void func()
{
int n1; // n1 is local to func() fucntion
}
Example:
void main()
{
int var1; //default storage class : auto
auto int var2; //storage class explicitly mentioned
printf(“\n %d %d”, var1, var2);
}
In the above example, both the variables are defined with the same storage class. Storage
class for var1 is not mentioned and so its initialized with default, i.e., auto. ‘auto’ can only be used
within functions, i.e., local variables.
Output of the above program is:
1258 1547
Their garbage values, as the variable were not initialized. So always make it a point that you
initialize the automatic variables properly, otherwise you are likely to get unexpected results.
Output:
n=7
Suppose, a global variable is declared in file1. If you try to use that variable in a different
file file2, the compiler will complain. To solve this problem, keyword extern is used in file2 to
indicate that the external variable is declared in another file.
3. Static Variable
A static variable is declared by using keyword static. A variable defined to have static storage
class is stored in memory and initialized to a default value zero. The static storage class instructs
the compiler to keep a local variable in existence during the lifetime of the program instead of
creating and destroying it each time it comes into and goes out of scope. Therefore, making local
variables static allows them to maintain their values between function calls. The static modifier
may also be applied to global variables. When this is done, it causes that variable’s scope to be
restricted to the file in which it is declared.
Syntax:
static int i;
The value of a static variable persists until the end of the program.
Output:
0
5
During the first function call, the value of c is equal to 0. Then, its value is increased by 5.
During the second function call, variable c is not initialized to 0 again. It’s because c is a
static variable. So, 5 is displayed on the screen.
4. Register Variable
The register keyword is used to declare register variables. Register variables were supposed
to be faster than local variables. Local variable defined using register storage class is stored in CPU
registers instead of memory. They are by default initialized to garbage value. This means that the
variable has a maximum size equal to the register size (usually one word) and can’t have the unary
‘&’ operator applied to it (as it does not have a memory location). The scope and life of the variable
is same as auto variables, i.e., is local to the block it’s defined.
Why would a variable be defined with this storage class? The answer is to have quick access.
For example, the counter variables may be defined with register storage class. It should also be
noted that defining ‘register’ does not mean that the variable will be stored in a register. It means
that it might be stored in a register depending on hardware and implementation restrictions like
number of free registers.
void main()
{
register int i;
for(i=0;i<3;i++)
printf(“\n %d”, i);
}
Not every type of variable can be stored in a CPU register. For example, if the microprocessor
has 16-bit register then they cannot hold float and double variables which require 4 or 8 bytes
respectively. In this case the compiler would treat the variable as auto storage class.
However, modern compilers are very good at code optimization and there is a rare chance that
using register variables will make your program faster. Unless you are working on embedded system
where you know how to optimize code for the given application, there is no use of register variables.
2.10 Summary
C programming is a general-purpose, procedural, imperative computer programming language
developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX
operating system. C is the most widely used computer language. It keeps fluctuating at number one
scale of popularity along with Java programming language, which is also equally popular and most
widely used among modern software programmers.
Features of C Language:
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
Datatypes in C
Data types specify how we enter data into our programs and what type of data we enter. C
language has some predefined set of data types to handle various kinds of data that we can use in
our program. These datatypes have different storage capacities.
C language supports 2 different type of data types:
1. Primary data types:
These are fundamental data types in C namely integer(int), floating point(float),
character(char) and void.
2. Derived data types:
Derived data types are nothing but primary datatypes but a little twisted or grouped
together like array, stucture, union and pointer.
Data type determines the type of data a variable will hold. If a variable x is declared as int. it
means x can hold only integer values. Every variable which is used in the program must be declared
as what data-type it is.
Execution Flow
1. C program (source code) is sent to preprocessor first. The preprocessor is responsible
to convert preprocessor directives into their respective values. The preprocessor generates
an expanded source code.
2. Expanded source code is sent to compiler which compiles the code and converts it
into assembly code.
3. The assembly code is sent to assembler which assembles the code and converts it into
object code. Now a simple.obj file is generated.
4. The object code is sent to linker which links it to the library such as header files. Then
it is converted into executable code. A simple.exe file is generated.
5. The executable code is sent to loader which loads it into memory and then it is executed.
After execution, output is sent to console.
ch=’G’;
i=ch=’A’;
printf(“%d”,i);
(a) 5 (b) 7n
(c) 8 (d) 6
Answers : 1. (a), 2. (d), 3. (b), 4. (d)
2.14 References
1. https://www.studytonight.com/c/datatype-in-c.php
2. https://www.programiz.com/c-programming
3. https://www.tutorialspoint.com/cprogramming/c_data_types.htm
4. http://www-personal.acfr.usyd.edu.au/tbailey/ctext/ctext.pdf
5. http://www.vssut.ac.in/lecture_notes/lecture1424354156.pdf
Structure:
3.0 Learning Objectives
3.1 Introduction
3.2 Arithmetic Operators
3.3 Relational Operators
3.4 Logical Operators
3.5 Assignment and Compound Assignment Operators
3.6 Unary Operators and Increment and Decrement Operator
3.7 Conditional Operator or Ternary Operator
3.8 Bitwise and Comma Operator
3.9 Expressions and Evaluation of Expression
3.10 Type Conversion
3.11 Precedence and Associatively (Order of Evaluation)
3.12 I/O Functions: printf( ), scanf( )
3.13 Summary
3.14 Key Words/Abbreviations
3.15 Learning Activity
3.16 Unit End Questions (MCQ and Descriptive)
3.17 References
3.1 Introduction
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions.Operators, functions, constants and variables are combined together to form expressions.
Here you will learn about Operators in C Programming (all valid operator’s available in C),
expressions (combination of operators, variables and constants) and precedence of operators (which
operator has higher priority and which operator has lower priority).
The variables or constants on which operators are operated are known as operands. The
arithmetic in C can be of three types:
x_float/y_int = result_float
x_float/y_float = result_float
(c) Mixed Mode Arithmetic: C++ permits us to mix integer operand with real operand.
When one operand is real and the other is integer, the expression is called mixed mode
arithmetic expression, i.e., if either of the operand is of the real type, then only real
operation is performed and result is always a real number.
For e.g.,
15/10.0 = 1.5
4 + 3.5 = 7.5
c = a-b;
printf(“a-b = %d \n”,c);
c = a*b;
printf(“a*b = %d \n”,c);
c=a/b;
printf(“a/b = %d \n”,c);
c=a%b;
printf(“Remainder when a divided by b = %d \n”,c );
getch();
}
Output:
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The operators +, - and * computes addition, subtraction and multiplication respectively as
expected.
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.
It is because both variables a and b are integers. Hence, the output is also an integer. The
compiler neglects the term after decimal point and shows answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder
is 1. The % operator can only be used with integers.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,
a/b = 2.5 // Because both operands are floating-point variables
a/d = 2.5 // Because one operand is floating-point variable
c/b = 2.5 // Because one operand is floating-point variable
c/d = 2 // Because both operands are integers
Expression Result
3>4 false
6<=2 false
10 > – 32 True
(23 * 7) > = (–67 + 89) True
The relational operators are self-explanatory. As far as the explanation of the logical operators
is concerned. Consider the following. Any operator which uses two characters as a symbol should
have no space between the two characters, that is ==, It will erroneous if it is written as = =.
A relational operator checks the relationship between two operands. If the relation is true, it
returns 1 if the relation is false, it returns value 0.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0
(a < b) || (b > c)
true || false
true
Logical Negation Operator (!): A logical expression can be changed from false to true or
from true to false with negation operator (!)
Situation Result
! (true) false
! (false) true
Assignment Operator
Assignment operators are used to assign the result of an expression or constant to variable.
The assignment operators can be used within any valid expression, the usual assignment
operator is ‘=’.
variable_Name = constant or expression;
The arithmetic expression is a combination of variables, constants and operators
E.g., x = a + b;
z = 0;
final = 100;
During the assignment operator the value of expression of right hand side is assigned to left
side variable.
During the assignment operator the value of the expression on right hand side is computed
and is assigned to the variable on the left hand side.
value += 3
The += operator adds the value of the right operand to the value of the left operand and stores
the result in the left operand’s variable.
In addition to the usual assignment operator ‘=’. C++ has short hand assignment operators of
the form.
variable op = expression;
where op is C language is binary arithmetic operator
Compound assignment operator Sample expression Explanation Assigns
Assume: c = 4, d = “He”
+= c += 7 c= c+ 7 11 to c
-= c -= 3 c= c-3 1 to c
*= c *= 4 c=c*4 16 to c
/= c /= 2 c=c/2 2 to c
\= c \= 3 c= c\3 1 to c
^= c ^= 2 c= c^ 2 16 to c
&= d &= “llo” d = “kiran” & “llo” “Hello” to kiran
Unary Minus(-)
The symbol is the same as used for binary subtraction. Unary minus is used to indicate or
change the algebraic sign of a value. For example:
a=-75;
b=-a;
assign the value –75 to a and the value 75(-(-75)) to b. The minus sign used in this way is called the
unary operator because it takes just one operand.
Strictly speaking, there is no unary + in C.
Syntax
++ // increment operator
— // decrement operator
Increment and decrement operators cannot apply on constant.
x= 4++; // gives error, because 4 is constant
C includes two useful operators, which are generally not found in other computer languages.
These are the increment operator (+ +) and the decrement operator (—). The operator ++ adds 1 to
its operand, whereas the operator – subtracts 1 from its operand.
To be precise,
x = x + 1; can be written as x++; and
x = x –1; can be written as x—;
Both these operators may either precede or follow the operand, i.e.,
x = x + 1; can be represented as
1] ++x; or x++;
The first case is known as prefix while the later one is known as postfix operator.
Similar operations hold true for – operator. Ie. 1] - –x or x - -
The difference between pre and post-fixing the operator is useful when it is used in an
expression. When the operator precedes the operand, C performs the increment or decrement
operation before using the value of the operand. If the operator follows the operand, the value of
the operand is used before incrementing or decrementing it.
Example:
x = 1;
i = i +(+ + x);
In the above expression, the value of x, which is added to i is 2
On the other hand,
x = 1;
i = i +(x + +);
x =1 is added to i; in both the cases the value of x after evaluating the expression is 2.
Syntax
++ variable;
Example pre-increment
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=++i;
printf(“x: %d”,x);
printf(“i: %d”,i);
getch();
}
Output:
x: 11
i: 11
In above program first increase the value of i and then used value of i into expression.
post-increment (variable ++)
In post-increment first value of variable is used in the expression (initialize into another variable)
and then increment the value of variable.
post-increment (variable ++)
In post-increment first value of variable is used in the expression (initialize into another variable)
and then increment the value of variable.
Syntax
variable ++;
Example post-increment
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i++;
printf(“x: %d”,x);
printf(“i: %d”,i);
getch();
}
Output:
x: 10
i: 11
In above program first used the value of i into expression then increase value of i by 1.
Pre-decrement (— variable)
In pre-decrement first decrement the value of variable and then used inside the expression
(initialize into another variable).
Syntax
— variable;
Example pre-decrement
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=—i;
printf(“x: %d”,x);
printf(“i: %d”,i);
getch();
}
Output:
x: 9
i: 9
In above program first decrease the value of i and then value of i used in expression.
post-decrement (variable —)
In Post-decrement first value of variable is used in the expression (initialize into another
variable) and then decrement the value of variable.
Syntax
variable —;
Example post-decrement
#include<stdio.h>
#include<conio.h>
void main()
{
int x,i;
i=10;
x=i—;
printf(“x: %d”,x);
printf(“i: %d”,i);
getch();
}
Output:
x: 10
i: 9
In above program first used the value of x in expression then decrease value of i by 1.
Example:
(1) if (i % 2 = = 0)
even = true
else
even = false
even = (i % 2 = = 0)? true : false;
(2) if (i > j)
max = i
else
man = j
max = (i > j)? i : j;
(3) if (x > y)
x=x+3
else
x=x–3
x = (x > y)? x + 3 : x – 3;
Output:
If this year is leap year, enter 1. If not enter any integer: 1
Number of days in February = 29
Bitwise Operators
During computation, mathematical operations like: addition, subtraction, addition and division
are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
(a) Bitwise AND: The bitwise AND operation will be carried out between the two bit patterns
of the two operands.
x 5 0101
y 2 0010
x&y 0 0000
a 6 0110
b 3 0011
a&b 2 0010
To generate a 1 bit in the result, bitwise AND need a one in both numbers.
Let us suppose the bitwise AND operation of two integers 12 and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001
—————
00001000 = 8 (In decimal)
Output:
Output = 8
(b) Bitwise OR: The bitwise OR operations result 1 if any one of the bit value is 1.
Bitwise OR
Variable Value Binary pattern
x 5 0101
y 2 0010
x|y 7 0111
a 6 0110
b 1 0001
a|b 7 0111
Bitwise OR operator |
The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C
Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)
Output:
Output = 29
(c) Bitwise Exclusive OR: The bitwise exclusive OR will be carried out by the notation ^. To
generate a 1 bit in the result, a bitwise exclusive OR needs a one in either number but not both.
Bitwise EX – OR
Variable Value Binary pattern
x 5 0101
y 2 0011
x^y 25 11001
a 6 0110
b 3 0011
a^b 216 11011000
Output:
Output = 21
(d) Bitwise complement: The complement operator ~ switches all the bits in a binary pattern,
that is all the zeroes become ones and all ones become zeroes. It acts as a 1’s complement.
x 23 0001 0111
~x 132 1110 1000
y Ff 1111 1111
~y 00 0000 0000
Output:
Complement = -36
Output = 11
0010 0001
shift *** 01000010
shift *** 10000100
shift *** 00001000
x << 3 is 00001000
Left Shift Operator: Left shift operator shifts all bits towards left by certain number of
specified bits. It is denoted by <<.
printf(“\n”);
comma (,) works as a separator and an operator too and its behaviour is little different
according to the place where it is used.
(1) Comma (,) as separator
While declaration multiple variables and providing multiple arguments in a function, comma
works as a separator.
Example:
int a,b,c;
In this statement, comma is a separator and tells to the compiler that these (a, b, and c)
are three different variables.
(2) Comma (,) as an operator
Sometimes we assign multiple values to a variable using comma, in that case comma is known
as operator.
Example:
a = 10,20,30;
b = (10,20,30);
In the first statement, value of a will be 10, because assignment operator (=) has more
priority more than comma (,), thus 10 will be assigned to the variable a.
In the second statement, value of b will be 30, because 10, 20, 30 are enclosed in braces,
and braces has more priority than assignment (=) operator. When multiple values are given
with comma operator within the braces, then right most value is considered as result of the expression.
Thus, 30 will be assigned to the variable b.
Consider the program:
#include <stdio.h>
int main()
{
int a,b;
a = 10,20,30;
b = (10,20,30);
Percentage=(marks/total)*100;
}
Control statements are used to create special program features, such as logical tests, loops
and branches. Many control statements require that other statements be embedded within them.
for(i=1;i<=10;i++)
{
printf(“%d”,i);
}
5. Else, if one of the operand is long int, and the other is unsigned int, then
(1) if a long int can represent all values of an unsigned int, the unsigned int is converted
to long int.
(2) otherwise, both operands are converted to unsigned long int.
6. Else, if either operand is long int then others will be converted to long int.
7. Else, if either operand is unsigned int then others will be converted to unsigned int.
It should be noted that the final result of expression is converted to type of variable on left
side of assignment operator before assigning value to it.
Also, conversion of float to int causes truncation of fractional part, conversion of double to
float causes rounding of digits and the conversion of long int to int causes dropping of excess
higher order bits.
++ — Prefix increment/decrement
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
*/% Multiplication/Division/Modulus left-to-right
+- Addition/Subtraction left-to-right
Note 1: Parentheses are also used to group sub-expressions to force a different precedence; such
parenthetical expressions can be nested and are evaluated from inner to outer.
Note 2: Postfix increment/decrement have high precedence, but the actual increment or decrement of
the operand is delayed (to be accomplished sometime before the statement completes execution).
So in the statement y = x * z++; the current value of z is used to evaluate the expression,
(i.e., z++ evaluates to z) and z only incremented after all else is done. See postinc.cfor another
example.
Associativity specification is redundant for unary operators and is only shown for completeness:
unary prefix operators always associate right-to-left (sizeof ++*p is sizeof(++(*p))) and unary
postfix operators always associate left-to-right (a[1][2]++ is ((a[1])[2])++). Note that the associativity
is meaningful for member access operators, even though they are grouped with unary postfix
operators: a.b++ is parsed (a.b)++ and not a.(b++).
printf Function
The printf function writes data to standard output (usually, the terminal).
printf( ) function is available in stdio.h (standard input output header file)
Syntax of print() function:
printf(control_string, arg1, arg2, arg3, ..., argn);
where control_string refers to a character string containing formatting information, and arg1,
arg2, etc., are arguments that represent the individual output data items.
The purpose of printf() is to display messages and values on the standard output using format
specifiers.
The general format of printf() is
(1) printf(<msg>); only for displaying the message.
(2) printf(<format string>, arguments); only for displaying the value of argument or variable
(3) printf(<format string> <msg>, arguments) Displaying the message along with the value
of argument or variable.
Always the format string is defined within the " " ( double quotes)
Example 1:
printf("C is fun");
Will display
C is fun
printf() does not automatically print a new line. The programmer has to explicitly do it, by
including the \n in the format string.
Example 2:
printf("The rain in Spain");
printf("stays mainly on the plains");
Output:
The rain in Spain stays mainly on the plains.
If you change the above to:
printf("The rain in Spain");
printf("\nstays mainly on the plains");
Output:
The rain in Spain
Stays mainly on the plains
The control string consists of individual groups of characters, with one character group for
each output data item. In its simplest form, each character group consists of a percent sign (%),
followed by a conversion character which controls the format of the corresponding data item.
The most useful conversion characters are as follows:
The format string can contain format specifiers like scanf().
%d stands for integer numbers
%c stands for character
%f stands for float
%s stands for string
%o stands for octal
%x stands for hexadecimal
Example 1:
void main()
{
int n;
n = 7;
printf("There are %d days in a week. \n",n);
}
Output:
There are 7 days in a week.
Example 2:
void main()
{
int num=0;
printf("Enter number :");
scanf("%d\n" &num);
printf("The number is %d.\n",num);
}
Output:
Enter number: 20
The number is 20.
Example 3:
void main()
{
int num=0;
printf("Enter number :");
scanf("%d\n" &num);
printf("The number is %4d.\n",num);
}
Output:
Enter number: 12
The number is 12
Indicates a Blank Space
Example 4:
void main()
{
int a, b,c;
a= 10;
b=20;
c = a*b;
printf("The Product of Two numbers %d & %d is = %d \n", a,b,c);
}
Output:
The Product of Two numbers 10 and 20 is = 200
scanf Function
The scanf function reads data from standard input (usually, the terminal).
scanf( ) function is available in stdio.h (standard input output header file)
For inputting values to your program you can either use getchar() or scanf(). The getchar()
returns a single character from a standard input device, the function does not require any argument
and it is restricted in the sense that only one character can be read-in at a time and no float/string
values can be read and the scanf() function allows more flexible input.
Syntax of scanf() is:
scanf(control_string, arg1, arg2, arg3, ..., argn);
where control_string refers to a character string containing certain required formatting
information, and arg1, arg2, etc., are arguments that represent the individual input data items.
Example:
scanf("%d", &n);
where the variable n has been declared as an integer.
The & is mandatory and stands for "address of".
scanf("%d %d", &a, &b);
where a,b are integers.
scanf("%f %d", &a, &f);
where a is a float and f is an integer
The first argument to the scanf() function is a format string which contains FORMAT
SPECIFIERS. Always the format string is defined within " " (double quotes).
The control string consists of individual groups of characters, with one character group for
each data input item. In its simplest form, each character group consists of a percent sign (%),
followed by a set of conversion characters which indicate the type of the corresponding data item.
These can be any of the following:
%d stands for integer numbers
%c stands for character
%e stands for floating-point value with an exponent
%f stands for float
%i stands for signed decimal integer
%u stands for unsigned decimal integer
%s stands for string
%o stands for octal
%x stands for hexadecimal
These all % characters are known as Modulus Operator
3.13 Summary
Operators form expressions by joining individual constants, variables, array elements. C
includes a large number of operators which fall into different categories. They are as follows:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit-wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
Type Conversion: When variables and constants of different types are combined in an
expression then they are converted to same data type. The process of converting one predefined
type into another is called type conversion or type casting.
Type conversion in C can be classified into the following two types:
(a) Implicit Type Conversion
(b) Explicit Type Conversion
Operators Precedence in C: Operator precedence determines the grouping of terms in an
expression and decides how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has a higher precedence than the addition
operator.
5. What are unary operators? How many operands are associated with a unary operator?
State purpose of each.
6. Describe two different ways to utilize the increment and decrement operators. How do
the two methods differ?
7. Explain conditional or ternary operators with suitable example.
8. Explain Bitwise operators and its types and comma operators with suitable example.
9. Describe Precedence and order of evaluation used in C Programming language.
10. Explain Statements and different types of statements in C programming language.
11. Describe Automatic and explicit type conversion with suitable example.
12. Explain Use of Formatted input and output functions with format specifers used. Illustrate
with some suitable examples.
3.17 References
1. http://download.nos.org/cca/cca11.pdf
2. https://www.programtopia.net/c-programming/docs/operators-expressions
3. https://fresh2refresh.com/c-programming/c-operators-expressions/
4. https://faculty.psau.edu.sa/filedownload/doc-13-pdf-
b790198028e7b75cde4173bc1c825c64-original.pdf
5. https://www.tenouk.com/download/pdf/Module3.pdf
CU IDOL SELF LEARNING MATERIAL (SLM)
Decision and Loop Control Structure 99
Structure:
4.0 Learning Objectives
4.1 Introduction
4.2 Control Statements for Decision Making
4.3 Branching: If Statement
4.4 Looping: While Loop
4.5 Jump Statements
4.6 Summary
4.7 Key Words/Abbreviations
4.8 Learning Activity
4.9 Unit End Questions (MCQ and Descriptive)
4.10 References
4.1 Introduction
In any programming language, there is a need to perform different tasks based on the condition.
For example, consider an online website, when you enter wrong id or password it displays error
page and when you enter correct credentials then it displays welcome page. So there must be a logic
in place that checks the condition (id and password) and if the condition returns true it performs a
task (displaying welcome page) else it performs a different task (displaying error page).
Using decision control statements we can control the flow of program in such a way so that it
executes certain statements based on the outcome of a condition (i.e., true or false).
Sequential
Sequential means the program flow moves from one statement to the next, and then to the
later and then to the one after and so on.
It is the simplest form of structures, and it is not likely to be sequential structuring when
developing complex programs.
Selection (Decision)
Selection structures make decisions and perform commands according to the desicion making.
Selection structures involve “if statements” which are statements like “if this, then do that” and “if
not this, then do that”.
With “if statements”, we can also include “nested if statements”, which are “if statements”
inside other “if statements”. Another form of selection structures is called a “switch statement”,
which is very powerful for certain situations, but not for others. “Switch statements” focus on the
value of a particular variable and perform different “cases” accordingly.
Repetition (Loops)
Repetition structures are used when something needs to be repeated a certain number of times
through the use of “loops”. A loop is simply a statement that completes iterations or cycles until a
certain value is reached and then execution moves to the next executable statement.
For instance, if you were to ask the user to enter ten values; to find the average of the numbers,
you could write a loop that would continue letting the user enter numbers until ten numbers had
been entered.
Flowchart of if Statement
Example:
#include<stdio.h>
void main()
{
int x =20;
int y =22;
if(x<y)
{
printf("Variable x is less than y");
}
getch( );
}
Output:
Variable x is less than y
Syntax of if...else
if (testExpression)
{
// codes inside the body of if
}
else
{
// codes inside the body of else
}
If test expression is true, codes inside the body of if statement is executed and, codes inside
the body of else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes
inside the body of if statement is skipped.
Test False
expression
True
Statement just
below if.. else
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output:
Enter an integer: 7
7 is an odd integer.
When user enters 7, the test expression ( number%2 == 0 ) is evaluated to false. Hence, the
statement inside the body of else statement printf("%d is an odd integer"); is executed and the
statement inside the body of if is skipped.
printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}
// if both test expression is false
else
{
printf("Result: %d < %d",number1, number2);
}
getch( );
}
Output:
Enter two integers: 12
23
Result: 12 < 23
default:
stmt-list;
}
During execution, the expression is evaluated. If the value of the expression matches label-1,
then stmt-list-1 will be executed. If not, execution will move on to check label-2 and so on. If no
labels match the expression, default will be executed. Inside each case and at the end of every
statement list (except default) there must be a break statement, which terminates the innermost
enclosing switch or loop statement.
Here are some final notes about switch statements: the expression being tested must result in
an integral value (int or single char), case labels must be integral constants (either literals or named
constants), each label within a switch should be unique, and each stmt-list may contain 0 or more
statements which do not need to enclosed with curly braces { }.
switch_expression
Equal
Case 1 Case 1 code block
Not Equal
Equal
Case 2 Case 2 code block
Not Equal
Equal
Case 3 Case 3 code block
Not Equal
Example:
void main()
{
int i=2;
switch(i)
{
case1:
printf("Case1 ");
break;
case2:
printf("Case2 ");
break;
case3:
printf("Case3 ");
break;
case4:
printf("Case4 ");
break;
default:
printf("Default ");
}
getch( );
}
Output:
Case2
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int count=1;
while(count <=5)
{
printf("%d ", count);
count++;
}
getch();
}
Output:
12345
Step 1: First counter variable count has initialized with value 1 and then it has been tested
for the condition.
Step 2: If condition holds true then the body of the while loop gets executed otherwise,
control comes out of the loop.
Step 3: Count value was incremented using ++ operator, then it has been tested again for
the loop condition. It keeps happening until the condition returns to false.
A do while loop statements will be performed and then checks the test expression of the loop.
do
{
// codes or statements
} while (testExpression);
The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the loop body is executed
again. This process goes on until the test expression is evaluated to 0 (false).
When the test expression is false (nonzero), the do...while loop is terminated.
The statement in the loop may be single or complex. Complex statements must be enclosed
with curly braces { }. Let's look at a couple of examples of do while loops.
Body of Loop
true Test
expression
false
Statement just
below Loop
{
int a;i;
a=5;
i=1;
do
{
printf("%d\t",a*i);
i++;
}
while (i <= 10);
getch();
}
Output:
5 10 15 20 25 30 35 40 45 50
The for loop is commonly used when the number of iterations is known.
In general, a for loop can be written as an equivalent to a while loop and vice versa.
for (expression1; expression2; expression3)
statement;
is equivalent to...
expression1;
while (expression2)
{
Statements;
expression3;
}
Initialization
False
For loop
condition
True
Increment/Update
Statements
Example:
…
int i;
for(i=1; i<=4; i++)
{
printf("hello, World");
}
…
Output:
hello,World
hello,World
hello,World
hello, World
Step 1: First the counter variable gets initialized; here variable is I, which has been assigned
by value 1.
Step 2: Then variable has been tested for a given condition, if the condition results in true
then C statements enclosed in loop body get executed by compiler, otherwise control
skips the loop and continues with the next statements following loop.
Step 3: After successful execution of loop's body, the counter variable is incremented or
decremented, depending on the operation (++ or -).
3. Like initialization, you can also skip the increment part as we did below. In this case
semicolon (;) is must, after condition logic. The increment part is being done in for loop
body itself.
for(num=10;num<20;)
{
//Code
num++;
}
4. Below case is also possible, increment in body and init during declaration of counter
variable.
int num=10;
for(;num<20;)
{
//Statements
num++;
}
5. Counter can be decremented also. In the below example the variable gets decremented
each time the loop runs until the condition num>10 becomes false.
for(num=20;num>10;num--)
Output:
1
21
321
4321
54321
Example 1:
#include<stdio.h>
#include<conio.h>
int main()
{
int a=6;
while(a>=5)
{
printf("%d",a);
a++;
}
return0;
}
Infinite loop: a will always have value >=5 so the loop would never end.
Example 2:
#include<stdio.h>
int main()
{
int x=5;
while(x<=10)
{
printf("%d",x);
x--;
}
return0;
}
Infinite loop: x value will keep decreasing because of - operator, hence it will always be <=
10.
{
// codes
if (condition for break)
{
break;
}
// codes
}
You can also use characters in switch case. For example:
void main()
{
char ch='b';
switch(ch)
{
case'd':
printf("CaseD ");
break;
case'b':
printf("CaseB");
break;
case'c':
printf("CaseC");
break;
case'z':
printf("CaseZ ");
break;
default:
printf("Default ");
}
getch( );
}
Output:
CaseB
In addition to this, the break statement can also be used to terminate loops or to exit from a
switch. It can be used within a while a do — while, a for or a switch statement.
while(condition check)
{
statement-1;
statement-2;
if(some condition)
{
break;
}
statement-3;
statement-4;
}
Jumps out of the loop, no matter how
many cycles are left, loop is exited
Continue Statement
The continue statement skips some statements inside the loop. The continue statement is used
with decision making statement such as if...else
Example:
#include <stdio.h>
void main( )
{
static int marks[5] = {90,80,76,89, -90};
int i, total = 0;
for(i=0; i<5; i++)
{
if(marks[i] <0)
{
ptrint("negative marks not added \n");
continue;
}
total += marks[i]
}
Goto Statement:
A goto statement in C programming provides an unconditional jump from the 'goto' to a
labelled statement in the same function.
Syntax
The syntax for a goto statement in C is as follows ?
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C
program above or below to goto statement. The label is an identifier. When goto statement is
encountered, control of the program jumps to label: and starts executing the code.
Flow Diagram:
label 1 statement 2
go to
label 2 statement 2 label 3
label 3
statement 2
Example
#include <stdio.h>
void main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:
do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}
while( a < 20 );
getch( );
}
When the above code is compiled and executed, it produces the following result ?
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
4.6 Summary
We generally follow a sequence in the program but at times we would just want to execute
only selected statements.
1. This type of conditional processing is really useful to the programs.
2. It allows the programmers to build the programs that determine which statements
of the code should be executed and which are to be ignored.
Conditional statements
The conditional statements help to jump from one part of a program to another depending if a
particular condition is satisfied or not.
The conditional statements are:
1. if statement: It is one of the simplest forms of decision control statements which is frequently
used in decision making.
4. Switch case: This case statement is a multi-way decision statement which is a simpler
version of the if-else block which evaluates only one variable.
Control Structures: A loop is used for executing a block of statements repeatedly until a
given condition returns false.
1. For loop
2. While loop
3. do..while loop
Syntax of do-while loop
Continue statement: The continue statement is used inside loops. When a continue statement
is encountered inside a loop, control jumps to the beginning of the loop for next iteration, skipping
the execution of statements inside the body of loop for the current iteration.
Goto statement: The goto statement is rarely used because it makes program confusing,
less readable and complex. Also, when this is used, the control of the program won’t be easy to
trace, hence it makes testing and debugging difficult.
4.19 References
1. https://www.tutorialride.com/c-programming/decision-control-statements-in-c-
programming.htm
2. https://beginnersbook.com/2014/01/c-if-statement/
3. https://fresh2refresh.com/c-programming/c-decision-control/
4. http://www.nhcue.edu.tw/~jinnliu/teaching/cs07/6%20Control%20Structures.pdf
5. http://www.nyu.edu/classes/jcf/CSCI-GA.2110-001/slides/session3/ControlStructures-
LoopsConditionalsAndCaseStatements.pdf
UNIT 5 ARRAYS
Structure:
5.0 Learning Objectives
5.1 Introduction
5.2 One Dimensional Array
5.3 Two Dimensional Arrays
5.4 Summary
5.5 Key Words/Abbreviations
5.6 Learning Activity
5.7 Unit End Questions (MCQ and Descriptive)
5.8 References
5.1 Introduction
The array is another kind of variable or user defined variable that is used extensively in C. An
array is an identifier that refers to a collection of data items that all have the same name hence,
Array is a collection of similar types of data items like collection of all integers, collection of all
floats, collection of all characters.
The individual data items are represented by their corresponding array-elements (index).
Suppose that x is a 10-element array. The first element is referred to as x [0], the second as
x[1], and so on. The last element will be x [9]
Each member in the array (i.e., each individual data item) is referred to by specifying the
array name followed by one or more subscripts (array index), with each subscript enclosed in
square brackets. Each subscript must be expressed as a non-negative integer. In an n-element array,
the array elements are:
x [0], x [1] , x [2], . . . ,x [n - 1]
as illustrated in the following diagram. The first element of the array is referred to using the notation
x[0], the second element is referred to using the notation x[1] and so on.
A declaration is a statement that provides a data type and an identifier for a variable. An
identifier is a program component’s name.
element occupies an area in memory next to, or contiguous to, the others. All elements in a array
will be stored in a contiguous allocation of a memory.
Note that this version of the program does not require any input data. Execution of this program
will generate the following output:
Values of array item:
1
6
3
9
2
4
8
0
Remember one thing; all the array elements would always be present in contiguous memory
locations.
Data entered with a subscript exceeding the array size will simply be placed in memory outside
the array; probably on top of other data, or on the program itself. This will lead to unpredictable
results and there will be no error message. In some cases the computer may just hang.
Thus, every element in the array a is identified by an element name of the forma [ i ][ j ],
where ‘a’ is the name of the array, and ‘i’ and ‘j’ are the subscripts that uniquely identify each
element in ‘a’.
Of course, it is little difficult to understand so most of the programmers use the previous way
to initialize the 2D array items.
It is important to remember that while initializing a 2-D array it is necessary to mention the
second (column) dimension, whereas the first dimension (row) is optional. That means the following
declarations are valid
int items[4][2] = { 34, 56, 12, 33, 34, 80, 12, 78 } ;
int items[][2] = { 34, 56, 12, 33, 34, 80, 12, 78 } ;
whereas the following declarations are not valid
int items[4][] = { 34, 56, 12, 33, 34, 80, 12, 78 } ;
Programmers need to take care of the order in which initial values are assigned to
multidimensional array elements. The rule is that the last (rightmost) subscript increases most
rapidly, and the first (leftmost) subscript increases least rapidly. Thus, the elements of a two-
dimensional array will be assigned by rows; i.e., the elements of the first row will be assigned, then
the elements of the second row, and so on. Hence the above declaration will have the initial assignment
as follows:
Observe that the first subscript ranges from 0 to 2, while the second one ranges from 0 to 3.
The natural order in which the initial values are assigned can be altered by forming groups of
initial values enclosed within braces (i.e., { ... }). Consider the following example:
int items[4][2] = { { 34 },
{ 12 },
{ 34 },
{ 12 }
};
An element of the above array can be accessed using the following code:
int value = a[1][0];
printf("Value = %d", a[1][0]);
The above snippet would produce the following output:
Value = 34
5.4 Summary
An array is a group (or collection) of same data types. For example an int array holds
the elements of int types while a float array holds the elements of float types.
There are 2 types of C arrays. They are,
1. One dimensional array
2. Multi-dimensional array
Two dimensional array
Three dimensional array
Four dimensional array etc…
5.8 References
1. https://beginnersbook.com/2014/01/c-arrays-example/
2. https://fresh2refresh.com/c-programming/c-array/
3. https://www.tutorialspoint.com/cprogramming/c_arrays.htm
4. http://ee.hawaii.edu/~tep/EE160/Book/PDF/Chapter9.pdf
UNIT 6 STRINGS
Structure:
6.0 Learning Objectives
6.1 Introduction
6.2 Strings Basics
6.3 Declaring and Initializing String Variables
6.4 String Storage
6.5 Built-in-string functions
6.6 Summary
6.7 Key Words/Abbreviations
6.8 Learning Activity
6.9 Unit End Questions (MCQ and Descriptive)
6.10 References
6.1 Introduction
String is an array of characters. In this guide, we learn how to declare strings, how to work
with strings in C programming and how to use the pre-defined string handling functions.
We will see how to compare two strings, concatenate strings, copy one string to another &
perform various string manipulation operations. We can perform such operations using the pre-
defined functions of “string.h” header file. In order to use these string functions you must include
string.h file in your C program.
{
char name[15];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output:
Enter name
Shrutkirti
Your name is Shrutkirti
Index 0 1 2 3 4 5 6 7
Array P r o g r a m \0
Memory location 7890 7891 7892 7893 7894 7895 7896 7897
The null character automatically places the \0 character at the end of the string when it's
initialized in the array.
Example:
void main()
{
char word[8] = {'P', 'r', 'o', 'g', 'r', 'a', 'm', '\0'};
printf("Message = %s", word );
}
Output:
Message = Program
int add()
{
return x + y;
}
int main()
{
int answer; // Local variable
x = 2;
y = 5;
answer = add();
printf(“%d\n”,answer);
return 0;
}
In example, global variables are declared, x and y. These variables can be used in main() and
add(). The local variable answer can only be used in main().
6.5 Built-in-string-Functions
string.h or strings.h
The C language provides no explicit support for strings in the language itself. The string-
handling functions are implemented in libraries. String I/O operations are implemented in <stdio.h>
(puts , gets, etc). A set of simple string manipulation functions are implemented in <string.h>, or on
some systems in <strings.h>.
There is a separate header file that handles String in C Programming named "string.h". It
provides a wide range of functions that manipulate a null-terminated string.
strcpy() function
This library function is used to copy a string and can be used like this: strcpy(destination,
source). (It is not possible in C to do this: string1 = string2). Take a look at the following example:
str_one = "shruti";
str_two = "kirti";
strcpy(str_one , str_two); // str_one becomes "kirti"
Note: strcpy() will not perform any boundary checking, and thus, there is a risk of overrunning
the strings.
strcmp() function
This library function is used to compare two strings and can be used like this: strcmp(str1,
str2).
If the first string is greater than the second string a number greater than null is returned.
If the first string is less than the second string a number less than null is returned.
If the first and the second string are equal a null is returned.
strcat() function
This library function concatenates a string onto the end of the other string. The result is
returned. Take a look at the example:
printf("Enter you age: ");
scanf("%s", age);
result = strcat( age, " years old." ) == 0 )
printf("You are %s\n", result);
Note: strcat() will not perform any boundary checking, and thus, there is a risk of overrunning
the strings.
strlen() function
This library function returns the length of a string. (All characters before the null termination.)
Take a look at the example:
name = "Shruti";
result = strlen(name); //Will return size of six.
memcmp() function
This library function compares the first count characters of buffer1 and buffer2. The function
is used like this: memcmp(buffer1,buffer2). The return values are as follows:
If buffer1 is greater than buffer2 a number greater than null is returned.
If buffer1 is less than buffer2 a number less than null is returned.
If buffer1 and buffer2 are equal a null is returned.
Note: There are also library functions: memcpy, memset and memchr.
strlwr() function
strlwr( ) function converts a given string into lowercase. Syntax for strlwr( ) function is given
below.
char *strlwr(char *string);
In this program, string "MODIFY This String To LOwer" is converted into lower case using
strlwr( ) function and result is displayed as "THIS IS CAPITAL STRING".
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = " THIS IS CAPITAL STRING ";
printf("%s\n",strlwr (str));
return 0;
}
Output:
modify this string to lower
strupr() function
strupr( ) function converts a given string into uppercase. Syntax for strupr( ) function is given
below.
char *strupr(char *string);
In this program, string is converted into uppercase using strupr( ) function and result is displayed
as "THIS IS LOWER CASE STRING".
#include<stdio.h>
#include<string.h>
int main()
{
Output:
MODIFY THIS STRING TO UPPER
strrev() function
strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is given
below:
char *strrev(char *string);
In below program, string "Shrutkirti" is reversed using strrev( ) function and output is displayed
as "itrikturhS".
#include<stdio.h>
#include<string.h>
int main()
{
char name[25] = " Shrutkirti ";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
return 0;
}
Output:
String before strrev( ) : Shrutkirti
String after strrev( ) : itrikturhS
Consider the following example that demonstrates some of the above mentioned methods
#include<string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char msg1[10] = "Good"; //String one
char msg2[10] = "morning"; //String two
char msg3[15]; //String three to hold the result
//original strings
printf("\n\nOriginal Messages:\n");
printf("\nMsg1 : %s",msg1);
printf("\nMsg2 : %s",msg2);
//copy string
strcpy(msg3,msg2);
printf("\n\nMessages after copying:\n");
printf("\nMsg1 : %s",msg1);
printf("\nMsg2 : %s",msg2);
printf("\nMsg3 : %s",msg3);
printf("\n\nLength of Messages before concatenation:\n");
printf("\nMsg1 : %d", strlen(msg1));
printf("\nMsg2 : %d", strlen(msg2));
//string concatenation
strcat(msg1,msg2);
printf("\n\nMessages after concatenation:\n");
printf("\nMsg1 : %s",msg1);
printf("\nMsg2 : %s",msg2);
printf("\n\nLength of Messages after concatenation:\n");
printf("\nMsg1 : %d", strlen(msg1));
printf("\nMsg2 : %d", strlen(msg2));
getch();
}
Output:
Original Message
Msg1 : Good
Msg2 : Morning
6.6 Summary
Strings are actually one-dimensional array of characters terminated by a null character
‘\0’. Thus a null-terminated string contains the characters that comprise the string
followed by a null.
Strings are defined as an array of characters. The difference between a character array
and a string is the string is terminated with a special character ‘\0’.
4. strcmp ( ) - Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1
> str2
5. strcmpi ( ) - Same as strcmp() function. But, this function negotiates case. “A” and “a”
are treated as same.
6. strchr ( ) - Returns pointer to first occurrence of char in str1.
7. strrchr ( ) - last occurrence of given character in a string is found
8. strstr ( ) - Returns pointer to first occurrence of str2 in str1
9. strrstr ( ) - Returns pointer to last occurrence of str2 in str1
10. strdup ( ) - Duplicates the string
11. strlwr ( ) - Converts string to lowercase
12. strupr ( ) - Converts string to uppercase
13. strrev ( ) - Reverses the given string
14. strset ( ) - Sets all character in a string to given character
15. strtok ( ) - Tokenizing given string using delimiter
6.10 References
1. https://www.tutorialspoint.com/learn_c_by_examples/string_programs_in_c.htm
2. https://beginnersbook.com/2014/01/c-strings-string-functions/
3. https://www.programiz.com/c-programming/c-strings
4. C Programming Language written by Dennis Ritchie and Brian W. Kernighan.
UNIT 7 FUNCTIONS
Structure:
7.0 Learning Objectives
7.1 Introduction
7.2 Concepts of User Defined Function
7.3 Function Prototype (Declaration) and Definition
7.4 Return Statement
7.5 Calling a Function by Passing Values
7.6 Recursive Function
7.7 Summary
7.8 Key Words/Abbreviations
7.9 Learning Activity
7.10 Unit End Questions (MCQ and Descriptive)
7.11 References
7.1 Introduction
A function is a block of statements that performs a specific task. Suppose you are building an
application in C language and in one of your program, you need to perform a same task more than
once. In such case you have two options –
(a) Use the same set of statements every time you want to perform the task.
(b) Create a function to perform that task, and just call it every time you need to perform
that task.
Using option (b) is a good practice and a good programmer always uses functions while
writing codes in C.
5. Modification can be done easily because of modularization. Updatation does not affect
whole program only respective module will be affected.
Categories of Functions
C functions can be classified into two categories,
Library functions
User-defined functions
Library functions are those functions which are defined by C library, example printf(), scanf(),
strcat() etc.
Every C Program has main() function inbuilt in the program with return type int or void which
is function header statement.
Consist of main function definition with function body comprises of atatements terminated
by; sign and user defined functions can be added according to the requirement.
Function Definition:
return_type function name (no. of parameters/arguments with data types)
{
c statement; // Block code of statements //
c statement;
return statement;
}
Return_type: Every function returns a value after execution of block of statements, Return
type can be of any data type such as int, double, char, void, short, etc., Normally, function return
type is any datatype but if function does not return any value then we have to specify with void
keyword to indicate function returns null value.
Function_name: Function name should be valid identifier and function name should be a
meaningful name so that it can be easy to understand the purpose of function just by seeing its
name.
Argument list/parameter list (type arg1, type arg2): Arguments are also called parameters,
parameter list contains variables names along with their data types. These arguments are positional
formal/dummy parameters whose value can be replaced with actual parameter during function call.
For example – A function which is used to add three integer variables, will have three integer
argument. All arguments are to be specified along with data type and are separated by commas.
Block of code: It is a Set or Block of C statements, which will be executed during function
call. Function definition execution will be performed in a stack.
If function has return type, then return statement will be the last statement of a block and if
function has no return type, i.e., void then this function will have a no return statement.
Let us Assume on example to solve the problem of function
Solution:
Solution:.
Function definition of even number checking with No return type hence void:
void even (int a)
{
if (a%2 = = 0)
printf(“a is even”);
else
printf(“a is odd”);
}
Example:
/* function return type is void and doesn’t have parameters*/
void main()
{
/*calling function*/
intro();
getch();
}
void intro()
{
printf(“Hi\n”);
printf(“My name is Kiran Gurbani\n”);
printf(“How are you?”);
/* there is no return statement inside this function, since its
* return type is void */
}
Output:
Hi
My name is Kiran Gurbani
How are you?
Fig. 7.1: Pictorial representation of function call accessed by function definition and
returing value back to main function
Function Prototypes
1. Function prototype is the signature of the function also called a function declaration.
2. Function declaration informs to the compiler about return type of the function, name of
the function and list of arguments with their data types.
In below example we have declared function with no argument and integer as return type
int get(void);
int x,y,s;
clrscr();
printf(“Enter two numbers\n”);
scanf(“%d %d”,&x,&y);
s=x+y;
printf(“\n The sum of two numbers is %d”,s);
getch();
}
int sum(int a, int b)
{
int c;
c= a+b;
return c;
}
Arguments can be passed to functions and functions always return one value
1. If function returns only one single value then function must have return data type
compulsory.
Example: Sum of three numbers, Factorial of a number, these functions having return
value by function, will be single.
2. If function returns more than one values or if through function we are going to print
any message then in both the cases function does not have any return type because
function cannot return more than one value and we cannot return message hence function
will not have any return type. By using pointers we can achieve this.
Example: Print number is even or odd, print number is prime or not, print natural
numbers from 1 to 10, print prime numbers from 1 to n.
3. Function with argument return multiple values using function using pointers.
getch();
}
void even(int n)
{
If(n % 2 ==0)
printf(“*n=%d is even number “,n);
else
printf(“n = %d is odd number”,n);
}
c of the function with arguments and no return value.
getch();
}
void natural(int n)
{
int i;
for( i=1;i<=n;i++)
{
printf(“%d”,i);
}
}
Pictorial representation of the function with arguments and no return value because of multiple
values returning.
operator called address operator, that evaluates the address of its operand. Now suppose the address
of x is assigned to another variable, px, i.e.,
px = &x;
This new variable, px, is called a pointer to x because it points to the location where x is
stored in memory. Thus px is referred to as pointer variable. The data item identified by x can also
be accessed by the expression *px, where * is a unary operator that operates on only a pointer
variable. Therefore, *px and x both identify the same data. The relationship between px and x is
shown in the diagram below:
Address of x Value of x
px x
Fig. 7.2: Pictorial Representation of Relationship between Pointer Variable and Variable
Defining a Pointer
The syntax for pointer declaration is
data-type *pt_var
where pt_var is the name of the pointer variable and data-type refers to the data type of the pointer.
(Note: Remember that an asterisk must precede pt_var)
For example, consider the following snippet for pointer declaration
int x, y; //integer variable declaration
int *ptr_x; // integer pointer declaration
The variable ptr_x is declared as pointer variable that can point to a integer quantity. Note that
ptr_x represents an address, not a floating-point quantity.
We have used arguments to send values to the called function, in the same way we can also
use arguments to send back information to the calling function. The arguments that are used to send
back data are called Output Parameters.
It is a bit difficult for a novice because this type of function uses a pointer. Let’s see an
example:
#include<stdio.h>
#include<conio.h>
void main()
{
int len,br,area,peri;
void areaperi(int l,int b,int *area,int *peri);
clrscr();
printf(“Enter length & breath\n”);
scanf(“ %d %d”,&len,&br, &area, &peri);
printf(“Area is %d”,*area);
printf(“permeter is %d”, *peri);
getch();
}
void areaperi(int l, int b, int *area, int *peri)
{
*area = l * b;
*peri = 2*(l+b);
}
to a function also they are called as positional parameters, since their postion is fixed when passed
within a function. While passing formal parameters we have to specify data types.
Actual arguments: The parameter’s value (or arguments) we provide while calling a function
is known as actual arguments. These arguments are original or actual values of parameters which is
to be passed during function call. Actual parameters are also positional parameters. While passing
actual parameters we have to pass values of variables but we don’t have to pass data type of
parameters, we have to pass only arguments or its value.
For example
Example of C program containing a function that alters the value of its argument.
#include <stdio.h>
void modify ( int a); /* function prototype */
void main ( )
{
int a = 2;
printf( “ \n a = %d (from main, before calling the function ) “, a );
modify(a);
printf( “ \n a = %d (from main, after callig the function) “, a ) ;
getch();
}
void modify (int a)
{
a *= 3;
printf ( “ \n a = %d (from the function, after being modified)”, a ) ;
return;
}
The value of a variable is assigned with value is 2, original value of a (i.e., a = 2) is displayed
when main begins execution. This value is then passed to the function modify, i.e., actual parameter
a value will be passed to formal parameter of modify function, where it is multiplied by 3 in modify
function and the new value displayed after modification since function does not have return value.
Note that it is the altered value of the formal argument that is displayed within the function. Finally,
the value of a within main (i.e., the actual argument) is again displayed, after control is transferred
back to main from modify.
When the program is executed, the following output is generated.
a = 2 (from main, before calling the function)
a = 6 (from the function, after being modified)
a = 2 (from main, after calling the function)
These results show that a is not altered within main, even though the corresponding value of
a is changed within modify.
Passing an argument by value has the following advantages and disadvantages :
Advantage: It allows a single valued actual argument to be written as an expression rather
than being restricted to a single variable.
Moreover, if the actual argument is expressed simply as a single variable, it protects the value
of this variable from alterations within the function.
Disadvantage: It does not allow information to be transferred back to the calling portion of
the program via arguments. Thus, passing by value is restricted to a one-way transfer of information.
Function Definition
1. Function Definition is a body of the function written outside the main function.
2. The function definition has a function header statement with a body of statements
enclosed within { and }
3. Function definition has two main components: (1) First Line Function Header (2) Body
of function enclosed with { }
4. The First Header statement consists of type specification of the value returned by the
function followed by function name and followed by ( )
5. Within ( ) round brackets either can be empty or it can have parameters or arguments
with data type of each argument
The Syntax of function definition is:
return_type function_name (no. of parameters/arguments with data types)
{
c statement; // Block code of statements //
c statement;
return statement;
}
Return_type: Every function returns a value after execution of block of statements,
Return type can be of any data type such as int, double, char, void, short etc. Normally
function return type is any datatype but if function does not return any value then we
have to specify with void keyword to indicate function returns null value.
Function_name: Function name should be valid identifier and function name should
be a meaningful name so that it can be easy to understand the purpose of function just
by seeing its name.
Argument list/parameter list (type arg1, type arg2): Arguments are also called
parameters, parameter list contains variables names along with their data types. These
arguments are positional formal/dummy parameters whose value can be replaced with
actual parameter during function call. For example – A function which is used to add
three integer variables, will have three integer argument. All arguments are to be specified
along with data type and are separated by commas.
Block of code: It is a Set or Block of C statements, which will be executed during
function call. Function definition execution will be performed in a stack.
If function has return type, then return statement will be the last statement of a block
and if function has no return type, i.e., void then this function will have a no return
statement.
Let us assume on example to solve the problem of function.
Function definition of even number checking with no return type hence void:
void even (int a)
{
if (a%2 = = 0)
printf(“a is even”);
else
printf(“a is odd”);
}
return r;
}
Pictorial representation of function with arguments and return type.
*area = l * b;
*peri = 2*(l+b);
}
Call by Value
If data is passed by value, the data is copied from the variable used in for example main() to a
variable used by the function. So if the data passed (that is stored in the function variable) is
modified inside the function, the value is only changed in the variable used inside the function.
Let’s take a look at a call by value example:
1. Call by value: Function call has number of different parameters, the value of these parameters
is passed to formal parameters hence the value of actual parameters passed to formal parameters
are called call by value. In this function call passes arguments by value. The called function creates
a new set of variables.
Function prototype statement is:
void call_by_value(int x)
Function call statement is:
call_by_value(a);
Function definition is:
void call_by_value(int x)
{
Program:
# include <stdio.h>
void call_by_value(int x)
{
printf(“Inside call_by_value x = %d before adding 10.\n”, x);
x += 10;
printf(“Inside call_by_value x = %d after adding 10.\n”, x);
}
void main()
{
int a=20;
printf(“a = %d before function call_by_value.\n”, a);
call_by_value(a);
printf(“a = %d after function call_by_value.\n”, a);
getch();
}
then copied to the function variable x. In the function we add 10 to x (and also call some print
statements). Then when the next statement is called in main() function the value of variable a is
printed. We can see that the value of variable a isn’t changed by the call of the function
call_by_value().
2. Call by reference: In this function, declaration and definition parameters are passed by
reference. In this formal parameters of function definition become aliases to the actual arguments
in the calling function.
The call by reference method of passing arguments to a function copies the address of an
argument into the formal parameter. Inside the function, the address is used to access the actual
argument used in the call. It means the changes made to the parameter affect the passed argument.
To pass a value by reference, argument pointers are passed to the functions just like any other
value. So accordingly you need to declare the function parameters as pointer types as in the following
function swap(), which exchanges the values of the two integer variables pointed to, by their
arguments. The pointer variables are to be specified in function declaration and function definition.
/* function definition to swap the values */
void swap(int *a, int *b)
{
int temp;
temp = *a; /* save the value at address a */
*a = *b; /* put b into a */
*b = temp; /* put temp into b */
Return
}
Let us now call the function swap() by passing values by reference as in the following example
#include <stdio.h>
/* function declaration */
void swap(int *a, int *b);
void main ()
{
/* local variable definition */
int x = 10;
int y = 20;
printf(“Before swap, value of x : %d\n”, x );
printf(“Before swap, value of y : %d\n”, y );
/* calling a function to swap the values.
* &x indicates pointer to x ie. address of variable x and
* &y indicates pointer to y ie. address of variable y.
*/
swap(&x, &y);
printf(“After swap, value of x : %d\n”, x );
printf(“After swap, value of y : %d\n”, y );
getch();
}
Output:
Before swap, value of x :10
Before swap, value of y :20
After swap, value of x :20
After swap, value of y :10
Recursion is a process by which action calls itself repeatedly, until some specified condition
has been satisfied. The process is used for repetitive computations in which each action is stated in
terms of a previous result. It is similar to looping. On the other hand, recursion makes it easier to
express ideas in which the result of the recursive call is necessary to complete the task.
A simple example of recursion would be:
void recurse()
{
recurse(); /* Function calls itself */
}
int main()
{
recurse(); /* Sets off the recursion */
return 0;
}
This program will not continue forever, however. The computer keeps function calls on a
stack and once too many are called without ending, the program will crash.
Recursive Function
Statem ents
TRUE
Condition
FALSE
STOP
Example:
/* calculate the factorial of an integer quantity using recursion */
#include<stdio.h>
long int factorial(int n); / * function prototype */
void main( )
{
int n;
long int factorial(int n);
/* read in the integer value */
scanf(“‘%ld”, &n) ;
/ * calculate and display the factorial */
printf(“n! = %ld\n”, factorial(n));
getch();
}
/* function definition */
long int factorial(int n) / * calculate the factorial */
{
if (n <= 1)
return( 1 ) ;
else
return(n * factorial(n - 1));
}
The main portion of the program simply reads the integer quantity n and then calls the long-
integer recursive function factorial. The function factorial calls itself recursively, with an actual
argument (n - 1) that decreases in magnitude for each successive call. The recursive calls terminate
when the value of the actual argument becomes equal to 1.
Recursive Method
factorial(n)
Yes
n=1
factorial=1
Not
fact=n*factorial(n–1)
return fact
When the program is executed, the function factorial will be accessed repeatedly, once in
main and (n - 1) times within itself, though the person using the program will not be aware of this.
Only the final answer will be displayed; for example,
n! = 3628800
When a recursive program is executed, the recursive function calls are not executed
immediately. Rather, they are placed on a stack until the condition that terminates the recursion is
encountered.* The function calls are then executed in reverse order, as they are “popped” off the
stack. Thus, when evaluating a factorial recursively, the function calls will proceed in the following
order:
n! = n x (n - l)!
(n - l)! = (n - 1) x (n -2)!
(n - 2)! = (n - 2) x (n - 3)!
2! =2 x l!
The actual values will then be returned in the following reverse order:
l! = 1
2! = 2 x l! = 2 x 1 = 2
3! = 3 x 2! = 3 x 2 =6
4! = 4 x 3! = 4 x 6 = 24
n!= n x (n- l)! = * - -
This reversal in the order of execution is a characteristic of all functions that are executed
recursively.
If a recursive function contains local variables, a set of local variables will be created during
each call. The names of the local variables will, of course, always be the same, as declared within
the function. However, the variables will represent a different set of values each time the function
is executed.
Each set of values will be stored on the stack, so that they will be available as the recursive
process “unwinds”, i.e., as the various function calls are “popped” off the stack and executed.
7.7 Summary
C functions are basic building blocks in every C program. We have given key points those to
be kept in mind for using existing C library functions and writing our own functions in a C program
efficiently.
All C programs contain main() function which is mandatory.
main() function is the function from where every C program is started to execute.
Name of the function is unique in a C program.
C Functions can be invoked from anywhere within a C program.
There can any number of functions be created in a program. There is no limit on this.
There is no limit in calling C functions in a program.
All functions are called in sequence manner specified in main() function.
One function can be called within another function.
C functions can be called with or without arguments/parameters. These arguments are
nothing but inputs to the functions.
C functions may or may not return values to calling functions. These values are nothing
but output of the functions.
When a function completes its task, program control is returned to the function from
where it is called.
There can be functions within functions.
Before calling and defining a function, we have to declare function prototype in order
to inform the compiler about the function name, function parameters and return value
type.
C function can return only one value to the calling function.
When return data type of a function is “void”, then, it won’t return any values
When return data type of a function is other than void such as “int, float, double”, it
returns value to the calling function.
main() program comes to an end when there is no functions or commands to execute.
There are 2 types of functions in C. They are, 1. Library functions 2. User defined
functions
7.11 References
1. https://beginnersbook.com/2014/01/c-functions-examples/
2. https://www.programiz.com/c-programming/c-functions.
3. https://publications.gbdirect.co.uk/c_book/thecbook.pdf
4. https://phy.ntnu.edu.tw/~cchen/ctutor.pdf
UNIT 8 POINTERS
Structure:
8.0 Learning Objectives
8.1 Introduction
8.2 Fundamentals of Pointer
8.3 Pointer Variables
8.4 Referencing and Dereferencing
8.5 Pointer Arithmetic
8.6 Using Pointers with Arrays
8.7 Using Pointers with Strings
8.8 Arrays of Pointers
8.9 Pointers as Function Arguments
8.10 Functions Returning Pointers
8.11 Summary
8.12 Key Words/Abbreviations
8.13 Learning Activity
8.14 Unit End Questions (MCQ and Descriptive)
8.15 References
8.1 Introduction
Introduction to C Pointers. A Pointer in C language is a variable which holds the address
of another variable of same data type. Pointers are used to access memory and manipulate the
address. Pointers are one of the most distinct and exciting features of C language.
variable. Therefore, *px and x both identify the same data. The relationship between px and x is
shown in the diagram below:
Address of x Value of x
px x
The program starts by declaring the integer variables x and y; it also initializes them with 50
and 45 respectively. It later defines a pointer variable prt_x that is assigned the address of x. so
ptr_x gets loaded with the value 1450. Now y is assigned the contents of ptr_x. ptr_x currents
points to memory location 1450, i.e., location of x. so y gets assigned to the value of x, i.e., 50. now
xi assigned with ptr_x, that itself, holds the address of x. so x gets loaded with its own address, i.e.,
1450. Finally, *ptr_x is assigned with 30. *ptr_x means value at the location pointed by ptr_x that
is x itself. So x gets loaded with 30.
Address in C
If you have a variable var in your program, &var will give you its address in the memory,
where & is commonly called the reference operator.
You must have seen this notation while using scanf() function. It was used in the function to
store the user inputted value in the address of var.
scanf(“%d”, &var);
/* Example to demonstrate use of reference operator in C programming. */
#include <stdio.h>
int main()
{
int var = 5;
printf(“Value: %d\n”, var);
printf(“Address: %u”, &var); //Notice, the ampersand(&) before var.
return 0;
}
Output:
Value: 5
Address: 2686778
Note: You may obtain different value of address while using this program.
In above source code, value 5 is stored in the memory location 2686778. var is just the name
given to that location.
return 0;
}
Output:
Address of c: 2686784
Value of c: 22
Address of pointer pc: 2686784
Content of pointer pc: 22
Address of pointer pc: 2686784
Content of pointer pc: 11
Address of c: 2686784
Value of c: 2
pc c pc c pc c pc c pc c
22 22 11 2
Line 4: int *pc, c; Line 5: c=22; Line 8: pc=&c; Line 11: c=11; Line 14: *p=2;
Increment/Decrement
Consider an integer pointer variable ptr_x which points to the address 1450. Let’s increment
the variable (integer data size is 16 bit i.e. 2 bytes).
ptr_x++;
Now the pointer variable ptr_x will point to the location 1452 because each time ptr_x will be
incremented, it will point to the next integer location which is 2 bytes next to the current location.
If ptr_x points to a character whose address is 1000, then the above operation will point to the
location 1001 because the next character will be available at 1001.
Example:
void main()
{
int x = 45;
intptr_x = &x;
printf(“\nOriginal values: x = %d ptr_x = %d”, x, ptr_x);
ptr_x++;
printf(“\nValues after incrementing : x = %d ptr_x = %d”, x, ptr_x);
}
When the above code is compiled and executed, it produces the following result:
Original values: x = 45 ptr_x = 8945
Values after incrementing : x = 45 ptr_x = 8947
Similarly for decrement, it decreases pointer variables value by the number of bytes of its data
type.
Example
void main()
{
int x = 45;
intptr_x = &x;
printf(“\nOriginal values: x = %d ptr_x = %d”, x, ptr_x);
ptr_x—;
printf(“\nValues after decrementing : x = %d ptr_x = %d”, x, ptr_x);
}
When the above code is compiled and executed, it produces the following result
Original values: x = 45 ptr_x = 8945
Values after incrementing : x = 45ptr_x = 8943
Addition/Subtraction
Consider the following example to demonstrate the addition operation on pointer, which can
be similarly considered for subtraction.
void main( )
{
int *ptr_i; /* pointer to an integer */
int i= 1;
ptr_i = & i ;
printf (“Value: i=%d \n\n”, i);
printf (“Address: &i=%X \n\n”, &i) ;
printf (“ Pointer value: ptr_i=%X ptr_i + l=%X ptr_i + 2=%X ptr_i + 3=%X” ptr_i,
ptr_i + 1, ptr_i + 2, ptr_i + 3 ) ;
}
This program displays the value and address associated to i, an integer variable. The program
also makes use of a pointer variable, ptr_i, which represents the address of i. The values of ptr_i,
ptr_i + 1, ptr_i + 2 and ptr_i + 3 are also displayed, so that they may be compared with the addresses
of the different variables.
Execution of the program results in the following output:
Value: i=1
Address: &i=7890
Pointer values: ptr_i=7890 ptr_i + 1=7892 ptr_i + 2=7894 ptr_i + 3=7896
The first line simply displays the value of the variable, and the second line displays its addresses,
as assigned by the compiler. Notice the number of bytes associated with data item. The integer
value represented by i requires two bytes (specifically, addresses 7890 and 7891).
Now consider the third line of output, it contains the addresses represented by the pointer
expressions. Clearly, ptr_i represents the address of i (i.e., 7890). However, ptr_i + 1 moves over
only two bytes, to 7892,and ptr_i + 2 moves over another two bytes, to 7894, and so on. The reason
is pointer ptr_i points to an integer quantity that require 2bytes. Hence when integer constants are
added to ptr_i, the constant is treated as two-byte multiple. If ptr_i is defined as a pointer to a
different type of object (e.g., a character or a floating-point quantity), then any integer constant that
is added to or subtracted from the pointer will be interpreted differently. For example, if ptr_i
would be a floating point quantity then the integer constant would be treated as four-byte multiple.
Pointer Comparison
Pointer variables can be compared provided both variables are of the same data type. Such
comparisons can be useful when both pointer variables point to elements of the same array. The
comparisons can test for either equality or inequality. Moreover, a pointer variable can be compared
with zero (i.e., NULL).
Assume pt_x and pt_y are pointer variables that point to elements of the same array. Several
logical expressions involving these two variables are shown below. All of the expressions are
syntactically correct.
(pt_x<pt_y) Indicates whether or not the element associated with pt_x is ranked ahead of
the element associated with pt_y
(pt_x>= pt_y) Indicates whether or not the element associated with pt_x is ranked after the
element associated with pt_y
(pt_x == pt_y) Indicates whether or not the element associated with pt_x is equal to the
element associated with pt_y
(pt_x != pt_y) Indicates whether or not the element associated with pt_x is not equal to the
element associated with pt_y
(pt_x == NULL) Indicates whether or not the element associated with pt_x is equal to NULL
C \0 C + + \0 J a v a \0 V B A \0
178 189
In this example
1. ptr : It is pointer to array of string of size 4.
2. array[4] : It is an array and its content are string.
for(i=0;i<4;i++)
printf(“Address of String %d : %u\n”,i+1,(*ptr)[i]);
return 0;
}
Output:
Address of String 1 = 178
Address of String 2 = 180
Address of String 3 = 184
Address of String 4 = 189
Output:
String 1 = Kiran
String 2 = KS
String 3 = SK
String 4 = Shri
Output:
ava
array of pointers would be a collection of addresses. The address present in the array of pointers
can be addresses of isolated variables or addresses of array elements or any other addresses.
Consider the following example:
void main()
{
int marks[] = {45, 55, 65, 35, 47};
int i, *pt[5]; // array of pointers
for(i=0;i<5;i++)
pt[i] = &marks[i]; // assigning the address of integers stored in integer array
for(i=0;i<5;i++)
printf(“Marks of student: \n %d \n”, *pt[i]);
}
For loop in the program picks up the addresses present in pt and prints the values present at
these addresses. This is shown in Fig. 8.6.
Array index marks[0] marks[1] marks[2] marks[3] marks[4]
marks 45 55 65 35 47
As discussed above, the array of pointers can contain address of isolated variables. That
exercise if left up to readers.
Example:
void show_int(int x, int y);//function prototype
void show_int1(int *pt_x, int *pt_y);
void main()
{
int x = 56;
int y = 75;
printf(“\n Original values: x=%d, y=%d”, x, y);
show_int(x,y);
printf(“\n Values of x and y after calling show_int(): x=%d, y=%d”, x, y);
show_int1(&u, &v);
printf(“\n Values of x and y after calling show_int1(): x=%d, y=%d”, x, y);
}
the output illustrates the local nature of the alterations within show_int(), and the global nature of
the alterations within show_int1().
}
int* larger(int *x, int *y)
{
if(*x > *y)
return x;
else
return y;
}
8.11 Summary
Pointers in C language is a variable that stores/points the address of another variable. A Pointer
in C is used to allocate memory dynamically, i.e., at run time. The pointer variable might be belonging
to any of the data type such as int, float, char, double, short etc.
A pointer is a variable that represents the location (rather than the value) of a data item in
memory, such as a variable or an array element. Pointer is a very useful tool of C programming as
it can help improve the programs efficiency and allow the user to handle unlimited amount of data.
Pointers are also closely associated with arrays, and therefore, provide an alternate way to access
individual array elements.
Pointer Variables contains the following points:
1. Defining and Declaration of a Pointer Variable
2. Pointer Initialization and Pointer Assignment
3. Null Pointer
4. What Happens at Memory Level
3. What is the relationship between the address of a variable and the corresponding pointer
variable? Explain with the help of a diagram.
4. What is the relationship between the data item represented by a variable and the
corresponding pointer variable? Explain with the help of a diagram.
5. How is a pointer variable declared? What is the purpose of the data type included in the
declaration?
6. Explain the function prototype when it receives a pointer as an argument. Also explain
how the pointer argument is declared within the function definition.
7. What is the relationship between an array name and a pointer?
8. How can a one-dimensional array of pointers be used to represent a collection of strings?
Explain with an example.
9. Describe the two different ways to specify the address of an array element.
10. Describe the two different ways to access an array element.
11. Explain how functions returning pointer with suitable example.
12. Explain with suitable example how pointer variables can be passed as a function
arguments.
13. Explain array of pointers in detail with example.
8.15 References
1. https://fresh2refresh.com/c-programming/c-pointer/
2. https://www.studytonight.com/c/pointers-in-c.php
3. C: The complete reference by Herbert Schildt.
UNIT 9 STRUCTURE
Structure:
9.0 Learning Objectives
9.1 Introduction
9.2 Basics of Structure
9.3 Declaration of Structure
9.4 Reading and Assignment of Structure Variables
9.5 Array of Structures
9.6 Arrays within Structures
9.7 Nested Structure
9.8 Structures and Pointers
9.9 Summary
9.10 Key Words/Abbreviations
9.11 Learning Activity
9.12 Unit End Questions (MCQ and Descriptive)
9.13 References
9.1 Introduction
Structure is a user-defined datatype in C language which allows us to combine data of different
types together. Structure helps to construct a complex data type which is more meaningful. It is
somewhat similar to an Array, but an array holds data of similar type only. But structure on the
other hand, can store data of any type, which is practical more useful.
Uses of Structures in C
1. C Structures can be used to store huge data. Structures act as a database.
2. C Structures can be used to send data to the printer.
3. C Structures can interact with keyboard and mouse to store the data.
4. C Structures can be used in drawing and floppy formatting.
5. C Structures can be used to clear output screen contents.
6. C Structures can be used to check computer’s memory size, etc.
type varname ;
type varname ;
type varname ;
type varname ;
};
Structure Padding in C
Many processors expect memory for variables to be aligned based on the size of the variable.
A ‘char’ of 1 byte can be allocated anywhere in memory like 0x5000 or 0x5001. And an ‘int’ of 4
bytes, must start at a 4-byte boundary like 0x5004 or 0x5008. The structure padding is automatically
done by the compiler to make sure all its members are byte aligned.
The size of the below structure is 16 bytes due to structure padding:
Struct dummy {
Char ch;
Int num;
Double temp;
}
Here ‘char’ is only 1 byte but after 3 byte padding, the number starts at 4 byte boundary. For
‘int’ and ‘double’, it takes up 4 and 8 bytes respectively.
The compiler used the 3 wasted bytes (marked in red) to pad the structure so that all the other
members are byte aligned. Now, the size of the structure is 4 + 1 +3 = 8 bytes. The size of the entire
structure is 8 bytes. On knowing the structured padding, it is easier to redesign or rewrite the
structure.
Let’s look at another example where the syntax is slightly different;
#include<stdio.h>
Struct dummy {
Int num;
Double x;
Float f;
};
Struct dummy1 {
Double x;
Int num;
Float f;
};
Int main()
{
Printf(“size:%d %d
”, sizeof(struct dummy ), sizeof(struct dummy1));
System(“PAUSE”);
Return 0;
}
The output will be as shown below;
++variable. member is equivalent to ++(variable. member); i.e., the ++ operator will apply to the
structure member, not the entire structure variable.
Similarly, the expression and instance variable.member is equivalent to & (variable. member);
thus, the expression accesses the address of the structure member, not the starting address of the
structure variable.
Structure Assignment
Normally, can structure variables be treated similar to any regular variables? Especially, when
the value of one structure variable needs to be assigned to other. Well it is a complicated task. Let’s
try to understand. Consider the following structure definition.
struct car
{
char manufacturer[50];
char model[10];
int cost;
};
If two variables c1and c2, structure variables of type car, are to be assigned to each other then
there are three different ways in which it can be done
(i) Assign the members one by one
c1.manufacturer = c2.manufacturer
c1.model = c2.model
c1.cost = c2.cost
(ii) Copy the whole memory contents of c2 to c1
memcpy(&c1,&c2,sizeof(c1));
(iii) Straight assignment using ‘=’
c1=c2;
As shown above, it would be stupid programming if the programmer uses the first approach.
So obviously they would prefer using the 2nd or the 3rd way of structure assignment. But what is
the difference? Is there any drawback?
Copying the structure variables using the straight assignment ‘=’ technique is probably the
best as it’s shorter, easier to read and has higher level of abstraction. While the other technique is
more compiler friendly, it just copies the memory of the size specified. This requires the reader to
think about the size argument to copy. When doing a straight assignment, there is no hesitation
about whether or not the size is correct.
The dangerous part of structure assignment is when the structure element is a pointer. Copying
structures that contain pointers can be a bit dangerous, since by doing so those pointers are aliased,
typically making it ambiguous who owns the pointer after the copying operation. If the structure
has char * pointing to a specific string, both structures will point to the same string. Changing the
contents of one of those string fields will change the other as well.
To overcome this, copy the entire contents of the structure and then deep copy the string by
effectively giving a separate string to each structure.
Thing to remember while using structure assignment
Recommend using straight assignment ‘=’ instead of memcpy.
If structure has pointer or array member, please consider the pointer alias problem, it
will lead to dangling pointer once incorrect use. Better way is to implement structure
assignment function in C
{
char title[20];
struct author book_author;
int no_of_pages;
float cost;
} books[50];
In this declaration books is a 50 elements array of structure. Each element of books is a
separate structure to type book. Each structure of type book in turn includes an array (title) and
another structure (author) as members. This shows how an array and a structure in embedded in
another structure, which itself is an element of an array.
An alternate way to define an array of structure book is shown below
struct author
{
char first_name[15];
char last_name[15];
};
struct book
{
char title[20];
struct author book_author;
int no_of_pages;
float cost;
};
struct book books[50];
an array of structure can be initialized just the way as any other array. Consider the following
declarations
struct author
{
char first_name[15];
char last_name[15];
};
struct author author_list[]={ “Kiran”, “Gurbani”}
As seen in this example, the size of the array of structure is not specified. The initial values
will define the size of the array and amount of memory required to store the array.
The use of the period operator can be extended to arrays of structures, by writing array
[expression] .member where array refers to the array name, and array [expression] is an individual
array element (a structure variable). Therefore, array [expression], member will refer to a specific
member within a particular structure.
For the above example, author_list is an array of structures of type author. To access its
second element use the expression author_list[1].
Let’s consider the following example:
struct author
{
char first_name[15];
char last_name[15];
};
struct book
{
char title[20];
struct author book_author;
int no_of_pages;
float cost;
}books[5];
The following table gives expression showing how the various members and submembers of
the structure variable can be accessed.
Expression Explanation
book[1].title Access the title member for the second book
&book[1].title Access the address of title member within the second book structure
book[1].title[3] Access the 3rd character within book’s title
book[1].book_author.first_name Access the first_name member of structure of type author within
the structure book
++book[1].no_of_pages Causes the value of no_of_pages to increment
data[1].percentage = 89.5;
// 3rd student’s data
data[2].id=3;
strcpy(data[2].name, “Swapnil”);
data[2].percentage = 77.5;
for(i=0; i<3; i++)
{
printf(“ Records of STUDENT : %d \n”, i+1);
printf(“ Id is: %d \n”, data[i].id);
printf(“ Name is: %s \n”, data[i].name);
printf(“ Percentage is: %f\n\n”, data[i].percentage);
}
getch( );
}
Output of the above program is
Records of STUDENT : 1
Id is: 1
Name is: Prem
Percentage is: 68.500000
Records of STUDENT : 2
Id is: 2
Name is: Dheeraj
Percentage is: 89.500000
Records of STUDENT : 3
Id is: 3
Name is: Swapnil
Percentage is: 77.500000
Example:
//structure declaration
struct month
{
int num_of_days;
char name[4];
};
void main()
{
struct month this_month = { 31, “Jan” };
printf(“The month is %s\n”, this_month.name );
}
Alternate way to define the array is explained in the following array:
//structure declaration
struct month
{
int num_of_days;
char name[4];
};
void main()
{
this_month.num_of_days = 31;
strcpy( this_month.name, “Jan” );
printf(“The month is %s\n”, this_month.name );
}
struct Student s;
printf(“\nEnter Student Roll No: “);
scanf(“%d”, &s.roll_No);
printf(“\n Enter Student Name: “);
scanf(“%s”, &s.name);
s.total = 0;
for(i=0; i<5; i++)
{
printf(“\n Enter Marks %d:”, i+1);
scanf(“%d”, &s.marks[i]);
s.total = s.total + s.marks[i];
}
s.percentage = (s.total/500)*100;
printf(“\n Roll No: %d”,s.roll_No);
printf(“\n Name: %d”,s.Name);
printf(“\n Marks in 5 subjects: %d %d %d %d %d”, s.marks[0], s.marks[1], s.marks[2],
s.marks[3], s.marks[4])
printf(“\n Total: %d”,s.total);
printf(“\n Percentage: %d”,s.percentage);
}
Output:
Enter Student Roll No : 51
Enter Student Name : sravan
Enter Marks 1: 55
Enter Marks 2: 56
Enter Marks 3: 74
Enter Marks 4: 81
Enter Marks 5: 45
Roll No: 51
Name: sravan
Marks in 5 subjects: 55 56 74 81 45
Total: 311
Percentage: 62.20000
type varname ;
type varname ;
};
type varname
type varname
};
} varname ;
What does this imply? Structure members which are arrays can be processed in the same
manner as an ordinary array. Structure member that is a structure can be processed on member at a
time in the same manner as any other structure. These operations are shown below
Consider the structure
struct author{
char first_name[15];
char last_name[15];
};
struct book {
char title[20];
struct author book_author;
int no_of_pages;
float cost;
} cprog;
Several operations to access structure members
cprog.no_of_pages=455;
This statement assigns the value of 455 to cprog.no_of_pages
printf(“Book title is %s”, cprog.title);
This statement passes the array cprog.title to the printf function, so that it could be printed on
console.
printf(“Author’s name %s %s”, cprog.book_author.first_name,Prog.book_author.first_name);
This statement passes two arrays cprog.book_author.first_name and cprog.book_author
last_name to the printf function, both of which are submembers of structure cprog, so that it could
be printed on console.
void main()
{
struct student_detail stu_data = {1, “Raju”, 90.5, 71145,
“Anna University”};
stu_data_ptr = &stu_data;
Output:
Id is: 1
Name is: shruti
Percentage is: 90.500000
College Id is: 71145
College Name is: Mumbai University
9.9 Summary
When you design a program, it is important to choose an optimal way to represent the data
that the program processes. In simple cases, scalar variables and arrays are sufficient. However, in
practical programming context, you need a new form of variable that reflects the real world. For
example, in your program, you may want to refer to an address that holds multiple fields including
house number, street, zip code, state and country.
C provides a special kind of variable called structure. C structure allows you to wrap related
variables that has different data types into a single variable. A structure can contain any valid data
types such as int,char,float,array,pointer or even other structures. Each variable in the structure is
called structure member.
{
struct student
{
int no;
char name[20];
};
struct student s;
s.no = 8;
printf("%d", s.no);
}
(a) Nothing (b) Compile time error
(c) Junk (d) 8
5.
#include<stdio.h>
struct Point
{
int x, y, z;
};
int main()
{
struct Point p1 = {.y = 0, .z = 1, .x = 2};
printf("%d %d %d", p1.x, p1.y, p1.z);
return 0;
}
(a) Compiler Error (b) 2 0 1
(c) 0 1 2 (d) 2 1 0
Answers: 1. (b), 2. (b), 3. (a), 4. (d), 5. (b)
9.13 References
1. https://www.studytonight.com/c/structures-in-c.php
2. https://www.geeksforgeeks.org/structures-c/
3. https://www.zentut.com/c-tutorial/c-structure/
4. https://www.tutorialspoint.com/cprogramming/pdf/c_structures.pdf
Structure:
10.0 Learning Objectives
10.1 Introduction
10.2 Dynamic Memory Allocation Functions
10.3 Summary
10.4 Key Words/Abbreviations
10.5 Learning Activity
10.6 Unit End Questions (MCQ and Descriptive)
10.7 References
10.1 Introduction
Since C is a structured language, it has some fixed rules for programming. One of it includes
changing the size of an array. An array is collection of items stored at continuous memory locations.
As it can be seen that the length (size) of the array above made is 9. But what if there is a
requirement to change this length (size). For Example,
If there is a situation where only 5 elements are needed to be entered in this array. In this
case, the remaining 4 indices are just wasting memory in this array. So there is a
requirement to lessen the length (size) of the array from 9 to 5.
Take another situation. In this, there is an array of 9 elements with all 9 indices filled.
But there is a need to enter 3 more elements in this array. In this case 3 indices more are
required. So the length (size) of the array needs to be changed from 9 to 12.
This procedure is referred to as Dynamic Memory Allocation in C.
Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the size
of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming.
They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
these two region is known as Heap area. This region is used for dynamic memory allocation during
execution of the program. The size of heap keep changing.
Global Variable
Program Permanent
Instruction Storage
Area
Static
Variable
free() functions –
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char name[100];
char *description;
strcpy(name, “Shrutkirti Shelar”);
/* allocate memory dynamically */
description = malloc( 30 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, “Error - unable to allocate required memory\n”);
}
else {
strcpy( description, “Shrutkirti Shelar a CS student”);
}
/* suppose you want to store bigger description */
description = realloc( description, 100 * sizeof(char) );
if( description == NULL ) {
fprintf(stderr, “Error - unable to allocate required memory\n”);
}
else {
strcat( description, “She is in Computer Science class”);
}
printf(“Name = %s\n”, name );
printf(“Description: %s\n”, description );
10.2.1 malloc()
By using malloc() we can create the memory dynamically at initial stage. malloc() required
one argument of type size type that is data type size malloc() will creates the memory in bytes
format. malloc() through created memory initial value is garbage.
malloc() function is used to allocate space in memory during the execution of the program.
malloc() does not initialize the memory allocated during execution. It carries garbage
value.
malloc() function returns null pointer if it couldn’t able to allocate requested amount of
memory.
The name malloc stands for “memory allocation”.
The function malloc() reserves a block of memory of specified size and return apointer of
type void which can be casted into pointer of any form.
Syntax of malloc()
ptr = (cast-type*) malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory
with size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr = (int*) malloc(100 * sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively
and the pointer points to the address of first byte of memory.
Example of malloc():
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{
printf(“Couldn’t able to allocate requested memory\n”);
}
else
{
strcpy( mem_allocation, “God is great”);
}
printf(“Dynamically allocated memory content : “ \
“%s\n”, mem_allocation );
free(mem_allocation);
}
Output:
Dynamically allocated memory content: God is great
10.2.2 calloc(),
calloc() function is also like malloc() function. But calloc() initializes the allocated memory
to zero. But, malloc() doesn’t.
By using calloc() we can create the memory dynamically at initial stage.
calloc() required 2 arguments of type count, size-type.
Count will provide number of elements; size-type is data type size.
calloc() will creates the memory in blocks format.
Initial value of the memory is zero.
C calloc()
The name calloc stands for “contiguous allocation”
The only difference between malloc() and calloc() is that, malloc() allocates single block of
memory whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes
to zero.
Syntax of calloc()
ptr = (cast-type*)calloc(n, element-size);
This statement will allocate contiguous space in memory for an array of nelements. For
example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size
of float, i.e., 4 bytes.
Example of calloc():
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = calloc( 20, sizeof(char) );
if( mem_allocation== NULL )
{
printf(“Couldn’t able to allocate requested memory\n”);
}
else
{
strcpy( mem_allocation, “God is great”);
}
printf(“Dynamically allocated memory content : “ \
“%s\n”, mem_allocation );
free(mem_allocation);
}
Output:
Dynamically allocated memory content: God is great
10.2.3 realloc()
realloc() function modifies the allocated memory size by malloc() and calloc() functions
to new size.
If enough space doesn’t exist in memory of current block to extend, new block is allocated
for the full size of reallocation, then copies the existing data to new block and then frees
the old block.
By using realloc() we can create the memory dynamically at middle stage.
Generally by using realloc() we can reallocation the memory.
C realloc()
If the previously allocated memory is insufficient or more than required, you can change the
previously allocated memory size using realloc().
Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
10.2.4 free()
free() function frees the allocated memory by malloc(), calloc(), realloc() functions and returns
the memory to the system.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn’t get freed on
its own. You must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation == NULL )
{
printf(“Couldn’t able to allocate requested memory\n”);
}
else
{
Output:
Dynamically allocated memory content : God is great
Resized memory : space is extended up to 100 characters
10.2.5 Difference between Static Memory Allocation and Dynamic Memory Allocation
in C
Static Memory Allocation Dynamic Memory Allocation
In static memory allocation, memory is allocated In dynamic memory allocation, memory is allocated
while writing the C program. Actually, user while executing the program. That means at run time.
requested memory will be allocated at compile
time.
Memory size can’t be modified while execution. Memory size can be modified while execution.
Example: Array Example: Linked list
It allocates only single block of requested memory It allocates multiple blocks of requested memory
int *ptr;ptr = malloc( 20 * sizeof(int) );For the int *ptr;Ptr = calloc(20, 20 * sizeof(int)); For the
above, 20*4 bytes of memory only allocated in above, 20 blocks of memory will be created and
one block. Total = 80 bytes each contains 20*4 bytes of memory. Total = 1600
bytes
malloc() doesn’t initializes the allocated memory. calloc () initializes the allocated memory to zero
It contains garbage values
type cast must be done since this function Same as malloc() function int *ptr;ptr = (int*)
returns void pointer int *ptr;ptr = calloc( 20, 20 * sizeof(int) );
(int*)malloc(sizeof(int)*20);
calloc() initializes the allocated memory with 0 malloc() initializes the allocated memory with
value. garbage values.
10.3 Summary
Dynamic memory allocation is an aspect of allocating and freeing memory according to your
needs. Dynamic memory is managed and served with pointers that point to the newly allocated
space of memory in an area which we call the heap. Now you can create and destroy an array of
elements at runtime without any problems.
To sum up, the automatic memory management uses the stack, and the dynamic memory
allocation uses the heap.
The <stdlib.h> library has functions responsible for dynamic memory management.
malloc (): Allocates the memory of requested size and returns the pointer to the first
byte of allocated space.
realloc(): It is used to modify the size of previously allocated memory space.
free(): Frees or empties the previously allocated memory space.
10.7 References
1. https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-
free-and-realloc/
2. https://www.guru99.com/c-dynamic-memory-allocation.html
3. https://www.unf.edu/~wkloster/2220/ppts/malloc.pdf
4. https://www.cs.cmu.edu/~guna/15-123S11/Lectures/Lecture08.pdf
UNIT 11 C PREPROCESSOR
Structure:
11.0 Learning Objectives
11.1 Introduction
11.2 Concepts of Preprocessor
11.3 Preprocessor Directives
11.4 Predefined Macros
11.5 Parameterized Macros.
11.6 Summary
11.7 Key Words/Abbreviations
11.8 Learning Activity
11.9 Unit End Questions (MCQ and Descriptive)
11.10 References
11.1 Introduction
In C compilation model and processes, the C source code is passed to a preprocessor before
being transferred to the compiler. The preprocessor interprets all preprocessor directives or macros
by substituting the macros by their contents.
The preprocessor has its own syntax which is different from the C syntax. All the preprocessor
begins with a hash ( #) sign e.g., #define, #include
File inclusion: Including all the files from library that our program needs. In HLL we
write #include which is a directive for the preprocessor that tells it to include the contents of the
library file specified. For example, #include will tell the preprocessor to include all the contents in
the library file stdio.h.
This can also be written using double quotes – #include “stdio.h”
Macro expansion: Macros can be called as small functions that are not as overhead to process.
If we have to write a function (having a small definition) that needs to be called recursively (again
and again), then we should prefer a macro over a function.
So, defining these macros is done by preprocessor.
#define SI 1000
Preprocessor Syntax/Description
Macro Syntax: #defineThis macro defines constant value and can be any of
the basic data types.
Header file inclusion Syntax: #include <file_name>The source code of the file “file_name”
is included in the main program at the specified place.
Conditional compilation Syntax: #ifdef, #endif, #if, #else, #ifndefSet of commands are included
or excluded in source program before compilation with respect to the
condition.
Other directives Syntax: #undef, #pragma#undef is used to undefine a defined macro
variable. #Pragma is used to call a function before and after main
function in a C program.
Macro: #define
This macro defines constant value and can be any of the basic data types. These constants are
usually defined at the beginning of a program. They may then appear later in the program in place
of the numeric constants, character constants, etc. that the macro may represent. The syntax to use
define macro is as follows:
#define name value
Where name represents a symbolic name, typically written in uppercase letters, and text
represents the sequence of characters that is associated with the symbolic name. Note that text does
not end with a semicolon, since a symbolic constant definition is not a true C statement.
Let’s see an example:
#define PI 3.14
void main()
{
float radius=1.2;
float area_of_circle = PI * radius * radius;
float circumference_of_circle = 2 * PI * radius;
printf(“\n Details of circle”);
printf(“\n Area = %f”, area_of_circle);
printf(“\n Circumference = %f”, circumference_of_circle);
}
In the above program, instead of writing the value of 3.14 for calculating area and circumference
of circle, a constant PI which is defined before the main() method is used.
#define PI 3.14
This statement is called ‘macro definition’ or more commonly, just a ‘macro’. The preprocessor
replaces every occurrence of PI in the program with 3.14.
The source code of the file “file_name” is included in the main( ) function C program where
“#include <file_name>” is mentioned. Of course this assuming that the file being included is existing.
This directive is normally used for very large programs which can be divided into several
different files each containing related functions. These files are #include at the beginning of
main( ) function program file. Secondly, the commonly needed functions and macro definitions can
be stored in a file, and that file can be included in every program later.
The prototypes of all the library functions are grouped into different categories and then
stored in different header files. For example prototypes of all mathematics related functions are
stored in the header file ‘math.h’ which can be included as shown below:
#include<math.h>
The #include directive can be used in two ways as discussed below:
#include “filename”
#include <filename>
#include “sum.c”
#include “c:\employee.c”
It is Link section also called as include section, this section is prefixed by # sign
# include<stdio.h>
# include<conio.h>
# include<math.h>
# include<stdlib.h>
# is preprocessor directive which gives direction to the compiler that include specified
header file from Library to main( ) function program.
Table 11.2: List of Header Files
#include<Ctype.h> All character handling functions are defined in this header file.functionsIt
consist of islower( ), isupper( ), isdigit( )
Examples:
# define true 1
# define false 0
# define EoF – 1
# define product (x, y) ((x) * (y))
Predefined Macros
A predefined macro is a macro that is already understood by the C preprocessor without the
program needing to define it.
Here are some predefined macros in C programming.
Macro Value
__DATE__ A string containing the current date
__FILE__ A string containing the file name
__LINE__ An integer representing the current line number
__STDC__ If follows ANSI standard C, then the value is a nonzero integer
__TIME__ A string containing the current date.
Let’s try the following example - To Get current time using __TIME__
The following program outputs the current time using __TIME__ macro.
1. #include <stdio.h>
2. int main()
3. {
4. printf(“Current time: %s”,__TIME__);
5. }
Output
Current time: 19:54:39
Example:
#include <stdio.h>
int main() {
printf(“File :%s\n”, __FILE__ );
printf(“Date :%s\n”, __DATE__ );
printf(“Time :%s\n”, __TIME__ );
printf(“Line :%d\n”, __LINE__ );
printf(“ANSI :%d\n”, __STDC__ );
}
When the above code in a file test.c is compiled and executed, it produces the following
result –
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
Example:
11.6 Summary
The C preprocessor is a macro processor that is used automatically by the C compiler to
transform your program before actual compilation. It is called a macro processor because it allows
you to define macros, which are brief abbreviations for longer constructs.
The C preprocessor provides four separate facilities that you can use as you see fit:
Inclusion of header files. These are files of declarations that can be substituted into
your program.
Macro expansion. You can define macros, which are abbreviations for arbitrary fragments
of C code, and then the C preprocessor will replace the macros with their definitions
throughout the program.
Conditional compilation. Using special preprocessing directives, you can include or
exclude parts of the program according to various conditions.
Line control. If you use a program to combine or rearrange source files into an
intermediate file which is then compiled, you can use line control to inform the compiler
of where each source line originally came from.
11.10 References
1. https://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html
2. https://www.zentut.com/c-tutorial/c-preprocessor/
3. The C Programming Language Ritchie & kernighan
4. http://www2.cs.uregina.ca/~hilder/cs833/Other%20Reference%20Materials/
The%20C%20Programming%20Language.pdf
Structure:
12.0 Learning Objectives
12.1 Introduction
12.2 File Types
12.3 File Handling Functions
12.4 Summary
12.5 Key Words/Abbreviations
12.6 Learning Activity
12.7 Unit End Questions (MCQ and Descriptive)
12.8 References
12.1 Introduction
File Handling concept in C language is used for store a data permanently in computer memory.
Using this concept we can store our data in Secondary memory (Hard disk). Afilerepresents a
sequence of bytes on the disk where a group of related data is stored. File is created for permanent
storage of data. It is a readymade structure.
All files related function are available instdio.hheader file.
In C language, we use a structurepointer of file typeto declare a file.
File Handling in C:
1. New way of dealing with data is file handling.
2. Data is stored onto the disk and can be retrieve whenever require.
3. Output of the program may be stored onto the disk.
4. In C we have many functions that deals with file handling.
5. A file is a collection of bytes stored on a secondary storage device(generally a disk)
6. Collection of byte may be interpreted as —
– Single character
– Single Word
– Single Line
– Complete Structure.
File Operations
There are 5 major operations can be performed on files
1. Creation of new file
2. Opening an existing file
3. Reading data from file
4. Writing data into file
5. Appending data into file
6. Closing a file.
char buff[255];
fp = fopen(“/tmp/kiran.txt”, “r”);
fscanf(fp, “%s”, buff);
printf(“1 : %s\n”, buff );
fgets(buff, 255, (FILE*)fp);
printf(“2: %s\n”, buff );
fgets(buff, 255, (FILE*)fp);
printf(“3: %s\n”, buff );
fclose(fp);
}
When the above code is compiled and executed, it reads the file created in the previous section
and produces the following result “
1: This
2: is testing for fprintf...
3: This is testing for fputs...
Let’s see a little more in detail about what happened here. First, fscanf() read just This
because after that, it encountered a space, second call is for fgets() which reads the
remaining line till it encountered end of line. Finally, the last call fgets() reads the
second line completely.
Reading Binary File
fread( ) function is used to read from binary file.
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE
*a_file);
Both of these functions should be used to read or write blocks of memories - usually
arrays or structures.
4. If mode is write mode, then it will create new file and data can be written on to the
file.
Writing a File
fputc( ) and fputs( ) functions are used to write characters and strings into text files.
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream
referenced by fp. It returns the written character written on success otherwise EOF if
there is an error. You can use the following functions to write a null-terminated string to
a stream “
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns
a non-negative value on success, otherwise EOF is returned in case of any error. You
can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string
into a file. Try the following example:
Make sure you have /tmp directory available. If it is not, then before proceeding, you must
create this directory on your machine.
#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen(“/tmp/kiranbinary.txt”, “w+”);
fprintf(fp, “This is testing for fprintf...\n”);
fputs(“This is testing for fputs...\n”, fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file kiranbinary.txt in /tmp
directory and writes two lines using two different functions. Let us read this file in the next section.
Example: Write to a text file using fprintf()
#include <stdio.h>
void main()
{
int num;
FILE *fptr;
fptr = fopen(“C:\\kiran.txt”, “w”);
if(fptr == NULL)
{
printf(“Error!”);
exit(1);
}
printf(“Enter num:”);
scanf(“%d”,&num);
fprintf(fptr,”%d”,num);
fclose(fptr);
getch( );
}
This program takes a number from user and stores in the file kiran.txt.
After you compile and run this program, you can see a text file program.txt created in C
drive of your computer. When you open the file, you can see the integer you entered.
fwrite( ) function is used to write into binary file.
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE
*a_file);
5. If mode is append, the file should be already created with some contents and then
we can add the contents at the end of the file.
The syntax for opening a file in append mode is:-
fopen(“E:\\cprogram\\kirantxtfile.txt”,”a”); //For Text Mode
fopen(“E:\\cprogram\\kiranbinfile.bin”, “ab+”); // For Binary Mode
#include <stdio.h>
void main()
{
FILE *fp
file = fopen(“kiran.txt”,”a”);
fprintf(fp, “%s”,”This is just an example of text appended by kiran :)”);
/*append some text*/
fclose(fp);
getch( );
}
6. Close a file by using fclose( ) function.
The fclose( ) function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF (End of File)
if there is an error in closing the file. This EOF is a constant defined in the header file
stdio.h.
FILE *fp;
fclose(fp);
Appending File will be opened for appending some thing in file Retained
r – Opens a file in read mode and sets pointer to the first character in the file. It
returns null if file does not exist.
w – Opens a file in write mode. It returns null if file could not be opened. If file exists,
data are overwritten.
a – Opens a file in append mode. It returns null if file couldn’t be opened.
r+ – Opens a file for read and write mode and sets pointer to the first character in the
file.
w+ – Opens a file for read and write mode and sets pointer to the first character in the
file.
a+ – Opens a file for read and write mode and sets pointer to the first character in the
file. But, it can’t modify existing contents.
wb+ Open for both reading and writing in binary mode. If the file exists, its contents are
overwritten. If the file does not exist,
it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be
created.
ab+ Open for both reading and appending in If the file does not exists, it will be
binary mode. created.
A text file can be a stream of characters that a computer can process sequentially. It is not only
processed sequentially but only in forward direction. For this reason a text file is usually opened
for only one kind of operation (reading, writing, or appending) at any given time.
Similarly, since text files only process characters, they can only read or write data one character
at a time. (In C Programming Language, Functions are provided that deal with lines of text, but
these still essentially process data one character at a time.)
When you open those files, you will see all the contents within the file as plain text. You can
easily edit or delete the contents. They take minimum effort to maintain are easily readable and
provide least security and takes bigger storage space.
Binary Files
Binary file are mostly the .bin files in your computer. Instead of storing data in plain text, they
store it in the binary form (0s and 1s). They can hold higher amount of data are not readable easily
and provides a better security than text files.
Binary files can be either processed sequentially or, depending on the needs of the application,
they can be processed using random access techniques. In C Programming Language, processing a
file using random access techniques involves moving the current file position to an appropriate
place in the file before reading or writing data. This indicates a second characteristic of binary files.
They a generally processed using read and write operations simultaneously.
‘w’: Truncate file to zero length or create text file for writing. The stream is positioned at the
beginning of the file.
‘w+’: Open for reading and writing. The file is created if it does not exist, otherwise it is
truncated. The stream is positioned at the beginning of the file.
‘a’: Open for appending (writing at end of file). The file is created if it does not exist. The
stream is positioned at the end of the file.
‘a+’: Open for reading and appending (writing at end of file). The file is created if it does not
exist. The initial file position for reading is at the beginning of the file, but output is
always appended to the end of the file.
The fopen() function returns a FILE stream pointer on success while it returns NULL in case
of a failure.
12.3.2 fclose()
The fclose() function first flushes the stream opened by fopen() and then closes the underlying
descriptor. Upon successful completion this function returns 0 else end of file (eof) is returned. In
case of failure, if the stream is accessed further then the behaviour remains undefined.
int fclose(FILE *fp);
For example, Program to open and close a file:
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fptr;
If((fptr = fopen(“TEST”,”w”))==NULL)
{
printf(“Cannot open file\n”);
exit(1);
}
if(fclose(fptr))
pritf(“File close error\n”);
return o;
}
12.3.3 fgetc()
The fgetc() function reads a character from the input file referenced by fp. The return value is
the character read, or in case of any error, it returns EOF. The following function allows to read a
string from a stream
char *fgets( char *buf, int n, FILE *fp );
Example :
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
Output:
Hello friends, my name is Shruti
Data written successfully...
12.3.4 fputc()
The function fputc() writes the character value of the argument c to the output stream referenced
by fp. It returns the written character written on success otherwise EOF if there is an error. You can
use the following functions to write a null-terminated string to a stream.
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-
negative value on success, otherwise EOF is returned in case of any error.
You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string
into a file. Make sure you have /tmp directory available. If it is not, then before proceeding, you
must create this directory on your machine.
Following is the simplest function to write individual characters to a stream “
int fputc( int c, FILE *fp );
Example:
#include <stdio.h>
main() {
FILE *fp;
fp = fopen(“/tmp/test.txt”, “w+”);
fprintf(fp, “This is testing for fprintf...\n”);
fputs(“This is testing for fputs...\n”, fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory
and writes two lines using two different functions.
12.3.5 fgets()
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It
copies the read string into the bufferbuf, appending a null character to terminate the string.
If this function encounters a newline character ‘\n’ or the end of the file EOF before they have
read the maximum number of characters, then it returns only the characters read up to that point
including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...)
function to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen(“/tmp/test.txt”, “r”);
fscanf(fp, “%s”, buff);
printf(“1 : %s\n”, buff );
Output:
1. This
2. is testing for fprintf...
3. This is testing for fputs...
12.3.6 fputs()
The fputs() function is used to write string (array of characters) to the file.
fputs(char str[], FILE *fp);
The fputs() function takes two arguments, first is the string to be written to the file and second
is the file pointer where the string will be written.
#include<stdio.h>
void main()
{
FILE *fp;
char str[];
fp = fopen(“kiran.txt”, “w”); //Statement 1
if(fp == NULL)
{
printf(“\nCan’t open file or file doesn’t exist.”);
exit(0);
}
do
{
gets(str);
fputs(str,fp);
}while(strlen(str)!=0);
printf(“\nData written successfully...”);
fclose(fp);
}
Output:
C is a general-purpose programming language.
It is developed by Dennis Ritchie.
12.3.7 fscanf()
The fscanf() function is used to read mixed type form the file.
Syntax of fscanf() function
fscanf(FILE *fp, “format-string”,var-list);
The fscanf() function is similar to scanf() function except the first argument which is a file
pointer that specifies the file to be read.
Output:
Data in file...
1 Shruti 81.65
2 Kiran 82.62
In the above example, Statement 1 will open an existing file file.txt in read mode and statement
2 will read all the data up to EOF(end-of-file) reached.
12.3.8 fprintf()
So far we have seen writing of characters, strings and integers in different files. This is not
enough if we need to write characters, strings and integers in one single file, for that purpose we use
fprintf() function. The fprintf() function is used to write mixed type in the file.
Syntax of fprintf() function
fprintf(FILE *fp, “format-string”,var-list);
The fprintf() function is similar to printf() function except the first argument which is a file
pointer that specifies the file to be written.
exit(0);
}
do
{
printf(“\nEnter Roll :”);
scanf(“%d”,&roll);
printf(“\nEnter Name :”);
scanf(“%s”,name);
printf(“\nEnter Marks :”);
scanf(“%f”,&marks);
fprintf(fp, “%d%s%f”,roll,name,marks);
printf(“\nDo you want to add another data (y/n) :”);
ch = getche();
}while(ch==‘y’ || ch==‘Y’);
printf(“\nData written successfully...”);
fclose(fp);
}
Output:
Enter Roll : 11
Enter Name : Shruti
Enter Marks : 78.53
Do you want to add another data (y/n) : y
Enter Roll : 21
Enter Name : Kirti
Enter Marks : 89.62
Do you want to add another data (y/n) : n
Data written successfully...
12.3.9 getw()
The getw() function is used to read integer value form the file.
Syntax of getw() function
int getw(FILE *fp);
The getw() function takes the file pointer as argument from where the integer value will be
read and returns returns the end-of-file if it has reached the end of file.
Output:
Data in file...
78
45
63
In the above example, Statement 1 will open an existing file file.txt in read mode and statement
2 will read all the integer values up to EOF(end-of-file) reached.
12.3.10 putw()
The putw() function is used to write integers to the file.
{
printf(“\nEnter any number :”);
scanf(“%d”,&num);
putw(num,fp);
printf(“\nDo you want to another number :”);
ch = getche();
}while(ch==‘y’||ch==‘Y’);
printf(“\nData written successfully...”);
fclose(fp);
}
Output:
Enter any number : 78
Do you want to another number : y
Enter any number : 45
Do you want to another number : y
Enter any number : 63
Do you want to another number : n
Data written successfully...
In the above example, statement 1 will create a file named file.txt in write mode. Statement 2
is a loop, which take integer values from user and write the values to the file.
In case of success, fread/fwrite return the number of bytes actually read/written from/to the
stream opened by fopen function. In case of failure, a lesser number of byes (then requested to read/
write) is returned.
/* Open, Read and close a file: reading string by string */
# include <stdio.h>
int main( )
{
FILE *fp ;
char data[50] ;
printf(“Opening the file kiran.c in read mode”) ;
fp = fopen(“kiran.c”, “r”) ;
if ( fp == NULL )
{
printf(“Could not open file kiran.c”) ;
}
printf(“Reading the file kiran.c”) ;
while( fgets (data, 50, fp ) != NULL)
printf( “%s”, data ) ;
printf(“Closing the file kiran.c”) ;
fclose(fp) ;
}
Output:
Opening the file kiran.c in read mode
Reading the file kiran.c
Hai, How are you?
Closing the file kiran.c
Output:
OpenIng The File Kiran.c In Write Mode
Enter Some Text From Keyboard To Write In The File Kiran.c
Hai, How are you?
Closing the file kiran.c
12.3.12 fseek()
The fseek() function is used to set the file position indicator for the stream to a new position.
This function accepts three arguments. The first argument is the FILE stream pointer returned by
the fopen() function. The second argument ‘offset’ tells the amount of bytes to seek. The third
argument ‘whence’ tells from where the seek of ‘offset’ number of bytes is to be done. The available
values for whence are SEEK_SET, SEEK_CUR, or SEEK_END. These three values (in order)
depict the start of the file, the current position and the end of the file.
Upon success, this function returns 0, otherwise it returns -1.
int fseek(FILE *stream, long offset, int whence);
To perform Input/Output Operation on files we need below functions.
#include<stdio.h>
#include<string.h>
#define SIZE 1
#define NUMELEM 5
void main(void)
{
FILE* fd = NULL;
char buff[100];
memset(buff,0,sizeof(buff));
fd = fopen(“kiran.txt”, “rw+”);
if(NULL == fd)
{
printf(“\n fopen() Error!!!\n”);
return 1;
}
printf(“\n File opened successfully through fopen()\n”);
if(SIZE*NUMELEM != fread(buff,SIZE,NUMELEM,fd))
{
printf(“\n fread() failed\n”);
return 1;
}
printf(“\n Some bytes successfully read through fread()\n”);
printf(“\n The bytes read are [%s]\n”,buff);
if(0 != fseek(fd,11,SEEK_CUR))
{
printf(“\n fseek() failed\n”);
return 1;
}
printf(“\n fseek() successful\n”);
if(SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd))
{
printf(“\n fwrite() failed\n”);
return 1;
}
printf(“\n fwrite() successful, data written to text file\n”);
fclose(fd);
printf(“\n File stream closed through fclose()\n”);
getch( );
}
The code above assumes that you have a test file “kiran.txt” placed in the same location from
where this executable will be run.
Initially the content in file is:
$ cat kiran.txt
hello everybody
Now, run the code :
$ ./fileHandling
File opened successfully through fopen()
Some bytes successfully read through fread()
The bytes read are [hello]
fseek() successful
fwrite() successful, data written to text file
File stream closed through fclose()
Again check the contents of the file kiran.txt. As you see below, the content of the file was
modified.
$ cat kiran.txt
hello everybody
hello
12.4 Summary
So far the operations using C program are done on a prompt / terminal which is not stored
anywhere. But in the software industry, most of the programs are written to store the information
fetched from the program. One such way is to store the fetched information in a file. Different
operations that can be performed on a file are:
1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
2. Opening an existing file (fopen)
3. Reading from file (fscanf or fgetc)
4. Writing to a file (fprintf or fputs)
5. Moving to a specific location in a file (fseek, rewind)
6. Closing a file (fclose)
The text in the brackets denotes the functions used for performing those operations.
12.8 References
1. https://www.geeksforgeeks.org/basics-file-handling-c/
2. http://letsfindcourse.com/technical-questions/c/file-handling
1. Write a program that reads two nos. from keyboard and gives their addition,
subtraction, multiplication, division and modulo
2. The distance between two cities (In KM) is input through keyboard. Write a
program to convert and print this distance in metres, feet, inches and centimetres.
#include<stdio.h>
#include<conio.h>
void main()
{
float km,m,cm,f,in;
clrscr();
printf("Enter distance in kilometres: ");
scanf("%f",&km);
m=km*1000;
cm=km*1000*100;
f=km*3280.84;
in=km*39370.08;
printf("The distance in feet: %f\n"f);
printf("The distance in inches: %f\n"in);
printf("The distance in metres: %f\n"m);
printf("The distance in Centifeet: %f\n"cm);
getch();
}
Output:
#include <stdio.h>
int main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
5. Write a program to select and print the largest of the three nos. using Nested-If-
Else statement.
1. #include <stdio.h>
2. int main() {
3. double n1, n2, n3;
4. printf("Enter three numbers: ");
5. scanf("%lf %lf %lf", &n1, &n2, &n3);
6.
7. if (n1 >= n2) {
8. if (n1 >= n3)
9. printf("%.2lf is the largest number.", n1);
10. else
11. printf("%.2lf is the largest number.", n3);
12. } else {
13. if (n2 >= n3)
14. printf("%.2lf is the largest number.", n2);
15. else
16. printf("%.2lf is the largest number.", n3);
17. }
18.
19. return 0;
20. }
Output:
1. #include <stdio.h>
2. int main() {
3. char operator;
4. double first, second;
5. printf("Enter an operator (+, -, *,): ");
6. scanf("%c", &operator);
7. printf("Enter two operands: ");
8. scanf("%lf %lf", &first, &second);
9.
7. Write a program to find sum of all integers greater than 100 and less than 200
and are divisible by 5.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, sum=0;
clrscr();
printf("\n Numbers between 100 and 200 which is divisible by 5");
for(i=101;i<200;i++)
{
if(i%5==0)
{
printf("\n %d",i);
sum= sum + i;
}
}
printf("\n sum = %d",sum);
getch();
}
Output:
Numbers between 100 and 200 which is divisible by 5
105
110
115
120
125
130
135
140
145
150
155
160
165
170
175
180
185
190
195
sum = 2850
x x x2 x3
8. Write a C program to implement e 1 ,
1! 2! 3!
1. #include<stdio.h>
2. #define MAX 15
3. void main()
4. {
5. int A[MAX][MAX],B[MAX][MAX],C[MAX][MAX],I,J,K,M,N,R,S,CH;
6. clrscr();
7. printf("ENTER THE SIZE OF A MATRIX (M X N) : \n");
8. printf("ENTER VALUE FOR M (LESS THAN 15) :");
9. scanf("%d",&M);
10. printf("ENTER VALUE FOR N (LESS THAN 15) :");
11. scanf("%d",&N);
12. printf("\nENTER THE SIZE OF B MATRIX (R X S) : \n");
13. printf("ENTER VALUE FOR R (LESS THAN 15) :");
14. scanf("%d",&R);
15. printf("ENTER VALUE FOR S (LESS THAN 15) :");
16. scanf("%d",&S);
17. printf("\nSELECT UR CHOICE (1.ADD 2.SUB 3.MULT) : ");
18. scanf("%d",&CH);
19. switch(CH)
20. {
21. case 1 :
22. {
23. if(M==R && N==S)
24. {
25. printf("ENTER %d X %d MATRIX A VALUES\n",M,N);
26. for(I=0;I<M;I++)
27. {
28. for(J=0;J<N;J++)
29. {
30. scanf("%d",&A[I][J]);
31. }
32. }
33. printf("ENTER %d X %d MATRIX B VALUES\n",R,S);
34. for(I=0;I<R;I++)
35. {
36. for(J=0;J<S;J++)
37. {
38. scanf("%d",&B[I][J]);
39. }
40. }
41. for(I=0;I<M;I++)
42. {
43. for(J=0;J<N;J++)
44. {
45. C[I][J]=A[I][J]+B[I][J];
46. }
47. }
48. printf("\nRESULT %d X %d MATRIX C VALUES ARE :\n",M,N);
49. for(I=0;I<M;I++)
50. {
51. for(J=0;J<N;J++)
52. {
53. printf("%d\t",C[I][J]);
54. }
55. printf("\n");
56. }
57. }
58. else
59. {
60. printf("\nERROR : CONDITION FOR ADDITION");
61. printf(" MATRICES IS NOT SATISFIED!");
62. }
63. break;
64. }
65. case 2 :
66. {
67. if(M==R && N==S)
68. {
69. printf("ENTER %d X %d MATRIX A VALUES\n",M,N);
70. for(I=0;I<M;I++)
71. {
72. for(J=0;J<N;J++)
73. {
74. scanf("%d",&A[I][J]);
75. }
76. }
77. printf("ENTER %d X %d MATRIX B VALUES\n",R,S);
78. for(I=0;I<R;I++)
79. {
80. for(J=0;J<S;J++)
81. {
82. scanf("%d",&B[I][J]);
83. }
84. }
85. for(I=0;I<M;I++)
86. {
87. for(J=0;J<N;J++)
88. {
89. C[I][J]=A[I][J]-B[I][J];
90. }
91. }
92. printf("\nRESULT %d X %d MATRIX C VALUES ARE :\n",M,N);
93. for(I=0;I<M;I++)
94. {
95. for(J=0;J<N;J++)
96. {
97. printf("%d\t",C[I][J]);
98. }
99. printf("\n");
100. }
101. }
102. else
103. {
104. printf("\nERROR : CONDITION FOR SUBTRACTION");
105. printf(" MATRICES IS NOT SATISFIED!");
106. }
107. break;
108. }
109. case 3 :
110. {
111. if(N==R)
112. {
113. printf("ENTER %d X %d MATRIX A VALUES\n",M,N);
114. for(I=0;I<M;I++)
115. {
116. for(J=0;J<N;J++)
117. {
118. scanf("%d",&A[I][J]);
119. }
120. }
121. printf("ENTER %d X %d MATRIX B VALUES\n",R,S);
122. for(I=0;I<R;I++)
123. {
124. for(J=0;J<S;J++)
125. {
126. scanf("%d",&B[I][J]);
127. }
128. }
129. for(I=0;I<M;I++)
130. {
131. for(J=0;J<S;J++)
132. {
133. C[I][J]=0;
134. for(K=0;K<R;K++)
135. {
136. C[I][J]=C[I][J]+A[I][K]*B[K][J];
137. }
138. }
139. }
140. printf("\nRESULT %d X %d MATRIX C VALUES ARE :\n",M,S);
141. for(I=0;I<M;I++)
142. {
143. for(J=0;J<S;J++)
144. {
145. printf("%d\t",C[I][J]);
146. }
147. printf("\n");
148. }
149. }
150. else
151. {
152. printf("\nERROR : CONDITION FOR MULTIPLICATION");
153. printf(" MATRICES IS NOT SATISFIED!");
154. }
155. break;
156. }
157. default:
158. {
159. printf("YOU ENTERED WRONG CHOICE !!!");
160. }
161. }
162. getch();
163. }
Output:
(a) Program to accept name of the user through gets() and print string through puts()
function.
#include<stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
puts(name); //Function to display string.
return 0;
}
(b) Write a program in c to Calculate Length of String without Using strlen() Function
#include <stdio.h>
int main() {
char s[] = "Programming is fun";
int i;
for (i = 0; s[i] != '\0'; ++i);
printf("Length of the string: %d", i);
return 0;
}
Output:
Length of the string: 18
(c) Write a program in c to Copy String Without Using strcpy()
#include <stdio.h>
int main() {
char s1[100], s2[100], i;
printf("Enter string s1: ");
fgets(s1, sizeof(s1), stdin);
Output:
#include<stdio.h>
int main() {
int rows, coef=1, space, i, j;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i=0; i<rows; i++) {
for (space=1; space <= rows-i; space++)
printf(" ");
for (j=0; j<=i; j++) {
if (j==0 || i==0)
coef = 1;
else
coef=coef*(i-j+1)/j;
printf("%4d", coef);
}
printf("\n");
}
return 0;
}
{
int n,p;
clrscr();
printf(“Enter a number : “);
scanf(“%d”,&n);
p=prime(n);
if(p==1)
printf(“%d is prime\n”,n);
else
printf(“%d is not prime\n”,n);
getch();
return 0;
}
int prime(int n)
{
int i;
for(i=2;i<n;i++)
{
if(n%i==0)
return 0;
}
return 1;
}
Output:
Enter a number : 18
18 is not prime
Enter a number : 5
5 is prime
6. Define a structure type, personal, that would contain person name, date of joining
and salary. Using this structure, write a program to read this information for one
person from the key board and print the same on the screen.
#include <stdio.h>
struct personal
{
char person_name[100];
char join_date[100];
float salary;
};
struct personal p;
int main()
{
printf("Enter Name of the person :- ");
scanf("%s",p.person_name);
printf("Enter Joining Date of the person :- ");
scanf("%s",p.join_date);
printf("Enter Salary of the person :- ");
scanf("%f",&p.salary);
printf("\nName of the person :- %s\n",p.person_name);
printf("Joining Date of the person :- %s\n",p.join_date);
printf("Salary of the person :- %0.2f\n",p.salary);
}
Output:
#include<stdio.h>
#include<conio.h>
#include<string.h>
struct cricket
{
char nm[20],team[20];
int avg;
};
#define total 5
int main()
{
struct cricket player[total],temp;
int i,j;
clrscr();
for(i=0;i<total;i++)
{
printf(“For player %d\n”,i+1);
printf(“Enter the name of player : “);
fflush(stdin);
gets(player[i].nm);
printf(“Enter the team : “);
fflush(stdin);
gets(player[i].team);
printf(“Enter the batting average : “);
fflush(stdin);
scanf(“%d”,&player[i].avg);
}
printf(“\nTeam Name Average\n”);
printf(” \n”);
for(i=0;i<total;i++)
{
printf(“%-10s %-10s %7d\n”,player[i].team,player[i].nm,player[i].avg);
}
getch();
return 0;
}
Output:
For player 1
Enter the name of player : Radhe
Enter the team : India
Enter the batting average : 100
For player 2
Enter the name of player : Tiwari
Enter the team : Pakistan
Enter the batting average : 5
For player 3
Enter the name of player : Tendulkar
Enter the team : India
Enter the batting average : 45
For player 4
Enter the name of player : Dhoni
Enter the team : India
Enter the batting average : 48
For player 5
Enter the name of player : Yuvi
Enter the team : India
Enter the batting average : 39
Team Name Average
India Radhe 100
Pakistan Tiwari 5
India Tendulkar 45
India Dhoni 48
India Yuvi 39
PROGRAMS ON POINTERS
1. Write a program using pointer and function to determine the length of string.
#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;
printf("Enter a string to calculate its length\n");
gets(a);
length = strlen(a);
printf("Length of the string = %d\n", length);
return 0;
}
Output:
#include <stdio.h>
//Macro for maximum number of characters in a string
#define MAX 100
int main()
{
//declare string variables
char str1[MAX]={0};
char str2[MAX]={0};
//read strings
printf("Enter string 1: ");
scanf("%[^\n]s",pStr1);
printf("Enter string 2: ");
getchar(); //read & ignore extra character
scanf("%[^\n]s",pStr2);
//print strings
printf("string1: %s\nstring2: %s\n",pStr1,pStr2);
//comparing strings
for(loop=0; (*(pStr1+loop))!='\0'; loop++)
{
if(*(pStr1+loop) != *(pStr2+loop))
{
flag=0;
break;
}
}
if(flag)
printf("Strings are same.\n");
else
printf("Strings are not same.\n");
return 0;
}
Output:
Output:
#include <stdio.h>
#include <string.h>
int main()
{
char source[1000], destination[1000];
printf("Input a string\n");
gets(source);
strcpy(destination, source);
printf("Source string: %s\n", source);
printf("Destination string: %s\n", destination);
return 0;
}
Output:
5. Write a program using pointer to read an array if integer and print element in
reverse order.
#include <stdio.h>
int main()
{
int n, c, d, a[100], b[100];
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter array elements\n");
for (c = 0; c < n ; c++)
scanf("%d", &a[c]);
// Copying elements into array b starting from the end of array a
for (c = n - 1, d = 0; c >= 0; c--, d++)
b[d] = a[c];
// Copying reversed array into the original, we are modifying the original array.
for (c = 0; c < n; c++)
a[c] = b[c];
printf("The array after reversal:\n");
for (c = 0; c < n; c++)
printf("%d\n", a[c]);
return 0;
}
Output:
6. Write a program that uses a table of integers whose size will be specified
interactively at run time.
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *p, *table;
int size;
printf("\nWhat is the size of table?");
scanf("%d",&size);
printf("\n");
if((table = (int*)malloc(size *sizeof(int))) == 0)
{
printf("No space available \n");
exit(1);
}
printf("\n Address of the first byte is %u \n", table);
/* Reading table values*/
printf("\nInput table values\n");
for (p=table; p<table + size; p++)
scanf("%d",p);
/* Printing table values <span id="IL_AD3" class="IL_AD">in reverse</span>
order*/
for (p = table + size -1; p >= table; p --)
printf("%d is stored at address %u \n",*p,p);
getch();
}
Output:
What is the size of the table? 5
Address of the first byte is 2262
Input table values
11 12 13 14 15
15 is stored at address 2270
14 is stored at address 2268
13 is stored at address 2266
12 is stored at address 2264
11 is stored at address 2262
7. C program to input and print text using Dynamic Memory Allocation
Output:
1. Write a program which reads diameter and height of a cone and calculate its
volume using macros.
*
* C Program to Find the volume and surface area of cone
*/
#include <stdio.h>
#include <math.h>
int main()
{
float radius, height;
float surface_area, volume;
printf("Enter value of radius and height of a cone :\n ");
scanf("%f%f", &radius, &height);
surface_area = (22 / 7) * radius * (radius + sqrt(radius * radius + height * height));
volume = (1.0/3) * (22 / 7) * radius * radius * height;
printf("Surface area of cone is: %.3f", surface_area);
printf("\n Volume of cone is : %.3f", volume);
return 0;
}
2. Write a C program to read file kiran.txt and all data character wise.
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp=fopen("kiran.txt","r");
if(fp==NULL)
{
printf("file does not exists");
}
else
{
while(ch!=EOF)
{
ch=getc(fp);
putch(ch);
}
}
fclose(fp);
getch();
}
3. Write a program in C program to illustate fgetc() function
#include <stdio.h>
int main ()
{
// open the file
FILE *fp = fopen("test.txt","r");
// Return if could not open file
#include<stdio.h>
int main()
{
int i = 0;
FILE *fp = fopen("output.txt","w");
// Return if could not open file
if (fp == NULL)
return 0;
char string[] = "good bye", received_string[20];
for (i = 0; string[i]!='\0'; i++)
// Input string into the file
// single character at a time
fputc(string[i], fp);
fclose(fp);
fp = fopen("output.txt","r");