Decap010 Programming in C
Decap010 Programming in C
DECAP010
Edited by
Balraj Kumar
Programming In C
Edited By:
Balraj Kumar
Title: PROGRAMMING IN C
Publisher Address: Lovely Professional University, Jalandhar Delhi GT road, Phagwara - 144411
ISBN: 978-93-94068-23-0
Unit 1: Introduction 1
Prikshat Kumar Angra, Lovely Professional University
Unit 4: Operations 46
Prikshat Kumar Angra, Lovely Professional University
Unit 5: Decision making statements 58
Prikshat Kumar Angra, Lovely Professional University
Unit 6: Loop Statements 84
Prikshat Kumar Angra, Lovely Professional University
Unit 7: Functions 105
Prikshat Kumar Angra, Lovely Professional University
Unit 8: Storage Classes 123
Prikshat Kumar Angra, Lovely Professional University
Objectives
After studying this unit, you will be able to:
• Understand Programming language
• Discuss C Programming
• Different stages in program developmentusing codeblocks IDE
• Programing methodologies
Introduction
Computer is an electronic device which works on the instructions provided by the user. As the
computer does not understand natural language, it is required to provide the instructions in some
computer understandable language. Such a computer understandable language is known as
Programming language.
A computer programming language consists of a set of symbols and characters, words, and
grammar rules that permit people to construct instructions in the format that can be interpreted by
the computer system Computer Programming is the art of making a computer do what you want it
Instruction Format
We already know that all commuters use binary digits (0s and 1s) for performing operations.
Hence, most computers machine language consists of strings of binary numbers and is the only one
the CPU directly understands. When stored inside the computer, the symbols which make up the
machine language program are made up of 1s and 0s.
A typical program instruction to print out a number on the printer might be.
The program to add two numbers in memory and print the result look something like the
Following:
001000000000001100111001
001111000000111111000111
100111100011101100110101
101100010101010101110000
000000000000000000000000
This is obviously not a very easy language to learn, partly because it is difficult to read and
understand and partly because it is written in a number system with which we are not familiar. But
it will be surprising to note that some of the first programmers, who worked with the first few
computers, actually wrote their programs in binary form as above. Since human programmers are
more familiar with the decimal number system, most of them preferred to write the computer
instructions in decimal, and leave the input device to convert these to binary. In fact, without too
much effort, a computer can be wired so that instead of using long numbers. With this change, the
preceding program appears as follows:
10001471
14002041
30003456
50773456
00000000
The set of instruction codes, whether in binary or decimal, which can be directly understood by the
CPU of a computer without the help of a translating program, is called a machine code or machine
language. Thus, a machine language program need not necessarily be coded as strings of binary
digits (1s and 0s). It can also be written using decimal digits if the circuitry of the computer being
used permits this.
3. Error code
Here mnemonic MOV represents ‘transfer’ operation and AX, DX are used to represent the
registers. One of the first steps in improving the program preparation process was to
substitute letter symbols mnemonics for the numeric operation codes of machine language.
A mnemonic is any kind of mental trick we use to help us remember. Mnemonics come in
various shapes and sizes, all of them useful in their own way.
All computers have the power of handling letters as well as numbers. Hence, a computer can be
taught to recognize certain combination of letter or numbers. It can be taught to substitute the
number 14 every time it sees the symbol ADD, substitute the number 15 every time it sees the
symbol SUB, and so forth. In this way, the computer can be trained to translate a program written
with symbols instead of numbers into the computer’s own machine language. Then we can write
program for the computer using symbols instead of numbers, and have the computer do its own
translating. This makes it easier for the programmer, because he can use letters, symbols, and
mnemonics instead of numbers for writing his programs.
The preceding program that was written in machine language for adding two numbers and
printing out the result could be written in the following way:
CLA A
ADD B
STA C
TYP C
Which would mean “take A, add B, store the result in C, type C, and halt.” The computer by means
of a translating program, would translate each line of this program into the corresponding machine
language program.
1. The assembly step involves translating the source code into object code and generating an
intermediate .OBJ (object file) or module. The assembler also creates a header immediately in front
of the generated .OBJ module; part of the header contains information about incomplete addresses.
The .OBJ module is not quite in executable form.
2. The link step involves converting the .OBJ module to an .EXE machine code module. The linker’s
tasks include completing any address left open by the assembler and combining separately
assembled programs into one executable module.
The linker
(a) Combines assembled module into one executable program
(b) Generates an .EXE module and initializes with special instructions to facilitate its
3. The last step is to load the program for execution. Because the loader knows where the program
is going to load in memory, it is now able to resolve any remaining address still left incomplete in
the header. The loader drops the header and creates a program segment prefix (PSP) immediately
before the program is loaded in memory.
The machine-level language comes at the The assembly language comes above the
lowest level in the hierarchy, so it has zero machine language means that it has less
abstraction level from the hardware. abstraction level from the hardware.
It does not require any translator as the In assembly language, the assembler is used to
machine code is directly executed by the convert the assembly code into machine code.
LET X = 7
LET Y = 10
LET sum = X+Y
PRINT SUM
END
The time and cost of creating machine and assembly languages was quite high. And this was the
prime motivation for the development of high level languages. Because of the difficulty of working
with low-level languages, high-level languages were developed to make it easier to write computer
programs. High level programming languages create computer programs using instructions that
are much easier to understand than machine or assembly language code because you can use
words that more clearly describe the task being performed.
When writing a program in a high-level language, then the whole attention needs to be
paid to the logic of the problem. A compiler is required to translate a high-level language into a
low-level language.
High-level languages include FORTRAN, COBOL, BASIC, PASCAL, C, C++ and JAVA.
It requires the assembler to convert the It requires the compiler to convert the high-
assembly code into machine code. level language instructions into machine code.
The machine code cannot run on all machines, The high-level code can run all the platforms,
so it is not a portable language. so it is a portable language.
Debugging and maintenance are not easier in a Debugging and maintenance are easier in a
low-level language. high-level language.
• C programming language can be used to design the system software like operating system
and Compiler.
• To develop application software like database and spread sheets.
• For Develop Graphical related application like computer and mobile games.
• To evaluate any kind of mathematical equation use c language.
• C programming language can be used to design the compilers.
• UNIX Kernel is completely developed in C Language.
• For Creating Compilers of different Languages which can take input from other language
and convert it into lower level machine dependent language.
• C programming language can be used to design Operating System.
1.10 Evolution of C
By the late fifties, there were many computer languages into existence. However, none of them
were general purpose. They served better in a particular type of programming application more
than others. Thus, while FORTRAN was more suited for engineering programming, COBOL was
better for business programming. At this stage people started thinking that instead of learning so
many languages for different programming purposes, why not have a single computer language
that can be used for programming any type of application.
In 1960, to this end, an international committee was constituted which came out with a language
named ALGOL-60. This language could not become popular because it was too general and highly
abstract.
In 1963, a modified ALGOL-60 by reducing its generality and abstractness, a new language, CPL
(Combined Programming Language) was developed at Cambridge University. CPL, too turned out
to be very big and difficult to learn.
In 1967, Martin Richards, at Cambridge University, stripped down some of the complexities from
CPL retaining useful features and created BCPL (Basic CPL). Very soon it was realized that BCPL
was too specific and much too less powerful.
In 1970, Ken Thompson, at AT&T labs. Developed a language known by the name B as another
simplification to CPL. B, too, like its predecessors, turned out to be very specific and limited in
application.
In 1972, Ritchie, at AT&T, took the best of the two BCPL and B, and developed the language C. C
was truly a general purpose language, easy to learn and very powerful.
In 1972, Ritchie, at AT&T, took the best of the two BCPL and B, and developed the language C. C
was truly a general purpose language, easy to learn and very powerful.
Code blocks is an IDE for running C and C++ programs on different operating systems
like Windows, Linux and Mac OS.
Debugger
This program helps us identify syntax errors in the source code.
Pre Processor
There are certain special instructions within the source code identified by the # symbol that are
carried on by a special program called a preprocessor.
Compiler
The process of converting the C source code to machine code and is done by a program called
Compiler.
Linker
The machine code relating to the source code you have written is combined with some other
machine code to derive the complete program in an executable file. This is done by a program
called the linker.
C Program Code
#include<stdio.h>
main(){
printf(“Hello World”);
}
Click on empty file link and save that file with name hello.c and write code.
Like each other language, 'C' additionally has its own character set. A program is a bunch of
directions that, when executed, produce a yield. The information that is prepared by a program
comprises of different characters and images. The yield produced is additionally a mix of characters
and images.
A character set in 'C' is divided into
• Letters
• Numbers
• Special characters
• White spaces (blank spaces)
Letters
• Uppercase characters (A-Z)
• Lowercase characters (a-z)
Numbers
White spaces
• Blank space
• New line
• Carriage return
• Horizontal tab
Special characters
• Special characters in 'C' are shown in the given table,
~ (tilde) / (division)
Summary
• A computer programming language consists of a set of symbols and characters, words,
and grammar rules that permit people to construct instructions in the format that can be
interpreted by the computer system Computer Programming is the art of making a
computer do what you want it to do.
• Machine language, or machine code, is a low-level language comprised of binary digits
(ones and zeros).
• Assembly languages are also known as second generation languages. These languages
substitute alphabetic symbols for the binary codes of machine language.
• High-level languages include FORTRAN, COBOL, BASIC, PASCAL, C, C++ and JAVA.
• C is a general-purpose, structured programming language. Structured Languages have a
characteristic program structure and associated set of static scope rules. C was originated
in Bell Telephone Laboratories presently known as AT & T Bell Laboratories by Dennis
Ritchie in 1970.
• To develop application software like database and spread sheets.
• For Develop Graphical related application like computer and mobile games.
• Keywords have fixed meanings, and the meaning cannot be changed. They act as a
building block of a 'C' program. There are a total of 32 keywords in 'C'
• Code blocks is an IDE for running C and C++ programs on different operating systems
like Windows, Linux and Mac OS.
• An identifier is nothing but a name assigned to an element in a program. Example, name
of a variable, function, etc.
Keywords
Programming:Computer programming is the process of designing and building an executable
computer program to accomplish a specific computing result or to perform a specific task.
Machine Level Language:Machine language, or machine code, is a low-level language comprised
of binary digits (ones and zeros).
Self-Assessment
1. Which of the following language instructions execute very fast?
A. Machine language Instructions
B. Hardwired Instructions
C. Procedural language Instructions
D. Assembly language Instructions
2. Program written in ____________ language is difficult to understand.
A. Procedural language
B. Machine Language
C. Assembly Language
D. High Level Language.
3. Which of the following is part of computer system.
A. Hardware
B. Programming
C. Software
D. Hardware & Software
4. _____________ is a computer language.
A. Binary Language
B. Low Level Language
C. High Level Language
D. All of the above
5. Compiling is a process.
A. To convert source code to machine independent code.
B. To make program.
C. To complete coding.
D. All of the above.
6. Who developed C language?
A. Dennis M. Ritchie
B. Steve Jobs
C. Steve Smith
D. James Gosling
7.What will this program print?
#include<stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
A. Hello, World!
B. Hello, Programming
C. Error Message
A. .c
B. .x
C. .z
D. None of the above
9. Which of the following language is used to write Unix kernel?
A. C#
B. Java
C. C
D. SQL
10. Which of the following statement is true about comments?
A. complex
B. near
C. typed ef
D. const
12. We can use keywords as Identifier.
A. True
B. False
13. Which of the following statement is true about identifier?
6. A 7. A 8. A 9. C 10. B
Further Readings
Ashok N. Kamthane, "Programming with ANCI & Turbo C", Pearson Education,
Year of Publication, 2008.
B.W. Kernighan and D.M. Ritchie, "The Programming Language", Prentice Hall of
India, New Delhi.
Byron Gottfried, "Programming with C", Tata McGraw Hill Publishing Company
Limited, New Delhi.
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
Web Links
https://www.tutorialspoint.com/index.htm
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
• Understand constant and variables
• Explain data type in C
• Describe C program structure
• Describe how to declare variables in C
Introduction
Data items (variables and constants) can be manipulated arithmetically in a C programme using
operators. An operator is a symbol that instructs the machine to perform mathematical or logical
operations on data held in variables. Operands are the variables that are being worked on.
2.1 Constants in C
A constant is a non-changing token with a fixed value. It can be stored in a place in the computer's
memory and accessed using that memory address. In C, constants are divided into four categories:
integer constants, floating-point constants, character constants, and string constants. Constants can
be present in composite forms.
Integer and floating-point constants represent numbers. They are often referred to collectively as
numeric-type constants.
C imposes the following rules while creating a numeric constant type data item:
This declaration defines a constant named pi whose value remains 22/7 throughout the program in
which it is defined.
C language facilitates five different types of constants.
1. Character
2. Integer
3. Real
4. String
5. Logical
Character Constants
A character constant consists of a single character, single digit, or a single special symbol enclosed
with in a pair of single inverted commas. The maximum length of a character constant is one
character.
Example: ‘a’ is a character constant
Example: ‘d’ is a character constant
Example: ‘P’ is a character constant
Example: ‘7’ is a character constant
Example: ‘*’ is a character constant
Integer Constants
An integer constant refers to a sequence of digits and has a numeric value. There are three types of
integers in C language: decimal, octal and hexadecimal.
Another notation (called scientific notation) for real constants consists of three parts:
Example:
+ . 72 12 (no decimal)
24.4 e - 5
String Constants
A string constant is a sequence of one or more characters enclosed within a pair of double quotes
(““). If a single character is enclosed within a pair of double quotes, it will also be interpreted as a
string constant and not a character constant.
Example:
1. “ Hello World”
2. ”A”
Actually, a string is an array of characters terminated by a NULL character. Thus, “a” is a string
consisting of two characters, viz. ‘a’ and NULL(‘\0’).
Logical Constants
The value of a logical constant may be true or false. In C, a non-zero value is considered true, while
0 is considered false.
C has a rich set of data types that is capable of catering to all the programming requirements of an
application. The C-data types may be classified into two categories: Primary and Composite data
types as shown in figure.
C has two distinct categories of data types – primary, and composite. Primary data types are the
ones that are in-built with C language while composite data types allow the programmers to create
their own data types.
There are five primary data types in C language.
1. char: stores a single character belonging to the defined character set of C language.
Example: char a;
Example: int b;
3. float: stores real numbers with single precision (precision of six digits after decimal points)
Example: float c;
4. double: stores real numbers with double precision, i.e., twice the storage space required
by float.
Example: double d;
The following table shows the meaning and storage spaces required by various primary data types.
A single precision
– 3.4*1038 to +
float floating point 4 bytes %f
3.4*1038
number
A double precision
– 1.7 × 10308 to
double floating point 8 bytes %lf
+1.7*10308
number
1. Array: Sequence of objects, all of which are of same types and have same name.
Reserves a sequence of five locations of 2 bytes, each, for storing integers num[0], num[1],
num[2], num[3] and num[4].
In the first line, an enumeration named “colors” which may have any one of the four colors defined
in the curly braces. In the second line, variables of the enumerated data type “colors” are declared.
Notes: Data types always used on the basis of their length value suggest the range of
float data type.
2.3 Variables
A variable is an object whose value can change while a programme is running. A variable is a
symbolic representation of the address in memory space where values can be stored, accessed, and
updated. Each variable has a memory location or address assigned to it, and the value of that
variable is stored there.
Each variable has its own name, data type, size, and value. All variables must have a type so that
the compiler can record all necessary information about them, generate the appropriate code
during translation, and allocate the necessary memory space.
Every programming language has its own set of rules that must be observed while writing the
names of variables. If the rules are not followed, the compiler reports compilation error. Rules for
Constructing Variable Name in C language are listed below:
1. Variable name may be a combination of alphabets, digits or underscores. Sometimes, an
additional constraint on the number of characters in the name is imposed by compilers in which
case its length should not exceed 8 characters.
2. First character must be an alphabet or an underscore (_).
3. No commas or blank spaces are allowed in a variable name.
4. Among the special symbols, only underscore can be used in a variable name. E.g.: emp_age,
item_4, etc.
5. No word, having a reserved meaning in C can be used for variable name
Declaration of Variables
C language is strongly typed language, meaning that all the variables must be declared before their
use. Declaration does two things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold
In C language, a variable declaration has the form:
<Type-specifier> <comma-separated-list-of-variables>;
Here <type-specifier> is one of the valid data types (e.g. int, float, char, etc.). List-of-variables is a
comma-separated list of identifiers representing the program variables.
Once variable has been declared in the above manner, the compiler creates a space in the memory
and attaches the given name to this space. This variable can now be used in the program.
A value is stored in a variable using assignment operation. Assignment is of the form:
<Variable-name> = <value>;
Obviously, before assignment, the variable must be declared.
Example:
int a , b;
a = 100;
b = 20;
C also allows assignment of a value to a variable at the time of declaration. It takes the following
form:
<Type-specifier> <variable_name> = <value>;
e.g. : int I = 5;
Notes: This declaration not only creates an interior type variable I, but also stores a value 5
at the same time.
The process of assigning initial values to the variable is known as initialization. More than one
variable can be initialized in one statement using multiple assignment operators.
Example:
1. int i = 10, j = 15;
2. int j , m ;
j = m =2 ;
int i, j = 2, k;
The assignments will be made as follows:
i=0
j=2
k = 1063 (a garbage value, unintialized)
int a, b = 6, c;
/* declaration & multiple assignment */
int p, q, r, s;
p = q = r = s = 5;
}
values stored in various variables are:
var = 5
a = 0, b = 6
c = garbage value
p = 5, q = 5, r = 5, s = 5
Example:
Write a program to find sum of two numbers.
Solution : - #include<stdio.h>
int main(){
int num1,num2,sum;
num1=100;
num2=300;
sum=num1+num2;
printf("Sum of %d and %d is = %d",num1,num2,sum);
return 0;
}
Output:-
Summary
• A constant is a value that doesn't change throughout the execution of a program.
• A variable is an identifier which is used to store a value.
• There are four commonly used data types such as int, float, char and a void.
• Each data type differs in size and range from one another.
• C is a programming language. It has letters, words, sentences and a well-defined
grammar. Character set of a language is set of all the symbols used to write a program in
that language.
• Words formed in language C are termed as identifiers. C identifiers can be of two types -
keywords or reserved words, and user-defined identifiers. Every language contains
certain words that have specific predefined meaning associated with them. Such words
are known as Keywords.
• A token is a group of characters separated from other group of characters by one or more
white space. A constant is a token with fixed value that does not change.
• A variable is an entity whose value can change during program execution. A variable can
be thought of as a symbolic representation of address of the memory space where values
can be stored, accessed and changed.
• C language is a case-sensitive language which differentiates between lower case and
upper case. C language is strongly typed language, meaning that all the variables must be
declared before their use. C has two distinct categories of data types – primary, and
composite. Primary data types are the ones that are in-built with C language while
composite data types allow the programmers to create their own data types.
Keywords
Constant: A named data item whose value does not change throughout the execution of the
Program
Variable: A named location in the memory that can store a value of specified type.
Data type: A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
Character constant: A "character constant" is formed by enclosing a single character from the
representable character set within single quotation marks (' ').
White space: The characters that separate one identifier from the other like space, tab, carriage
return, new line etc.
Self Assessment
1. Which of the following is true for variable names in C?
A. Variable can be of any length
B. They can contain alphanumeric characters as well as special characters
C. Reserved Word can be used as variable name
D. Variable names cannot start with a digit
A. Real
B. Integer
C. Main
D. Character
7. Constant is ____________.
A. A value that is same as keyword
B. A value that doesn't change throughout the execution of a program.
C. A value that change throughout the execution of a program.
D. All of the above
A. start()
B. system()
C. main()
D. printf()
C. $
D. %
1. D 2. B 3. C 4. D 5. B
6. B 7. B 8. B 9. C 10. C
Further Readings
Ashok N. Kamthane, "Programming with ANCI & Turbo C", Pearson Education,
Year of Publication, 2008.
B.W. Kernighan and D.M. Ritchie, "The Programming Language", Prentice Hall of
India, New Delhi.
Byron Gottfried, "Programming with C", Tata McGraw Hill Publishing Company
Limited, New Delhi.
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
Yashvant Kanetkar, Let us C
Web Links
https://www.tutorialspoint.com/index.htm
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
If a user is unable to communicate with a computer programme, it is unlikely that the programme
would be useful. The software must read input values from the user console and generate the
expected useful output to the user in most programming assignments.
C is unique in that, unlike other high-level languages, it does not have any built-in I/O statements
in its syntax. We'll look at how C handles different I/O operations in this unit. We'll also hear about
the standard library functions in C, as well as the header files that go with them.. This unit is not
intended to be a complete treatment of these topics, but it provides enough information so that you
can start writing real programs.
Example: In order to print the sum of two numbers say a and b, in a new line along with
some identifying text, the printf() will take the following form:
printf(“\n the sum of %d and %d is %d.”, a, b, c);
If the value of a and b is 5 and 6 respectively, then the output would be as follows:
The sum of 5 and 6 is 11.
Undoubtedly, a little more complicated then printing a simple message. Before getting the detail of
the various section of this printf(), Let’s discuss the general format of a printf(), shown below:
printf(“Format string”, arg1, arg2,...., argn);
Where format string refers to a string in enclosed in double quotes that contain formatting
information and arg1, arg2, ...., argn are arguments (may be constants, variable, or other complex
expressions) whose values are formatted and printed according to the specification of the format
string.
The format string in a printf() contains the format specifies that defines how the output is
formatted. Following are the three possible components of a format string:
1. Literal text that is simply printed as entered in the format string.
2. An escape sequence that begins with a \ (backslash) sign, provides special formatting
control.
3. A conversion specifier that begins with a % sign and followed by a single character, that
tellsprintf() how to interpret the arguments being used. To understand the various sections
of previously used printf() statement,
The output of given statement if the value of a and b is 5 and 6 respectively, would be as:
The sum of 5 and 6 is 11
Let’s see how this output is evaluated:
The printf() function reads the format string from left to right and sends the characters that follow
to the standard output unit. It takes action as soon as it encounters the (backslash) (that is, the
signal of the existence of an escape sequence). When it comes across the percent (conversion
specifier) symbol, it grabs the corresponding argument and prints its value in the format defined.
When the closing pair of double quotes is encountered, the process comes to an end.
In our case, the first character after the opening pair of double quote is \ , followed by a character n,
so the effect of \n will take place i.e., output of the coming characters will start from the starting of
the next line. Output up to this stage appears as:
The sum of
Then comes the character % followed by character d (that is, the indication to treat the
corresponding variable as assigned decimal integer), so it picks up the variable a and will print
its value on the screen. At this stage the output will be looking like as:
The sum of 5
In the same manner, this process will go on until there comes an end point of format string. The
final output would be appears as:
The sum of 5 and 6 is 11
The following program will help you to understand the concept more closely as it uses the printf()
statement to print the result of the calculations.
Write a program to print the sum of two numbers.
Program:
#include<stdio.h>
void main()
{
int a, b, c;
a = 5;
b = 6;
c = a + b;
printf(“\n sum = %d”, C); /* will print the desired */
/* result on the monitor */
Format Specifiers
%d -- displays a decimal (base 10) integer
%i -- used with other specifiers to indicate a "long"
%e -- displays a floating point value in exponential notation
%f -- displays a floating point value
%c -- displays a single character
%s -- displays a string of characters
Program shows the usage by some of the frequently used escape sequences
#include<stdio.h>
void main()
{
printf(“\n 1..\t2..\t3....\n”);
printf(“The question is, \” said Humpty Dumpty,\”which is to be masterthat\’s all.\””);
}
Output:
1.. 2.. 3....
“The questions is, “said Humpty Dumpty,” which is to be master-that’s all”.
3.5 scanf()
As previously stated, in order to write an interactive application, certain statements in the
programme must be able to collect data from the user. We provided a few functions in this sense,
In layman's terms, the preceding statement is an instruction to the compiler to obtain an integer
value from the keyboard and store it in a variable called a. Where an is an integer variable that was
previously declared. Following this argument, the value stored in the variable can be used
anywhere for any reason. Let's take a closer look at the different components of this sentence.
Conversion Specifier in scanf()
As mentioned earlier, a conversion specifier instruct the scanf() to convert the input stream of
binary data coming from the keyboard in to the data type specified by the conversion character.
For instance, integer in case of %d as it utilizes the same conversion specifiers as the printf() except
one i.e., [...]. More than one conversion specifier can be used in a single scanf() to read more than
one value.
In such a case, corresponding variables each preceded by & must include in the same statement.
As white spaces are required is input stream, they just can be used to identify the end of each input
value.
For real time experience, consider the following program which demonstrate the usage of scanf() to
read integer values from the keyboard. This program will accept two numbers from the user and
will print their sum on the monitor
If execution is not provided with the proper input, result may be unexpected
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character");
c = getchar();
gets() function
The gets() function allows the user to type a string of characters and then press the enter key. A
character list is used to store all of the characters entered by the user. To render the array a string,
the null character is inserted. The user will enter space-separated strings using the gets() method. It
returns the string that the user typed in. The gets() function is problematic to use because it doesn't
search for array bounds and keeps reading characters until the new line (enter) is encountered.
Declaration
char[] gets(char[]);
puts() function
The puts() function looks a lot like the printf() function. The puts() function is used to print the
string that was previously read using the gets() or scanf() functions on the console. The integer
value returned by the puts() function represents the number of characters printed on the console.
Since it prints an extra newline character with the string, which transfers the cursor to a new line on
the console, the integer value returned by puts() will always be the number of characters in the
string plus 1.
Declaration
int puts(char[])
#include<stdio.h>
#include <string.h>
int main(){
char name[30];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}
• Formatted input and output functions contain format specifier in their syntax.
• Unformatted input and output functions do not contain format specifier in their syntax.
• printf() and scanf() are examples for formatted input and output functions.
• getchar(), gets(), puts(), putchar() etc. are examples of unformatted input output functions.
Program
#include<stdio.h>
void main()
{
charstr [11]; /* declar a character array str of size 11 */
printf(“\n enter a string (Maximum 10 characters):”);
gets(str); /* will read a string from the keyboard*/
printf(“\n the entered string \n:”);
puts(str); /* will print the under of str on the monitor and */
print(“ /* and advances the cursor to the .......*/ thank you”);
}
Output:
Enter a string (maximum 10 characters): GoodDay
The entered string is: GoodDay
Thank you
Summary
• I/O operations deal with the transfer of data to peripheral devices such as monitor, key
board, printer or secondary storage etc.
• A library is nothing more than one or more files that contain a group of predefined
functions. In its most general form the word ‘console’ refers to the standard input and
output devices.
• Unformatted console I/O functions doesn’t allow input and output to be formatted as per
the user requirements. getchar() function is used for reading a character from the
keyboard.
• The putchar() is complementary function of getchar(). It is used to display a character on
the monitor.
• The another possible use of getch() is to temporarily halt the execution of a program
intentionally. gets() function is used to accept a string from the keyboard whereas puts()
function is used to print a string on the monitor.
• Formatted I/O Functions allows input and output operations to be performed in a fixed
format.
• The printf() in one of the most important and useful functions to display data on monitor.
• Except for double quotes, escape sequences and conversions specifiers, all characters
within a pair of double quotes will be treated as literal text (string context) and will be
display as it is a on the monitor.
• Any character that is prefix with a backslash is supposed to be treated as an escape
sequence.
• Conversion’s specifiers always begin with the percent sign (%) and immediately followed
by one or more conversions characters
•
Keywords
printf() scanf()
5. main ( ) is a
A. Keyword
B. Function
C. Integer
D. Pointer
1. B 2. B 3. C 4. D 5. B
6. D 7. C 8. D 9. B 10. B
Review Questions
1. Define stdin, stdout, and stderr.
2. Differentiate the followings:
(a) printf() and puts()
(b) getche() and getch()
(c) scanf() and gets()
3. How format string is associated with printf()? Discuss the various possible components of a
format string in detail.
4. What happens if one uses variables in scanf() without using the address of operator (&)?
Discuss.
5. An amount of rupees, say R, is deposited in a bank for Y years, which pays simple interest at the
rate of ‘rt’ annually. Write a C program that prints the amount after Y years
6. Write down two functions xgets( ) and xputs( ) which work similar to the standard library
functions gets( ) and puts( ).
7. What is the differences between getchar( ), fgetchar( ), getch( ) and getche( )? With the help of
suitable example.
8. Write down two functions xgets( ) and xputs( ) which work similar to the standard library
functions gets( ) and puts( ).
9. Write down a function getint( ), which would receive a numeric string from the keyboard,
convert it to an integer number and return the integer to the calling function. A sample usage of
getint( ) is shown below:
main( )
{
int a ;
a = getint( ) ;
printf ( “you entered %d”, a )
}
10. What is the differences between getchar( ), fgetchar( ), getch( ) and getche( )?
Further Readings
Ashok N. Kamthane, "Programming with ANCI & Turbo C", Pearson Education,
Year of Publication, 2008.
B.W. Kernighan and D.M. Ritchie, "The Programming Language", Prentice Hall of
India, New Delhi.
Byron Gottfried, "Programming with C", Tata McGraw Hill Publishing Company
Limited, New Delhi.
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
Web Links
https://www.tutorialspoint.com/index.htm
www.webopedia.com
www.web-source.net
CONTENTS
Objectives
Introduction
4.1 Operators
4.2 Unary operator
4.3 Binary operator
4.4 Arithmetic Operators
4.5 Relational Operators
4.6 Logical Operators
4.7 Assignment Operators
4.8 Increment and Decrement Operators
4.9 Conditional Operators
4.10 Bitwise Operators
4.11 Special Operators
4.12 Operator Precedence and Associativity
Summary
Keywords
Self-Assessment
Answer for Self Assessment
Review Questions
Further Readings
Objectives
After studying this unit, you will be able to:
Introduction
The term "data types" refers to a comprehensive framework for defining variables and functions of
various types. The type of a variable decides how much storage space it takes up and how the
stored bit pattern is interpreted. An operator is a symbol that instructs the machine to perform
mathematical or logical operations on data held in variables. A value's data form identifies a set of
properties that it shares.
An expression is a set of constants, variables, and operators that follow the grammatical rules of the
language C and evaluate to a valid value. Activity refers to the impact that operators have on their
operands.
4.1 Operators
An operator is a symbol that instructs the machine to perform mathematical or logical operations
on data held in variables. Data items (variables and constants) can be manipulated arithmetically in
a C program using operators.
C operators can be classified into a number of categories.
• Unary operator
• Binary operator
• Arithmetic operators
• Relational operators
• Logical operators
• Conditional operators
• Assignment operators
• Bitwise operators
• Increment and decrement operators
• Special operators
• Relational operators: less than (<), less than or equal to (<=), greater than (>), and greater
than or equal to (>=)
The division operator (/) requires the second operand to be non-zero, though the operands need
not be integers. When an integer is divided by another integer, the result is also an integer. In
such instances the division is termed as integer division. Consider the following:
int x;
x = 10;
What do you expect the value of x/4 to be? If you guessed 2.5, you are wrong.
The result is of course 2.5 however, since it is integer division (division operation in which both
the operands are integers), the result 2.5 will be truncated to 2 to make the result an integer. In
case you wish to get the correct value you make this division a float type as x/4.0.
The % operator is known as modulus operator. It produces the remainder after the division of
two operands. The second operand must be non-zero.
Rest all the other operators work in their normal arithmetic way. Normal BODMAS rules are also
applicable to these arithmetic operators.
The relational operator compares two operands to see if they are equivalent, unequal, or if one is
greater or inferior to the other.
The consequence is always a numeric value equal to true or false, regardless of whether the
operands are variables, constants, or expressions. As previously stated, a non-zero result indicates
fact, while a zero result indicates false. Six relational operators are available in the C programming
language.
== equal to
!= not equal to
A simple relation contains only one relational expression and takes the following form: <ae-
1><relational operator><ae-2> <ae-1> and <ae-2> are arithmetic expressions, which may be
constants, variables or combination of these. The value of the relational operator is either 1 or 0. If
the relation is true, result is 1 otherwise it is0.
Example:
Expressions Result
Using logical operators, several relational expressions may be combined to create a single
compound relational expression. To combine two or more relational statements, logical operators
are used. Three logical operators are available in C. A compound relation behaves in the same way
as a single relation generating a real or false value
1. (age > 50 && weight < 80) will evaluate to true if age is more than 50 and also weight is
less than
80. Otherwise, it will evaluate to false.
2. (a < 0 ¦ ch = = ‘a’) will evaluate to true if a is less than 0 while ch is equal to ‘a’, false
otherwise.
3. (!(a < 0)) will evaluate to true if a is greater than or equal to 0, false otherwise.
Assignment operators are used to store the result of an expression to a variable. The most
commonly used assignment operator is (=). Be careful not to mistake assignment operator (=) for
mathematical equality operator which is indicated by the same symbol.
An expression with assignment operator is of the following form:
<identifier> = <expression>;
When this statement is executed, <expression> is evaluated and the value is stored in the
<identifier>.
Let us consider the following usage of assignment operator in C language.
int i;
i = 5;
i = i + 10;
The value now stored in the variable “i” will be 15. In this program, the current value stored in
variable i is 5. Thus, while executing i = i+10, the right-hand side will be evaluated to give a value
15. This value will then be assigned to the left-hand side. As a result, the current value of I after
execution of this statement will become 15.
C language provides a short cut to write arithmetic assignment expressions which takes the
following form:
<Variable> op = <expression>;
C has two very useful operators ++ and -- called increment and decrement operators respectively.
These are generally not found in other languages. These operators are unary operators as they
require only one operand. The operands must be a variable name and not a constant.
The increment operator (++) adds one to the current value of the operand and stores the result back
into the operand, while the decrement operator (--) subtracts one from the operand and stores the
decremented value back into the operand.
There are two different forms of increment and decrement operators. When they are used before
the operand, it is termed as prefix, while when used after the operand, they are termed as postfix
operators.
| (Bit-wise OR): Binary operator takes two operands of int type and performs bit-wise OR
operation. With assumption that int size is 8-bits:
int a = 5; [binary : 0000 0101]
int b = 9; [binary : 0000 1001]
a | b yields [binary : 0000 1101]
& (Bit-wise AND): Binary operator takes two operands of int type and performs bit-wise AND
operation. With same assumption on int size as above:
int a = 5; [binary : 0000 0101]
int b = 9; [binary : 0000 1001]
a & b yields [binary : 0000 0001]
^ (Bit-wise Logical XOR): XOR gives 1 if only one of the operand is 1 else 0. With same assumption
on int size as above:
int a = 5; [binary : 0000 0101]
int b = 9; [binary : 0000 1001]
a ^ b yields [binary : 0000 1100]
<< (Shift left): This operator shifts the bits towards left padding the space with 0 by given integer
times.
int a = 5; [binary : 0000 0101]
a << 3 yields [binary : 0010 1000]
>> (Shift right): This operator shifts the bits towards right padding the space with 0.
int a = 5; [binary : 0000 0101]
a >> 3 yields [binary : 0000 0000]
~ (one’s complement operator): It is a unary operator that causes the bits of its operand to be
inverted so that 1 becomes 0 and vice-versa. The operator must always precede the operand and
must be integer type of all sizes. Assuming that int type is of 1 byte size:
inr a = 5; [binary: 0000 0101]
~a; [binary: 1111 1010]
Comma Operator
This operator is used to link the related expressions together.
Example: int x, y, z;
Size of Operator
The size of operator works on variables, constants and even on data types. It returns the
number
of bytes the operand occupies in the memory.
Consider the following C code for illustration.
sizeof(int); //Gives number of bytes occupied by an
//integer type variable
sizeof(float); //Gives number of bytes occupied by a
//float type variable
The output of this code will be 2, 4. Don’t get disheartened if you get different result. This
is only because the machine on which this program was run allotted 2 bytes for int type
and 4 bytes for float type. The result that you get depends on the number of bytes
allocated to these types on your machine. Nevertheless, in all cases size of operator returns
the number of bytes occupied by its operand on that particular machine.
Summary
Precedence defines the sequence in which operators are to be applied on the operands, while
evaluating the expressions involving more than one operator.
Keywords
Expression: A combination of identifiers and operators according to some rule that yields a value
Operator Proceeding: The precedents of an operator determine the order in which expression
will be evaluated
Operator: A symbol that works on one or more values to yield another value
The Size of Operator: The size of operator which is used to measure the date sizes. It a unary
compile type operator that is to return the length of the variable or parenthesized type specifiers.
Self-Assessment
A. Unary operators are operators that act upon a single operand to produce a new value.
B. Unary operator acts like constant
C. Unary operator is used for logic operations
D. Above all
E.
2. Choose the correct statements for operator
A. Int
B. Char
C. double
D. Above all
4. In C programming language, which of the following type of operators have the highest
precedence
A. Relational operators
B. Equality operators
C. Logical operators
D. Arithmetic operators
5. Which is not unary operator
A. ++
B. --
C. &
D. +
6. Relational operator is used with
A. 1 operand.
B. 2 operands
C. Both 1 operand and 2 operand
D. none of above
7. Which among the following is NOT a logical operator
A. &&
B. ||
C. !
D. @
8. Find out the wrong statement
A. a>b
B. b>=c
C. a<=> c
D. a++
9. Which among the following is NOT a relational operator
A. >=
B. !=
C. ==
D. ||
10. Find out the wrong statement
A. if (a>b)
B. if(x=10 && y=20)
A. +=
B. *=
C. &
D. >>=
12. ( &= ) operator is used for…..
A. <<=
B. %=
C. /=
D. None of these
14. In c which operators having highest priority
A. Logical operator
B. Relational operator
C. Arithmetic operator
D. Conditional operator
15. Conditional operator in c is also called
A. Relational operator
B. Logical operator
C. Ternary operator
D. None of these
6. C 7. D 8. C 9. D 10. C
Review Questions
1. What are the different classes of operators available in C language?
2. Define the term “Expression”. Explain the various types of expression in C.
3. What are the various logical and relational operators supported by C. Explain them with
proper examples.
4. Draw a table that will provide a complete list of operators, their precedence level and
their rules of association.
Further Readings
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
Yashvant Kanetkar, Let us C
Web Links
https://www.tutorialspoint.com/index.htm
www.webopedia.com
www.web-source.net
Prikshat Kumar Angra, Lovely Professional University Unit 05: Decision making statements
Objectives
• After studying this unit, you will be able to:
• Explain decision making in C
• Explain branching
• Describe if, if-else statement in C
• Explain switch statement
• Understand Type Conversion and Type Modifiers
Introduction
To write a realistic program doesn’t mean that collection of the statements arranged in a particular
sequence. It requires more than that. Just take an analogy of our real life. Life doesn’t go straight all
the way as:
1. There are some situations when you have to take decisions like whether to purchase this book or
not.
2. There are also some situations where you have to perform the particular action again and again
like for better understanding read this unit 5 times continuously.
In the same manner, hardly we write a computer program that may not encounter these situations.
Most of the programs require a statement or set of statements to be executed multiple times or not
to execute at all, depending on the circumstances.
Programming in C
• Documentation
• Link
• Definition
• Global Declarations
• Main functions
• Subprograms
Documentation Section
The documentation section is the part of the program where the programmer gives the details
associated with the program. He usually gives the name of the program, the details of the author
and other details like the time of coding and description. It gives anyone reading the code the
overview of the code.
Example:
**
* Author: Name
* date: DD/MM/YYYY
* no input needed
*/
Link Section
This part of the code is used to declare all the header files that will be used in the program. This
leads to the compiler being told to link the header files to the system libraries.
Example: #include<stdio.h>
Definition Section
In this section, we define different constants. The keyword define is used in this part.
Programming in C
Lab Exercise:
#include<stdio.h>
int main(){
int a=10;
double b=9.34,sum;
sum=a+b;
printf("%lf",sum);
return 0;
}
Example:
double a = 4.5,b=3.5;
//explicitly defined by user
int sum=(int)a+(int)b;
Lab Exercise:
#include<stdio.h>
int main(){
double a = 10.5,b=5.5;
//explicitly defined by user
int sum=(int)a+(int)b;
printf("%d",sum);
return 0;
}
Long
This can be used to increased size of the current data.it is applied on int or double data type.
Programming in C
Lab Exercise:
#include<stdio.h>
int main(){
long double a ;
printf("%d",sizeof(a));
return 0;
}
Short
In general int data type occupies different memory spaces for a different operating system; to
allocate fixed memory space short keyword can be used.
Lab Exercise:
#include<stdio.h>
int main(){
short int a ;
printf("%d",sizeof(a));
return 0;
}
Unsigned
This keyword can be used to make the accepting values of a data type is positive data type.
Lab Exercise:
#include<stdio.h>
int main(){
unsigned int a=-10 ;
printf("%u", a);
return 0;
}
Signed
This keyword accepts both positive and negative value.
Lab Exercise:
#include<stdio.h>
int main(){
signed int a=-10 ;
printf("%d", a);
return 0;
}
Sequence
In the sequence construct, as the name implies, statements are executed sequentially i.e. one after
the other. In this, neither the statement are repeated nor in the order of execution changed as shown
in Figure.
Programming in C
You probably noticed in the previous unit that a C programme is executed top down, that is,
execution begins with the beginning of the main() function and continues, statement by statement,
until the end of the main (). In a C programme, the following programme illustrates the sequential
execution of statements.
Lab Exercise:
#include<stdio.h>
main(){
printf("\n First statement");
printf("\n Second statement");
printf("\n Third statement");
printf("\n Second last statement");
printf("\n Last statement");
}
Output : -
Notes: Other complex statement may be used in a sequence to demonstrate the concept.
Selection
Depending on the input and the situation involved, only appropriate statements are often executed
instead of all of them. The execution of statements in the selection construct is based on a condition
test. If the test returns true, you instruct the programme to take one course of action; otherwise, you
instruct the programme to take a different course of action. Two or more sets of statements are
written in the selection construct, but only one of these sets is executed, as shown in the Figure.
The selection construct can be implemented by means of the if construct. The if construct makes
use of relational and logical operators for decision making, as shown in the pseudo code given
below:
Lab Exercise:
#include<stdio.h>
main(){
int marks=50;
if(marks>40)
printf("Pass");
else
printf("Fail");
}
Output: -
Iteration
The iteration constructs are an efficient method of handling a series of statements that must be
repeated a variable number of times. Sometimes the required number of repetitions is known in
advance and sometimes the statements repeats over and over until certain specified conditions on
met, as shown in the Figure.
Programming in C
The iteration construct is also called as loop. The statements that are to be executed is called
as body of the loop and the condition on which a loop terminates is called as exit condition as
demonstrated by the program given below:
Lab Exercise:
#include<stdio.h>
main(){
int i=0;
while(i<=20){
printf("\n %d ",i);
i++;
}
}
Output: -
As mentioned earlier, purely sequenced statements are rarely included in a real program. Every
programming language must provide statement to support other constructs. C also provides
statements to supports these constructs. Let’s discuss these constructs in detail.
if (expression)
statement;
Where a statement may consist of a single statement, a compound statement or nothing as an
empty statement. The expression also referred so as test condition must be enclosed in parentheses,
which causes the expression to be evaluated first. If it evaluate to true (i.e., a non-zero value), then
the statement associated with it will be executed otherwise ignored and the control will pass to the
next statement.
Example:
Consider the following statement:
:
if (marks > 9)
printf (“\n Pass”);
:
:
The above code fragment will printf “Pass” on the monitor if the value of marks is greater than 9.If
the value of marks is not grater than 9, the control simple ignore this statement and will pass to the
next statement. The follow program shows the use of simple if as it accepts the marks of a student
and printfs his/her result.
Lab Exercise:
#include<stdio.h>
void main
{
int marks;
printf( “\n enter your marks”);
Programming in C
scanf(“%d”, marks);
if (marks>9) /* if construct with test condition */
printf (“ \n Pass”); /* statement associated with if */
printf(“ Thank you”); //next statement
}
output: run 1-> run 2->
Enter your marks : 77 ↵ Enter your marks : 9 ↵
Pass Thank you
Thank you
Notes: “Pass” has been displayed only if the expression evaluated to true otherwise if it
evaluated to false, the control ignores the associated statement and executed the next statement
i.e., “Thank you”.
As mentioned earlier, an if statement can control the execution of multiple statements, called as
compound statement or a block. Where a block is a group of two or more statements enclosed in
braces. So if these multiple statements are to be executed than they must be placed with in a pair of
braces, as illustrated by the following program.
Lab Exercise:
Program:
# include<stdio.h>
void main()
{
int marks;
printf (“\n Enter your marks: “);
scanf (“ %d “, &marks) ;
if (marks > 39)
{
printf(“\n Pass”);
printf (“ \n Congratulation …”);
}
if (marks <40)
{
printf (“\n Fail”);
printf (“\n sorry. Good luck next time …”);
}
printf (“\n Thank you”);
}
Output: run 1-> run 2->
Notes: Default an if construct when evaluates to true executes only the first statement
associated with it. If multiple statements are not enclosed with in parentheses, results may be
unexpected.
Task: Write a program if candidate got more than 50% in year exam screen show “Pass”
otherwise “Fail”.
Programming in C
The code segment will display “Pass” on the monitor if the value of marks is greater than or equals
to 40. If the marks are less than 40 (obviously the else case), then the statement in the else section
will be executed and will printf “Fail” on the monitor. Let’s write the Program by using an if-else
construct.
Lab exercise:
#include<stdio.h>
void main ()
{
int marks;
printf (“\n Enter your marks:”);
scanf (“% d”, & marks”);
if (marks >=40)
{
printf (“\n Pass”);
printf (“\n congratulations….”);
}
Else
{
Notes: else section required their own pair of braces as more than one statement is to be
executed when the expression evaluates to false.
In the above segment of code, the inner if executes only if the expression1 evaluates to true. The
other possible combination of nested if may take one of the following form:
· if (expression1)
{
if (expression2)
statement1;
}
· if (expression1)
{
if (expression 2)
statement1;
else
statement 2;
}
· if(expression1)
{
statement1;
}
else
{
if(exp2)
statement 2;
}
· if (exp 1)
{
statement1;
}
else
{
if (exp2)
statement 2;
else
statement3;
}
if(exp 1)
{
if (exp 2)
statement1;
else
statement 2;
Programming in C
}
else
{
if (exp3)
statement3;
else
statement4;
}
if (exp1)
{
if (exp2)
statement1;
}
else
{
if (exp3)
statement 2;
}
Let’s write a couple of programs to explore the various combination of nested if. The following
program not only print the request after accepting marks from the students but also print his/her
grade.
Lab Exercise:
Program
#include<stdio.h>
void main ()
{
int marks;
printf (“\n Enter your marks:”);
scanf (“% d”,&marks”);
if (marks >=40)
{
printf (“\n Pass”);
if (marks > = 80)
printf (“ with distinction”);
}
else
printf (“\n Fail”);
}
Output: run 1 ->
Enter your marks : 77↵
Pass
Run 2->
Enter your marks : 88↵
Pass with distinction
Run 3->
Enter your marks : 38↵
Fail
Notes: The execution of the inner if only be there if first expression evaluates to true and
the message “with distinction” will printf only if both the expressions evaluates to true.
Lab Exercise:
Program:
# include<stdio.h>
void main ()
{
int marks;
char grade;
printf (“\n Enter your marks:”);
scanf (“% d”, & marks”);
if (marks > = 90)
grade = ‘0’;
else
Programming in C
Notes: This whole section of code is actually one statement that is comprised of six
hierarchically nested is else constructs, so there is no need to put them in the braces. At any time
during the general top to bottom execution of these expressions, if an expression evaluates to
true, then the associated statement will be executed and control flow will pass to the statement
immediately following the entire nested chain.
Lab Exercise:
Program:
#include<stdio.h>
void main ()
{
int num;
printf (“\n Enter any number between 1 to 5 : “);
scanf (“ % d”, &num ) ;
switch (num)
{
case 1 : printf(“\n One”);
case 2 : printf (“\n Two”);
case 3 : printf (“\n Three”);
case 4 : printf (“\n Four”);
case 5 : printf (“\n Five”);
default : printf (“\n Wrong input”);
}
printf (“\n Thank You”);
}
Output: run 1 → run 2 →
Enter any number between 1 to 5: 2↵ Enter any number between
1 to 5: 4↵
Two Four
Programming in C
Three Five
Four Wrong input
Five Thank you
Wrong input
Thank you
Run 3->
Enter any number between 1 to 5 = 9↵
Wrong input
Thank you
Notes: There is no need to put braces with the individual case labels as they each contains
single statement, although a pair is required to group the entire case section.
Summary
• Most of the programs require a statement or set of statements to be executed multiple times
or not to execute at all, depending on the circumstances.
• The statement by which we can control the flow of the program execution is called as control
flow statement or program control statement.
• In the sequence construct, as the name implies, statements are executed sequentially i.e. one
after the other.
• In selection construct, the execution of statements depends upon a condition test.
• The iteration constructs are an efficient method of handling a series of statements that must
be repeated a variable number of times.
• If multiple statements are to be executed than they must be placed with in a pair of braces.
• A simple if or if else construct may be placed with in another if or if-else construct.
• The switch statement is another convenient tool provided by C to handle the situations in
which multiple decisions to be made based on an expression that can have multiple values.
Keywords
Conditional statement: A statement that evaluates to either true or false.
Continue statement: The statement that ignores execution of further statements and forces the loop
to evaluate the loop condition once again.
Default statement: An optional statement in a switch that is executed if none of the conditions
evaluates to true.
Switch statement: A multi-selection statement that branches to that statement whose specified
condition evaluates to true.
Self Assessment
1. Every C program must have
A. Data type
B. Constant
C. Main Function
D. None of the above
A. A sub program
B. A data type
C. A part of C program where we can declare global variables.
D. All of the above
A. 4
B. 2
C. 3
D. 1
A. 2
B. 2.2
C. 5
D. 7
Programming in C
A. Int, main
B. Sub program
C. Short, long, signed and unsigned
D. All of above
A. hi
B. how are u
C. compile time error
D. error
#include <stdio.h>
void main()
{
char val=1;
if(val--==0)
printf("TRUE");
else
printf("FALSE");
}
A. FALSE
B. Error
C. TRUE
D. None
A. if (if (a == 1)){}
B. if (func1 (a)){}
C. if (a){}
D. if ((char) a){}
A. Hello
B. World
C. Hello World
D. Error
Programming in C
void main()
{
short day=2;
switch(day)
{
case 2: || case 22:
printf("%d nd",day);
break;
default:
printf("%d th",day);
break;
}
}
A. 2 nd
B. 22 nd
C. Error
D. 2 nd 22 nd
A. x=1
B. x=2
C. x=3
D. All of above
6. D 7. B 8. C 9. B 10. B
16. B
Review Questions
1. Write a program using if-else statement.
2. Explain nested-if statement with example.
3. What do you mean by switch statement? How it used
4. A five-digit number is entered through the keyboard. Write a program to obtain the reversed
number and to determine whether the original and reversed numbers are equal or not.
5. Write a program to check whether a triangle is valid or not, when the three angles of the triangle
are entered through the keyboard. A triangle is valid if the sum of all the three angles is equal to
180 degrees.
6. Given the length and breadth of a rectangle, write a program to find whether the area of the
rectangle is greater than its perimeter. For example, the area of the rectangle with length = 5 and
breadth = 4 is greater than its perimeter.
7. What is the use of if-else statement?
8. Define selection in c programming.
9. Write a program in C to enter five integer values as age of five boys and calculate the average age
of all the boys.
10. Write a program to calculate the area of a square. All values enter with the help of keyboard.
Further Readings
Ashok N. Kamthane, "Programming with ANCI & Turbo C", Pearson Education,
Year of Publication, 2008.
B.W. Kernighan and D.M. Ritchie, "The Programming Language", Prentice Hall of
India, New Delhi.
Byron Gottfried, "Programming with C", Tata McGraw Hill Publishing Company
Limited, New Delhi.
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
Yashvant Kanetkar, Let us C
Web Links
https://www.tutorialspoint.com/index.htm
Programming in C
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
The C language includes a variety of program control statements that let you control the order of
program execution. This unit discusses various iteration-based program control statements and
how these can be implemented in a program. This unit also discusses some jump statements of C
which are break and continue.
6.1 Looping
Iteration statements are also known as loops or looping statements because the program execution
typically loops through the statement more than once. In this category, C provide the following
statement, or you call loops.
1. for loop
2. while loop
3. do-while loop
Looping must not continue indefinitely as an analogy to real life you would not like to crack the
same joke again and again, so a mechanism is required to break out the loop and to allow the
executives of the next set of statements.
When the above statement is encountered during program execution, the following events occur:
1. Initial expression is evaluated first and i will be assigned an initial value 1 i.e. i =1.
2. Then the condition expression is evaluated i.e. i< =10 and the result will be true as 1 < = 10 is
true.
3. Since the condition expression is true, the statement in the loop body is executed i.e. printf(“\n
Hello World!”); which prints the message Hello World! on the screen.
4. After the execution of the loop body, the update expression i.e. ++i is executed which increment
the value of i by 1. In this way after the first execution of the loop the value of I becomes 2 as
initially it was 1.
5. After the execution of the update expression the condition expression is again evaluated. If it
evaluates to true the sequence is repeated from step no. 3, otherwise the loop terminates.
After a certain repetition the condition expression evaluates to false, as the value of I will
be greater than 10, then loop will be terminated and the output of the code
may appear as:
Hello World!
Hello World!
::
Hello World! (10 Times)
Also note that the loop body never executes if condition expression is evaluated to false in its first
execution. Figure shows the operation of a for loop.
Program :-
#include<stdio.h>
inti,range;
printf("Enter Range");
scanf("%d",&range);
for(i=0;i<=range;i++)
{
// printf("%d\n",i);
printf("%d\t",i);
}
return 0;
}
Output : -
Program :
#include<stdio.h>
int main(){
inti,n;
printf("Enter Number");
scanf("%d",&n);
for(i=1;i<=10;i++)
{
printf("%d*%d=%d\n",i,n,i*n);
}
return 0;
}
Output : -
The while loop doesn’t explicitly contain the initialization expression and update expressions of the
loop. These two expressions are normally provided by the programmers as the initialization
expression(s) should be placed before the loop begins and updating expression(s) should be inside
the loop body. By using all these expressions, the general farm of while loop may looks like as:
:
initialization expression(s);
while (conditional expression)
{:
: Loop Body
updation expression;
}
And the statements between the {and } forms the body of the loop. But the braces can be discarded,
if there is only one statement in the loop body
When the program execution readers a while statement, the following events occur:
1. First of all the conditional expression is evaluated i.e., i< 10.
2. The conditional expression is evaluated to true as i was 1 initially and 1 < 10 is true. But if it
evaluates to false, the loop will be terminated, and the control moves to the first statement
following loop body.
3. Since the condition expression is true, the loop body will be executed i.e., the print statement and
the updating expression.
4. With the closing braces ( } ), it is assumed that the loop is finished and the control moves back to
the while statement, which repeats the test again and proceeds accordingly.
Program : -
#include<stdio.h>
int main(){
int number;
printf("Enter Number");
scanf("%d",&number);
while(number<=50)
{
Program : -
#include<stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter a number: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number: %d",reverse);
return 0;
}
Output : -
The braces { } can be discarded when the loop-boody contains a single statement. The do-whileloop
iterates the loop body as long as the specified condition is true while testing the condition at the
end of the loop each time, rather than at the beginning, as is done by the for and the whileloop.
Like while loop, do-while loop also doesn’t contain the initialization and Updation expression as
part of loop statement. However, these expressions can be associated with do-while loop by the
programmer according to required logic. Then the new form of do-while loop may looks like as:
Initialization expression(s);
do
{
Loop body;
Updating expression;
}while ( conditional expression(s) );
When the program control reaches at a ‘do while’ loop, the following events occur:
1. The loop body will be executed i.e. the print statement and the updation statement.
2. The conditional expression will be evaluated i.e. i<=10.
3. The conditional expression will evaluates to true as the value as i is 2 this time (initially=1).
4. Since the condition expression is true, the control will move back to execute the loop-bodyonce
again.
After a certain repetition the condition expression will evaluates to false as the
value as I will be greater than 10, the loop will be terminated.
The do-while loop is well suited for the problems where number of repetitions is not known
inadvance. But this is sure that the loop will be executed at least once. The following segment
ofcodes will give a clear picture of the concept:
Program :-
#include<stdio.h>
int main(){
int number;
printf("Enter a number:");
scanf("%d",&number);
do{
}while(number<=20);
return 0;
}
Output:-
Let’s write another interesting program using do-while loop. This program will printf thealphabet
A to Z along with their ASCII codes.
Program : -
#include<stdio.h>
void main()
{inta,b;
char choice ;
do
{
printf(“\n Main Menu “);
printf(“\n -----------------------------------------------”);
printf(“\n1. ADDITION “);
printf(“\n2. SUBTRACTION “);
printf(“ \n3. QUIT “);
printf(“\n Enter your choice:”);
scanf(“%c”,&choice);
if( choice ==’1’ || choice == ‘2’)
{
printf(“\n Enter the first & second number :”);
scanf(“%d %d, &a,&b);
}
switch (choice)
{
case ‘1’ : printf(“\n Result = % d”, a + b) ;
break;
1. ADDITION
2. SUBTRACTION
3. QUIT
enter your choice : 3↵
Thank you
To come out from the program execution if the choice entered is other than the given one,
the menu is simply redisplayed until user entered the connect one. For the desired
operation, program required the input accordingly
What if you need to exit from a loop statement even before the test condition becomes false?You
can use the break statement. The break statement is used to terminate loops or to exit froma switch
(discussed later). When break is encountered inside any C loop, the loop is immediatelyexited
without testing the loop condition and control automatically passes to the first statementafter the
loop. It can be used within a while, a do-while, a for or a switch statement. The breakstatement is
written simply as
Following C code snippets illustrate use of break statement to exit from various C loops. In each
situation, the loop will continue to execute as long as the current value for the integer variable x
does not exceed 10. However, the computation will break out of the loop if a negative value for x is
detected.
While loop
do-while loop
do
{
scanf (“%d”, &x);
if (x < 0)
{
printf (“Negative value entered”);
break;
}
} while (x < = 10);
for loop
for (i = 1; x < = 10; ++i)
{
scanf (“%f”, &x);
if (x < 0)
{
printf (“Negative value entered!!”);
Consider the following code snippet in which a while loop is nested within a for loop.
for (i = 0; i< = n; ++i)
{
while (( c = getchar( ))! = ‘\n’)
{
if (c = ‘*’) break;
}
}
The internal while loop terminates if the character variable c is assigned an asterisk (*). However,
the for loop will continue to execute. Thus, if the value of i is less than n when the break occurs, the
program will increment i and make another pass through the for loop.
Write a program to print all prime numbers from 1 to 300. (Use nested loops,
break and continue)
goto label;
…..
…..
label: statements;
........
statement;
The label: can by anywhere in the program either before or after the goto label; statement.
There is no built-in mechanism for the flow of execution to come back from where it
branched.
inti;
for(i=0;i<=10;i++)
{
if(i==5)
{
goto STATUS;
}
printf("%d\n",i);
}
STATUS:
printf("Value of i is = 5 than goto working");
return 0;
}
Output :-
Summary
• The for loop in C is the simplest, fixed and entry-controlled loop. An infinite for loop can
be created by skipping the conditional expression.
• A conditional expression cannot have multiple expression like initialization and Updating
expression, but it may contain several conditions linked together using logical operators.
• The second type of loop, the while loop is an entry-controlled loop as it tests the
conditions first and if the condition is true, then only the control will enter into the loop
body. An empty loop can also be configured using while statement and could used as a
time delay loop.
Keywords
Control Statements: The statements that allow programmers to alter the sequential flow of
execution of the program and control the flow are called control statements.
For Loop: A for loop allows execution of a statement (or a block of statements) repeatedly a
number of times.
While Loop: In case the number of times a statement is to be executed is not known in advance,
while loop is used.
goto statement: The goto statement is known as jump statement in C.
Self-Assessment
#include <stdio.h>
void main()
{
int k = 0;
for (k)
Printf ("Hello");
}
A. Compile time error
B. Hello
C. Nothing
D. Varies
5. What is the output of this program?
void main()
{
int x=0;
for(;;)
{
if(x==3)
break;
printf("%d ",++x);
}
}
A. 123
A. for
B. while
C. do while
D. None of the above
7. do-while loop terminates when conditional expression returns?
A. One
B. Zero
C. Non - zero
D. None of the above
8. Which of the following statement about for loop is true?
A. Index value is retained outside the loop
B. Index value can be changed from within the loop
C. Goto can be used to jump, out of the loop
D. All of these
9. Which one is correct syntax for do-while loop?
A. do
{
//Statements
}while(condition test);
B. do,
{
//Statements
}while(condition test);
C. do,
{
//Statements
}while(do);
D. do
{
}while(do);
10. How many times Programming will be printed?
#include <stdio.h>
int main()
{
inti = -5;
while (i<= 5)
{
if (i>= 0)
break;
else
{
i += 1;
continue;
}
printf("Programming");
}
return 0;
}
A. 5 times
B. 10 times
C. 0 times
D. Infinite times
6. C 7. B 8. D 9. A 10. C
Review Questions
1. What do you mean by looping?
2. Describe for loop with the help of suitable example.
3. Differentiate while loop and do-while loop.
4. What is the advantage of break statement in while loop?
5. Write a program to find the factorial value of any number entered through the keyboard.
6. Write a program to print all the ASCII values and their equivalent characters using a whileloop.
The ASCII values vary from 0 to 255.
7. Write a program to find the range of a set of numbers. Range is the difference between the
smallest and biggest number in the list.
8. Write a program to calculate overtime pay of 10 employees. Overtime is paid at the rate of` 12.00
per hour for every hour worked above 40 hours. Assume that employees do not work for fractional
part of an hour.
9. Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each
digit of the number is equal to the number itself, then the number is called an Armstrong number.
For example, 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 )
10. Write a program to enter the numbers till the user wants and at the end it should display the
count of positive, negative and zeros entered.
11. Write a program to find the range of a set of numbers. Range is the difference between the
smallest and biggest number in the list.
Further Readings
Ashok N. Kamthane, "Programming with ANCI & Turbo C", Pearson Education,
Year of Publication, 2008.
B.W. Kernighan and D.M. Ritchie, "The Programming Language", Prentice Hall of
India, New Delhi.
Byron Gottfried, "Programming with C", Tata McGraw Hill Publishing Company
Limited, New Delhi.
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
Web Links
https://www.tutorialspoint.com/index.htm
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
A function is a programming unit with a unique name that may be identified. It can be invoked by
a programme once it has been defined. When called, it may accept zero or more inputs. The code
placed inside the function specification determines what should be done with the incoming
input(s). The function generates a single output after doing the given transformation. The caller of
the function receives this output.
Define the functions factorial( ), prime( ) and Fibonacci( ) in a file , say ‘myfuncs.c.’. Do
not define main( ) in this file.
Example: Let us write a simple function that calculates the square of an integer.
/*Program to calculate the square of a given integer*/
/* square( ) function */
{
int square (int no) /*passing of argument */
int result ; /* local variable to function square */
result = no*no;
return (result); /* returns an integer value */
}
/*It will be called from main()as follows */
main( )
{
int n ,sq; /* local variable to function main */
printf (“Enter a number to calculate square value”);
scanf(“%d”,&n);
sq=square(n); /* function call with parameter passing */
printf (”\nSquare of the number is : %d”, sq);
} /* program ends */
Output:
Enter a number to calculate square value: 5
Square of the number is: 25
Important Points
1. You can pass any number of arguments to a function but can return only one value at a
time.
Call by Value
Call by value means sending the values of the arguments to functions. When a single value
ispassed to a function via an actual argument, the value of the actual argument is copied into
thefunction. Therefore, the value of the corresponding formal argument can be altered within
thefunction, but the value of the actual argument within the calling routine will not change. This
procedure for passing the value of an argument to a function is known as passing by value or call
by value.
Call by Reference
Call by reference means sending the addresses of the arguments to the called function. In this
method the addresses of actual arguments in the calling function are copied into formal arguments
of the called functions. Thus using these addresses we would have an access to the actual
arguments and hence we would be able to manipulate them. Using a call by reference intelligently,
it is possible to make a function return more than one value at a time, which involves the study of
pointer.
Summary
• In this unit, we learnt about “Functions”: definition, declaration, prototypes, types,
function calls datatypes and storage classes, types function invoking and lastly Recursion.
• All these subtopics must have given you a clear idea of how to create and call functions
from other functions, how to send values through arguments, and how to return values to
the called function.
• We have seen that the functions, which do not return any value, must be declared as
“void”, return type.
• A function can return only one value at a time, although it can have many return
statements.
• A function can return any of the data type specified in ‘C’.
Keywords
Call by Reference: It means sending the addresses of the arguments to the called function.
Data types: It refers to the type of information while storage class refers to the life-time of a
variable and its scope within the program.
Function Call: A function can be called by specifying its name followed by a list of arguments
enclosed in parentheses and separated by commas.
Return Statement: Information is returned from the function to the calling portion of the program
via return statement.
Self Assessment
1. Which one is not a library function
A. printf ( )
B. scanf ( )
C. gets ( )
D. abc ( )
A. local
B. global
C. intermediate
D. both a and b
A. Global variable
B. Local variable
C. Both a and b
D. None of these
A. Global variable
B. Local variable
C. Intermediate variable
D. None of above
A. formal Parameter
B. actual Parameter
C. intermediate
D. both a and b
A. pointers
B. array
C. functions
D. loops
A. Call by value
B. Call by reference
C. None of above
D. above all
A. Static function
B. Auto function
C. Recursive function
D. above all
A. 2
B. 3
C. 1
D. 4
A. local
B. global
C. intermediate
D. both local and global
A. pointers
B. array
C. functions
D. loops
6. C 7. A 8. A 9. C 10. B
Review Questions
1. Takes two integer inputs and produces the remainder when the larger is divided by the
smaller.
2. Swaps the two given integers.
3. What do you mean by function call.
4. Describe return value and their types.
5. Evaluates the following series for a specified n: 12 + 22 + 32 + 42 + ……..n2
6. A positive integer is entered through the keyboard. Write a function to obtain the prime
factors of this number.
7. Write a function which receives a float and an int from main( ), finds the product of
these two and returns the product which is printed through main( ).
8. Write a function that receives marks received by a student in 3 subjects and returns the
average and percentage of these marks. Call this function from main( ) and print the
results in main( ).
9. Given three variables x, y, z write a function to circularly shift their values to right. In
other words if x = 5, y = 8, z = 10 after circular shift y = 5, z = 8, x =10 after circular shift y =
5, z = 8 and x = 10. Call the function with variables a, b, c to circularly shift values.
10. Write a function to compute the distance between two points and use it to develop
another function that will compute the area of the triangle whose vertices are A(x1, y1),
B(x2, y2), and C(x3, y3). Use these functions to develop a function which returns a value 1
if the point (x, y) lines inside the triangle ABC, otherwise a value 0.
11. Write a function to find the binary equivalent of a given decimal integer and display it.
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
Web Links
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
www.programiz.com
Objectives
After studying this unit, you will be able to:
storage classes
Scope of a variable
Auto, Static, Extern and Register
Introduction
Storage Classes are used to characterize a variable's or function's characteristics. These
characteristics include scope, visibility, and life-time, which allow us to track the presence of a
variable through the course of a program's execution. The following items are described by a
storage class in C:
The variable scope.
The location where the variable will be stored.
The initialized value of a variable.
A lifetime of a variable.
Who can access a variable?
main( )
{
int m = 1000;
function 2( );
printf (“%d \n”, m);
}
function 1( )
{
int m = 10;
printf (“%d \n”, m);
}
function 2( )
{
int m = 100;
function 1( );
printf (“%d \n”, m);
}
output: 10
100
1000
Notes
function ( )
{
int count = 0;
-------
-------
count ++;
When the function references the variable count, it will be referencing only its local variable, not the
global one. The value of count in main( ) will not be affected.
}
fun2( )
{
int x = 1;
return x;
}
fun3( )
{
x = x+10;
return (x);
}
Output: x = 10
x = 20
x=1
x = 30
main()
{
externint y; /* external declaration */
--------
}
fun1()
{
externint y; /* external declaration */
--------
}
int y; /*definition */
The external declaration of y inside the functions informs the compiler that y is an integer type
defined somewhere else in the program.
A static variable is initialized only once, when the program is compiled. It is never initialized again.
A static variable may be either an internal type or an external type, depending on the place of
declaration. Internal static variables are those which are declared inside a function. The scope of
internal static variables extends upto the end of the function in which they are defined. Therefore,
internal static variables are similar to auto variables, except that they remain in existence (alive)
throughout the remaining program. Therefore, internal static variables can be used to retain values
between function calls.
An external static variable is declared outside of all functions and is available to all the functions in
that program. The difference between a static external variable and a simple external variable is that
the static external variable is available only within the file where it is defined while the simple
external variable can be accessed by other files also.
When a function is written before main it can be called in the body of main. If it is written
after main then in the declaration of main you have to write the prototype of the function. The
prototype can also be written as a global declaration.
Program:
Case 1:
#include <stdio.h>
main ( )
{
inti;
Explanation
In Case 1, the function is written after main, so you have to write the prototype definition in main
as given in statement D.
In Case 2, the function is written above the function main, so during the compilation of main the
reference of function f1 is resolved. So it is not necessary to write the prototype definition in main.
In Case 3, the prototype is written as a global declaration. So, during the compilation of main, all
the function information is known.
Questions
1. Write a function which receives a float and an int from main ( ), finds the product of these two
and returns the product which is printed through main ( ).
2. Write a function that receives 5 integers and returns the sum, average and standard deviation
of these numbers. Call this function from main ( ) and print the results in main ( ).
3. Write a function that receives marks received by a student in 3 subjects and returns the average
and percentage of these marks. Call this function from main ( ) and print
voidautoStorageClass()
{
printf("--------------------------------");
}
voidregisterStorageClass()
{
printf("--------------------------------");
}
printf("--------------------------------");
}
printf("--------------------------------");
}
int main()
{
// exiting
printf("\n\n Storage Classes demonstrated");
return 0;
}
Summary
Auto, extern, register, static are the four different storage classes in a C program.
In this unit, we learnt about “storage classes”. A keyword auto is used to define an auto
storage class.
Extern storage class is used when we have global functions or variables which are shared
between two or more files
The static variables are used within function/ file as local static variables. They can also be
used as a global variable
Register is used to store the variable in CPU registers rather memory location for quick
access.
Storage class represents the scope and lifespan of a variable.
Keywords
Auto Register
Extern Static
Self Assessment
1. What is the initial value of register storage class specifier?
A. 0
B. Null
C. Garbage
D. Infinite
A. Within block
B. Within Program
C. Global Multiple files
D. None of the above
A. Within block
B. Within Program
C. Global Multiple files
D. None of the above
A. Auto
B. Struct
C. Typedef
D. Static
int main()
{
staticint a = 3;
printf(“%d”, a --);
return 0;
}
A. 0
B. 1
C. 2
D. 3
A. Garbage value
B. 0 0
C. 1 0
D. 1 1
7. In case of a conflict between the names of a local and global variable what happens?
8. Where will the space be allocated for an automatic storage class variable?
A. In CPU register
B. In memory as well as in CPU register
C. In memory
D. On disk.
return 50;
}
A. -1
B. 50
C. 0
D. Compiler error
A. Declaration
B. Definition
C. Initialization
D. None of the above
A. Internal
B. External
C. External and Internal are not valid terms for functions
D. Both Internal and External
13. Global variables are __________
A. External
B. Internal
C. Both internal and external
D. None of above
A. Register
B. Auto
C. Extern
D. Static
A. Register
B. Auto
C. Extern
D. Static
6. C 7. B 8. C 9. B 10. A
Review Questions
1. Write a program to demonstrate static storage classes
2. What is significance of storageclasses.
3. Write a program to demonstrate auto storage classes
4. Write a program to demonstrate extern storage classes
5. Write a program to demonstrate register storage classes
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
Web Links
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Explain arrays
Describe two dimensional array
Describe array initialization
Introduction
An array is a group of data items of same data type that share a common name. Ordinary variables
are capable of holding only one value at a time. If we want to store more than one value at a time in
a single variable, we use arrays.
An array is a collective name given to a group of similar quantities. Each member in the group is
referred to by its position in the group.
Arrays are allotted the memory in a strictly contiguous fashion. The simplest array is one
dimensional array which is simply a list of variables of same data type. An array of one
dimensional arrays is called a two dimension array.
9.1 Arrays
Arrays are allocated the memory in a strictly contiguous fashion. The simplest array is one
dimensional array which is a list of variables of same data type. An array of one dimensional arrays
is called a two dimensional array; array of two dimensional arrays is three dimensional array and
so on.
As C performs no bounds checking, care should be taken to ensure that the array indices are within
the declared limits. Also, indexing in C begins from 0 and not from 1.
This is a table of four rows and three columns. Such a table of items can be defined using two
dimensional arrays.
General form of declaring a 2-D array is
data_type array_name [row_size] [colum_size];
Example: int marks [4] [2];
It will declare an integer array marks of four rows and two columns. An element of this array can
be accessed by the manipulation of both the indices. printf (“%d”, marks [2] [1]) will print the
element present in third row and second column.
C allows arrays of three or more dimensions. Multi-dimensional arrays are defined in much the
same manner as one-dimensional arrays, except that a separate pair of square brackets is required
for each subscript.
The general form of a multi-dimensional array is
data_type array_name [s1] [s2] [s3] . . . [sm];
E.g.: int survey [3] [5] [12];
float table [5] [4] [5] [3];
Here, survey is a 3-dimensional array declared to contain 180 integer type elements. Similarly, table
is a 4-dimensional array containing 300 elements of floating point type.
Let us consider some applications of multidimensional array programming.
Character Arrays
Just as a group of integers can be stored in an integer array, group of characters can be stored in a
character array or “strings”. The string constant is a one dimensional array of characters terminated
by null character („\0‟). This null character „\0‟ (ASCII value0) is different from „O‟
(ASCII value 48).
The terminating null character is important because it is the only way the function that works with
string can know where the string ends.
Example: Static char name [ ] = {„K‟, „R‟, „I‟, „S‟, „H‟, „\0‟};
This example shows the declaration and initialization of a character array. The array elements of a
character array are stored in contiguous locations with each element occupying one byte of
memory.
1. Contrary to the numeric array where a 5 digit number can be stored in one array cell, in
the character arrays only a single character can be stored in one cell. So in order to store an
array of strings, a 2-dimensional array is required.
2. As scanf( ) function is not capable of receiving multi word string, such strings should be
entered using gets( ).
int i, a - 2, b - 3 ;
int arr.[ 2 +3] ;
Two-dimensional Arrays
Two dimensional arrays may be initialized by a list of initial values enclosed in braces following
their declaration.
E.g.: static int table[2][3] = {0, 0, 0, 1, 1, 1};
initializes the elements of the first row to 0 and the second row to one. The initialization is done by
row.
The aforesaid statement can be equivalently written as
static int table[2][3] = {{0, 0, 0}, {1, 1, 1}};
by surrounding the elements of each row by braces.
We can also initialize a two dimensional array in the form of a matrix as shown below:
static int table[2][3] = {{0, 0, 0},
{1, 1, 1}};
The syntax of the above statement. Commas are required after each brace that closes off a row,
except in the case of the last row.
If the values are missing in an initializer, they are automatically set to 0. For instance, the statement
static int table [2] [3] = {{1, 1},
{2}};
will initialize the first two elements of the first row to one, the first element of the second row to
two, and all the other elements to 0.
When all the elements are to be initialized to 0, the following short cut method may be used.
static int m [3] [5] = {{0}, {0}, {0}};
The first element of each row is explicitly initialized to 0 while other elements are automatically
initialized to 0.
While initializing an array, it is necessary to mention the second (column) dimension, whereas the
first dimension (row) is optional. Thus, the following declarations are acceptable.
static int arr [2] [3] = {12, 34, 23, 45, 56, 45};
static int arr [ ] [3] = {12, 34, 23, 45, 56, 45 };
Multi-dimensional Array
Example: Example of initializing a 4-dimensional array:
static int arr [3] [4] [2] = {{{2, 4}, {7, 8}, {3, 4}, {5, 6},},
{{7, 6}, {3, 4}, {5, 3}, {2, 3}, },
{{8, 9}, {7, 2}, {3, 4}, {6, 1}, } };
In this example, the outer array has three elements, each of which is a two dimensional array of
four rows, each of which is a one dimensional array of two elements.
Case Study
Each element of the array has a memory address. The following program prints an array limit value
and an array element address.
Program:
#include <stdio.h>
void printarr(int a[]);
main()
{
int a[5];
for(int i = 0;i<5;i++)
{
a[i]=i;
}
printarr(a);
}
void printarr(int a[])
{
: Now, consider the following function, which takes an array as an argument along with
another argument and based on the passed arguments, it returns the average of the numbers
passed through the array as follows −
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum = 0;
#include <stdio.h>
double getAverage(int arr[], int size);
int main () {
int balance[5] = {1000, 2, 3, 17, 50};
double avg;
avg = getAverage( balance, 5 ) ;
printf( "Average value is: %f ", avg );
return 0;
}
Keywords
Array: A user defined simple data structure which represents a group of same type of
variables having same name each being referred to by an integral index
Multidimensional array: An array in which elements are accessed using multiple
indices
One dimensional array: An array in which elements are accessed using a single index
Subscript/Index: The integral index by which an array element is accessed
Two dimensional array: An array in which elements are accessed using two indices
Self Assessment
3. Arrays can
void main()
int i = 0, j = 0;
printf("%d", a[i][j]);
A. 1 2 3 4 5 0
B. 1 2 3 4 5 junk
C. 1 2 3 4 5 5
D. Run time error
10. Choose correct declaration of function with as array parameter, let name of function is sum
and array (arr) is of integer type
A. int sum(int)
B. int sum(int arr[])
C. int sum(arr[])
D. int sum(arr)
6. A 7. C 8. D 9. D 10. B
Review Questions
1. Explain the usefulness of Arrays in C.
2. What do you mean by „Array‟? How it can be declared & initialized in a C program?
3. Draw a diagram to represent the internal storage of an Array.
4. Describe the different types of Array. Give suitable programs.
5. Find the smallest number in an array using pointers.
6. If an array arr contains n elements, then write a program to check if arr[0] = arr[n-1],
arr[1]
= arr[n-2] and so on.
7. Write a program to copy the contents of one array into another in the reverse order.
8. How will you initialize a three-dimensional array threed[3][2][3]? How will you refer
the
first and last element in this array?
9. Write a program to pick up the largest number from any 5 row by 5 column matrix.
10. Write a program to obtain transpose of a 4 x 4 matrix. The transpose of a matrix is
obtained
by exchanging the elements of each row with the elements of the corresponding column.
11. Write a program that interchanges the odd and even components of an array.
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company
Limited, New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett,
1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
Yashvant Kanetkar, Let us C
Web Links
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Introduction
Computers use their memory for storing instructions of the programs as well as the values of the
variables. Since memory is a sequential collection of storage cells each cell has an address
associated with it. Whenever we declare a variable, the system allocates, somewhere in the
memory, a memory location and a unique address is assigned to this location. Whenever a value is
assigned to this variable the value gets stored in the location having a unique address in the
memory associated with that variable. Therefore, the values stored in memory can be manipulated
using their addresses. Pointer is an extremely powerful mechanism to write efficient programs.
Incidentally, this feature makes C stand out as the most powerful programming language. Pointers
are the topic of this unit.
10.1 Pointers
A memory variable is merely a symbolic reference given to a memory location. Now let us consider
that an expression in a C program is as follows:
int a = 10, b = 5, c;
c = a + b;
The above expression implies that a, b and c are the variables which can hold the integer data. Now
from the above mentioned statement let us assume that the variable „a‟ occupies the address 3000 in
the memory, „b‟ occupies 3020 and the variable „c‟ occupies 3040 in the memory. Then the compiler
will generate the machine instruction to transfer the data from the location 3000 and 3020 into the
CPU, add them and transfer the result to the location 3040 referenced as c. Hence
we can conclude that every variable holds two values:
Address of the variable in the memory (l-value)
Value stored at that memory location referenced by the variable. (r-value)
Pointer is nothing but a simple data type in C programming language, which has a
specialcharacteristic to hold the address of some other memory location as its r-value. C
programminglanguage provides „&‟ operator to extract the address of any object. These addresses
can be storedin the pointer variable and can be manipulated.
The syntax for declaring a pointer variable is,
<data type> *<identifier>;
Example
int n;
int *ptr; /* pointer to an integer*/
The following statement assigns the address location of the variable n to ptr, and ptr is a pointer to
n.
ptr=&n;
Since a pointer variable points to a location, the content of that location is obtained by prefixing the
pointer variable by the unary operator * (also called the indirection or dereferencing operator) like,
*<pointer_variable>.
: # include<stdio.h>
main()
{
int a=10, *ptr;
ptr=&a; /* ptr points to the location of a */
printf(“The value of a pointed by the pointer ptr is: %d”, *ptr);
/* printing the value of a pointed by ptr through the pointer ptr*/
}
A null value can be assigned to a pointer when it does not point to any data or in the other words,
as a good programming habit every pointer should be initialized with the null value. A pointer
with a null value assigned to it is nothing but a pointer which contains the address zero.
The precedence of the unary operators „&‟ and „*‟ are same in C language. Here as a special case we
can mention that „&‟ operator cannot be used or applied to any arithmetic expression, it can only be
used with an operand which has unique address.
Pointer is a variable which can hold the address of a memory location. The value stored in a pointer
type variable is interpreted as an address. Consider the following declarative statement:
intnum = 197;
This statement instructs the compiler to reserve a 2-byte memory location (assuming that the target
machine stores an int type in two bytes) and to put the value 84 in that location. Assume that a
system allocates memory location 1001 for num. diagrammatically it can be shown as:
As the memory addresses are numbers, they can be assigned to some other variable. Let ptr be the
variable which holds the address of variable num. We can access the value of num by the variable
ptr. Thus, we can say “ptr points to num”. Diagrammatically, it can be shown as:
1. The asterisk (*) tells that the variable pt_name is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data type.
: The statement
int *p;
declares the variable p as a pointer variable that points to an integer data type (int). The type int
refers to the data type of the variable being pointed to by p and not the type of the value of the
pointer.
Given below are some more examples of pointer declaration
Create a pointer variable roll number capable of pointing to an integer type vari
Int *roll number;
able or capable of holding the address of an integer type variable
int *p;
p = &x;
Then the following expression
*p
Represents the value 109.
Example:
main( )
{
inti = 3;
printf (“\n Address of i: = %u”, &i); /* returns the address * /
printf (“\t value i = %d”, * (&i)); /* returns the value of address of i */
}
int q, * i, n;
q = 35;
i = & q;
n = * i;
i is a pointer to an integer containing the address of q. In the fourth statement we have assignedthe
value at address contained in i to another variable n. Thus, indirectly we have accessed thevariable
q through n. using pointer variable i.
Decrement:
It is a condition that also comes under subtraction. When a pointer is decremented, it actually
decrements by the number equal to the size of the data type for which it is a pointer.
For Example:
If an integer pointer that stores address 1000 is decremented, then it will decrement by 2(size of an
int) and the new address it will points to 998. While if a float type pointer is decremented then it
will decrement by 4(size of a float) and the new address will be 996.
Example:
Program to illustrate pointer increment/decrement
#include <stdio.h>
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Pointer stores
// the address of N
ptr1 = &N;
ptr2 = &N;
return 0;
}
Pointer Comparisons
Pointers may be compared by using relational operators, such as ==, <, and >. If p1 and p2 point to
variables that are related to each other, such as elements of the same array, then p1 and p2 can be
meaningfully compared.
The following program modifies the previous example − one by incrementing the variable pointer
so long as the address to which it points is either less than or equal to the address of the last
element of the array, which is &var[MAX - 1]
Expressions such as x, (x+1) and &x[i] cannot appear on the left side of an assignment statement
because it is not possible to assign an arbitrary address to an array name or an array element.
int main () {
return 0;
}
Lab Exercise
// Program to demonstrate working of Pointers
#include<stdio.h>
int main(){
int n=123;
int *ptr=&n;
int **nn=n;
//*ptr=&n;
printf("Original value of variable n is = %d\n",n);
printf("Address of n is = %p\n",ptr);
printf("Address of n in decimal number is = %d\n",ptr);
printf("Value of %d",nn);
return 0;
}
Lab Exercise
// Program to access value using Pointers
#include<stdio.h>
int main(){
int x;
printf("Enter Value of x\n");
scanf("%d",&x);
int *p;
p=&x;
printf("value of x entered by user is %d\n",x);
printf("Address of variable x is %p\n",p);
printf("Getting value from pointer variable %d\n",*p);
printf("Address of variable x is %d\n",p);
printf("Address of variable x is %u\n",p);
*p=500;
printf("New value of x is %d\n",x);
return 0;
Lab Exercise
#include<stdio.h>
int main(){
inta,b,sum,sub,mul,div;
int *ptr1,*ptr2;
printf("Enter first number");
scanf("%d",&a);
printf("Enter second number");
scanf("%d",&b);
ptr1=&a;
ptr2=&b;
sum=*ptr1+*ptr2;
sub=*ptr1-*ptr2;
mul=*ptr1* *ptr2;
div= *ptr1/ *ptr2;
printf("Using pointers, all arithmetic operations
performed\n");
printf("Sum of first and second number is =%d\n",sum);
printf("Subtraction of first and second number is %d\n",sub);
printf("Product of first and second number is %d\n",mul);
printf("Division of first and second number is %d\n",div);
printf("Address of first and second number a=%p, b=%p
",ptr1,ptr2);
return 0;
}
#include<stdio.h>
int main(){
int *ptr;
ptr=NULL;
printf("Value of null pointer is %d",ptr);
return 0;
}
Summary
Pointers are often passed to a function as arguments by reference. This allows data items
within the calling function to be accessed, altered by the called function, and then returned
to the calling function in the altered form.
There is an intimate relationship between pointers and arrays as an array name is really a
pointer to the first element in the array.
Access to the elements of array using pointers is enabled by adding the respective
subscript to the pointer value (i.e. address of zeroth element) and the expression preceded
with an indirection operator.
As pointer declaration does not allocate memory to store the objects it points at, therefore,
memory is allocated at run time known as dynamic memory allocation.
The library routine malloc can be used for this purpose.
Keywords
Array of Pointer: A multi-dimensional array can be expressed in terms of an array of
pointers rather than as a pointer to a group of contiguous arrays.
Pointer: It is a variable which can hold the address of a memory location rather than the
value at the location.
Pointer Expression: Like other variables, pointer variables can be used in expressions.
Arithmetic and comparison operations can be performed on the pointers
Self Assessment
1. What are the correct statements about pointers?
A. +
B. -
C. *
D. /
A. %c
B. %d
C. %p
D. %s
A. 1
B. 2
C. 0
D. 4
A. int x=90;
B. int *ptr1,*ptr2;
C. ptr1=@x;
D. ptr2=ptr1;
A. Addition
B. Subtraction
C. Multiply
D. Above all
9. What is the output of following program?
#include<stdio.h>
int main(){
int x=90,y=10,result;
int *ptr1,*ptr2;
ptr1=&x;
ptr2=&y;
result=*ptr1**ptr2;
printf("Product of x and y using pointers is %d\n",result);
return 0;
}
A. 100
B. 80
C. 900
D. 10
A. int a=10,*ptr;
B. ptr=/a;
C. ptr--;
D. above all
11. What are the different operations that can be performed on pointers?
A. Decrement
B. Addition
C. Subtraction
D. Above all
A. It should be declared
B. It should be initialized
C. It should be both declared and initialized
D. None of above
A. int ->ptr[3];
B. int *ptr[2];
C. intptr[*5];
D. None of above
A. We can store pointers to an int or char or any other data type available.
B. We can also declare an array of pointers
C. Use a pointer to point to an array, and then we can use that pointer to access the array
elements
D. Above all
6. C 7. C 8. D 9. C 10. C
Review Questions
1. Define „Pointer‟. List down the various advantages of using pointers in a C program.
2. How pointer are initialized and implemented in C? Write a program to explain the concept.
3. Explain with the help of a C program, the concept of Pointer Arithmetic in C.
4. How printer in C incorporates the concept of Arrays? Write a suitable program to demonstrate
the concept.
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
Web Links
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Explain strings
Describe reading and writing strings
Explain string handling functions
Introduction
Computers process a variety of data kinds in addition to numeric data. The data to be processed is
frequently textual, such as words, names, and addresses. String type variables are used to store and
process this type of data. There is no explicit string data type in C.
Character arrays, on the other hand, can be used to simulate the same thing. In this session, we'll
look at strings and how to manipulate them in C.
11.1 Strings
In C, a string is defined as a collection of characters. The NULL character, which signifies the end of
the string, is used to end each string. Any group of characters enclosed in double-quote marks is
referred to as a string constant.
When characters in a string constant are stored, the NULL character is automatically appended to
the end of them. The escape sequence „0' is used to represent the NULL character within a
programme. A string constant is an array with a lower bound of 0 and an upper bound of the
string's length in characters.
When choosing a data representation for a given data object, the cost of performing various
operations with that representation must be considered. Furthermore, a hidden cost resulting from
the required storage management procedures must be considered.
Strings are stored in three types of structures:
1. Fixed length structure
2. Variable length structure
3. Linked structure
9.2 Sequential Fixed Length Structure
In this representation successive characters of a string will be placed in consecutive character
positions. The string S = „x1---xn‟ could then be represented as in Figure with s as a pointer to the
first character.
Now, if we want to pick a substring of size k from the string of size n, the time required to achieve
this would be O(k) plus the time needed to locate a free space big enough to hold the string.
In the above figure memory is divided into nodes of size 4 with a link field that is two characters
long. Deletion of a substring can be carried out by replacing all characters in this substring by 0 and
freeing nodes in which the data fields consist of only 0‟s.
Storage compaction can be carried out when there are no free nodes. String representation with
variable size is similar.
Each node in the purest version of a linked list representation of strings would be one in size.
Normally, this would be considered a huge waste of space. With a two-character link field, this
means that only 1/3 of the available Memory will be used to store string data, while the remaining
2/3 will be used exclusively for link data.
Because C has no built-in facilities for manipulating entire arrays (copying them, comparing them,
etc.), it also has very few built-in facilities for manipulating strings.
In fact, C‟s only truly built-in string-handling is that it allows us to use string constants (also called
string literals) in our code. Whenever we write a string, enclosed in double quotes, C automatically
creates an array of characters for us, containing that string, terminated by the \0 character.
: We can declare and define an array of characters, and initialize it with a stringconstant:
char string[] = “Hello, world!”;
In this situation, we may omit the array's dimension because the compiler will figure it out for us
based on the size of the initializer. The compiler will only size a string array for us in this scenario;
in all other circumstances, we will have to decide how big the arrays and other data structures we
employ to house strings are
To do anything else with strings, we must typically call functions. The C library contains a fewbasic
string manipulation functions, and to learn more about strings, we‟ll be looking at howthese
functions might be implemented.
Since C never lets us assign entire arrays, we use the strcpy function to copy one string toanother:
#include <string.h>
char string1[] = “Hello, world!”;
char string2[20];
strcpy(string2, string1);
The destination string is strcpy‟s first argument, so that a call to strcpy mimics an assignment
expression (with the destination on the left-hand side). Notice that we had to allocate string2 big
enough to hold the string that would be copied to it. Also, at the top of any source file where we‟re
using the standard library‟s string-handling functions (such as strcpy) we must include the line
#include <string.h>
which contains external declarations for these functions.
Since C won‟t let us compare entire arrays, either, we must call a function to do that, too. The
standard library‟s strcmp function compares two strings, and returns 0 if they are identical, or a
negative number if the first string is alphabetically “less than‟‟ the second string, or a positive
number if the first string is ”greater.” (Roughly speaking, what it means for one string to be “less
than‟‟ another is that it would come first in a dictionary or telephone book, although there are a few
anomalies.) Here is an example:
char string3[] = “this is”;
char string4[] = “a test”;
if(strcmp(string3, string4) == 0)
printf(“strings are equal\n”);
elseprintf(“strings are different\n”);
This code fragment will print “strings are different‟‟. Notice that strcmp does not return a
Boolean,
true/false, zero/nonzero answer, so it‟s not a good idea to write something like
if(strcmp(string3, string4))
...
because it will behave backwards from what you might reasonably expect. (Nevertheless, if you
start reading other people‟s code, you‟re likely to come across conditionals like if(strcmp(a, b)) or
even if(!strcmp(a, b)). The first does something if the strings are unequal; the second does
something if they‟re equal. You can read these more easily if you pretend for a moment that
strcmp‟s name were strdiff, instead.)
Another standard library function is strcat, which concatenates strings. It does not concatenate two
strings together and give you a third, new string; what it really does is append one string onto the
end of another. (If it gave you a new string, it would have to allocate memory for it somewhere, and
the standard library string functions generally never do that for you automatically.) Here‟s an
example:
char string5[20] = “Hello, “;
char string6[] = “world!”;
printf(“%s\n”, string5);
strcat(string5, string6);
printf(“%s\n”, string5);
The first call to printf prints ``Hello, „‟, and the second one prints “Hello, world!”, indicating that
the contents of string6 have been tacked on to the end of string5. Notice that we declared string5
with extra space, to make room for the appended characters.
If you have a string and you want to know its length (perhaps so that you can check whether it will
fit in some other array you‟ve allocated for it), you can call strlen, which returns the length of the
string (i.e. the number of characters in it), not including the \0:
char string7[] = “abc”;
intlen = strlen(string7);
printf(“%d\n”, len);
Finally, you can print strings out with printf using the %s format specifier, as we‟ve been doingin
these examples already (e.g. printf(“%s\n”, string5);).
Since a string is just an array of characters, all of the string-handling functions we‟ve just seen can
be written quite simply, using no techniques more complicated than the ones we already know. In
fact, it‟s quite instructive to look at how these functions might be implemented. Here is a version of
strcpy:
mystrcpy(char dest[], char src[])
{
inti = 0;
while(src[i] != „\0‟)
{
dest[i] = src[i];
i++;
}
dest[i] = „\0‟;
}
We‟ve called it mystrcpy instead of strcpy so that it won‟t clash with the version that‟s already in
the standard library. Its operation is simple: it looks at characters in the src string one at a time, and
as long as they‟re not \0, assigns them, one by one, to the corresponding positions in the dest
string. When it‟s done, it terminates the dest string by appending a \0. (After exiting the while loop,
i is guaranteed to have a value one greater than the subscript of the last character in src.) For
comparison, here‟s a way of writing the same code, using a for loop:
for(i = 0; src[i] != „\0‟; i++)
dest[i] = src[i];
dest[i] = „\0‟;
Yet a third possibility is to move the test for the terminating \0 character out of the for loop header
and into the body of the loop, using an explicit if and break statement, so that we can perform the
test after the assignment and therefore use the assignment inside the loop to copy
the \0 to dest, too:
for(i = 0; ; i++)
{
dest[i] = src[i];
if(src[i] == „\0‟)
break;
}
(There are in fact many, many ways to write strcpy. Many programmers like to combine the
assignment and test, using an expression like (dest[i] = src[i]) != „\0‟. Here is a version of
strcmp:
mystrcmp(char str1[], char str2[])
{
inti = 0;
while(1)
{
if(str1[i] != str2[i])
return str1[i] - str2[i];
if(str1[i] == „\0‟ || str2[i] == „\0‟)
return 0;
i++;
}
}
Characters are compared one at a time. If two characters in one position differ, the strings are
different, and we are supposed to return a value less than zero if the first string (str1) is
alphabetically less than the second string. Since characters in C are represented by their numeric
character set values, and since most reasonable character sets assign values to characters in
alphabetical order, we can simply subtract the two differing characters from each other: the
expression str1[i] - str2[i] will yield a negative result if the i‟th character of str1 is less than the
corresponding character in str2. (As it turns out, this will behave a bit strangely when comparing
upper- and lower-case letters, but it‟s the traditional approach, which the standard versions of
strcmp tend to use.) If the characters are the same, we continue around the loop, unless the
characters we just compared were (both) \0, in which case we‟ve reached the end of both strings,
and they were both equal. Notice that we used what may at first appear to be an infinite loop—the
controlling expression is the constant 1, which is always true. What actually happens is that the
loop runs until one of the two return statements breaks out of it (and the entire function).
Finally, here is a version of strlen:
intmystrlen(char str[])
{
inti;
for(i = 0; str[i] != „\0‟; i++)
{}
returni;
}
In this case, all we have to do is find the \0 that terminates the string, and it turns out that the three
control expressions of the for loop do all the work; there‟s nothing left to do in the body.
Therefore, we use an empty pair of braces {} as the loop body. Equivalently, we could use a null
statement, which is simply a semicolon:
for(i = 0; str[i] != „\0‟; i++)
Empty loop bodies can be a bit startling at first, but they‟re not unheard of.Everything we‟ve looked
at so far has come out of C‟s standard libraries. As one last example,let‟s write a substr function, for
extracting a substring out of a larger string. We might call it likethis:
char string8[] = “this is a test”;
char string9[10];
substr(string9, string8, 5, 4);
printf(“%s\n”, string9);
The idea is that we‟ll extract a substring of length 4, starting at character 5 (0-based) of string8,
andcopy the substring to string9. Just as with strcpy, it‟s our responsibility to declare the
destinationstring (string9) big enough. Here is an implementation of substr. Not surprisingly, it‟s
quite similar to strcpy:
substr(char dest[], char src[], int offset, intlen)
{
inti;
for(i = 0; i<len&&src[offset + i] != „\0‟; i++)
dest[i] = src[i + offset];
dest[i] = „\0‟;
}
If you compare this code to the code for mystrcpy, you‟ll see that the only differences are
thatcharacters are fetched from src[offset + i] instead of src[i], and that the loop stops when Len
characters have been copied (or when the src string runs out of characters, whichever comesfirst).
In this unit, we‟ve been careless about declaring the return types of the string functions, and(with
the exception of mystrlen) they haven‟t returned values. The real string functions do returnvalues,
but they‟re of type ``pointer to character,‟‟ which we haven‟t discussed yet.When working with
strings, it‟s important to keep firmly in mind the differences betweencharacters and strings. We
must also occasionally remember the way characters are represented,and about the relation
between character values and integers.
As we have had several occasions to mention, a character is represented internally as a
smallinteger, with a value depending on the character set in use. For example, we might find
that„A‟ had the value 65, that „a‟ had the value 97, and that „+‟ had the value 43. (These are, in
fact,the values in the ASCII character set, which most computers use. However, you don‟t need
tolearn these values, because the vast majority of the time, you use character constants to referto
characters, and the compiler worries about the values for you. Using character constants
inpreference to raw numeric values also makes your programs more portable.)
As we may also have mentioned, there is a big difference between a character and a string, evena
string which contains only one character (other than the \0).
„A‟ is not the same as “A”. To drive home this point, let‟s illustrate it with a fewexamples.
If you have a string:
char string[] = “hello, world!”;
you can modify its first character by saying
string[0] = „H‟;
(Of course, there‟s nothing magic about the first character; you can modify any character in the
string in this way. Be aware, though, that it is not always safe to modify strings in-place like this;
we‟ll say more about the modifiability of strings in a later unit on pointers.) Since you‟re replacing a
character, you want a character constant, „H‟. It would not be right to write
string[0] = “H”; /* WRONG */
because “H” is a string (an array of characters), not a single character. (The destination of the
assignment, string[0], is a char, but the right-hand side is a string; these types don‟t match.) On the
other hand, when you need a string, you must use a string. To print a single newline, you could call
printf(“\n”);
It would not be correct to call
printf(„\n‟); /* WRONG */
printf always wants a string as its first argument. (As one final example, putchar wants a single
character, so putchar(„\n‟) would be correct, and putchar(“\n”) would be incorrect.) We must also
remember the difference between strings and integers. If we treat the character „1‟ as an integer,
perhaps by saying
inti = „1‟;
we will probably not get the value 1 in i; we‟ll get the value of the character „1‟ in the machine‟s
character set. (In ASCII, it‟s 49.) When we do need to find the numeric value of a digit character (or
to go the other way, to get the digit character with a particular value) we can make use of the fact
that, in any character set used by C, the values for the digit characters, whatever they are, are
contiguous. In other words, no matter what values „0‟ and „1‟ have, „1‟ - „0‟ will be 1 (and, obviously,
„0‟ - „0‟ will be 0). So, for a variable c holding some digit character, the expression
c - „0‟
gives us its value. (Similarly, for an integer value i, i + „0‟ gives us the corresponding digit character,
as long as 0 <= i<= 9.)
Just as the character „1‟ is not the integer 1, the string “123” is not the integer 123. When we have a
string of digits, we can convert it to the corresponding integer by calling the standard function
atoi:
char string[] = “123”;
inti = atoi(string);
int j = atoi(“456”);
# include <stdio.h>
# include <conio.h>
main( )
{
charstr [50]
gets (str);
puts (str);
}
Out of the above list, We shall discuss the functions strlen( ), strcpy( ), strcat( ) and strcmp( ), since
these are the most commonly used functions. This will also illustrate how the library functions in
general handle strings. Let us study these functions one by one.
11.5 strlen( )
This function counts the number of characters present in a string. Its usage is illustrated in the
following program.
main( )
{
chararr[ ] = “Bamboozled” ;
int len1, len2 ;
11.6 strcpy( )
This function copies the contents of one string into another. The base addresses of the
source and target strings should be supplied to this function. Here is an example of strcpy(
) in action...
main( )
{
char source[ ] = “Sayonara” ;
char target[20] ;
strcpy ( target, source ) ;
printf ( “\nsource string = %s”, source ) ;
printf ( “\ntarget string = %s”, target ) ;
}
And here is the output...
source string = Sayonara
target string = Sayonara
On supplying the base addresses, strcpy( ) goes on copying the characters in source string into the
target string till it doesn‟t encounter the end of source string („\0‟). It is our responsibility to see to it
that the target string‟s dimension is big enough to hold the string being copied into it.
Thus, a string gets copied into another, piece-meal, character by character. There is no short cut for
this. Let us now attempt to mimic strcpy( ), via our own string copy function, which we will call
xstrcpy( ).
main( )
{
char source[ ] = “Sayonara” ;
char target[20] ;
xstrcpy ( target, source ) ;
printf ( “\nsource string = %s”, source ) ;
printf ( “\ntarget string = %s”, target ) ;
}
xstrcpy ( char *t, char *s )
{
while ( *s != „\0‟ )
{
*t = *s ;
s++ ;
t++ ;
}
*t = „\0‟ ;
}
The output of the program would be...
source string = Sayonara
target string = Sayonara
11.7 strcat( )
This function concatenates the source string at the end of the target string. For example,
“Bombay”and “Nagpur” on concatenation would result into a string “BombayNagpur”. Here is an
example of strcat( ) at work.
#include<stdio.h>
#include<string.h>
int main(){
char name[10];
charlname[10];
printf("Enter Name");
gets(name);
printf("Enter last name");
gets(lname);
strcat(name,lname);
printf("Full name is %s",name);
return 0;
11.8 strcmp( )
This is a function which compares two strings to find out whether they are same or different. The
two strings are compared character by character until there is a mismatch or end of one of the
strings is reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a value
zero. If they‟re not, it returns the numeric difference between the ASCII values of the first non-
matching pairs of characters. Here is a program which puts strcmp( ) in action.
#include<stdio.h>
#include<string.h>
int main(){
char str1[10]="aBC";
char str2[10]="ABC";
String related functions are grouped into string.h header file. It contains the following
functions among others:
1. char * strcat(char *dest, const char *src): This function appends one string to another
returning a pointer to concatenated string. It appends a copy of src to the end of dest. The
length of the resulting string is strlen(dest) + strlen(src). strings.
2. intstrcmp(const char *s1, const char *s2): This function compares two strings. The string
comparison starts with the first character in each string and continues with subsequent
characters until the corresponding characters differ or until the end of the strings is
reached.
The returned values are integers as follows:
< 0 if s1 < s2
= 0 if s1 = = s2
> 0 if s1 > s2
3. char *strcpy(char *dest, const char *src): This function copies string src to dest stopping
after the terminating null character has been moved. The return value is dest.
4. intstrlen(const char *s): This function returns the length of a string (i.e., the number of
characters in s), not counting the terminating null character.
5. intstrncmp(const char *s1, const char *s2, intmaxlen): This function compares portions of
two strings s1 and s2 looking at no more than maxlen characters. The string comparison
starts with the first character in each string and continues with subsequent characters until
the corresponding characters differ or until maxlen characters have been examined. It
returns an int value based on the result of comparing s1 (or part of it) to s2 (or part of it) as
given below:
< 0 if s1 < s2
= 0 if s1 == s2
> 0 if s1 > s2
Syntax
char *names[];
#include <stdio.h>
int main()
{
char *names[] = {"ABC", "DEF"};
inti;
for(i = 0; i< 2; i++)
printf("%s \n", names[i]);
return 0;
}
Summary
A string is defined in C as an array of characters. Each string is terminated by the NULL
character, which indicates end of the string.
A string constant is denoted by any set of characters included in double-quote marks.
The NULL character is automatically appended to the end of the characters in a string
constant when they are stored. Within a program, the NULL character is denoted by the
escape sequence „\ 0‟.
A string constant represents an array whose lower bound is 0 and whose upper bound is
the number of characters in the string.
Strings are stored in three types of structures - Fixed length structure, Variable length
structure, and Linked structure.
Keywords
gets( ): A C library function used to read a character entered at the keyboard and to place
it at theaddress pointed to by its character pointer argument
puts( ): A C library function that writes its string argument to the screen followed by the
newline
strcat(): The C library function that appends one string to another returning a pointer to
concatenated string
strcmp(): The C library function that compares two strings
string.h: A C header file that contains string manipulating library functions
String: An array of characters terminated by the NULL character
Self Assessment
1. Which one is correct method for Initializing string?
A. Puts ( )
B. Gets ( )
C. Print ( )
D. None of above
A. Scanf ( )
B. Gets ( )
C. Puts ( )
D. Printf ( )
4. String is an______________
A. an array of characters
5. Which of the following function is more appropriate for reading in a multi-word string?
A. gets ( )
B. Puts ( )
C. Printf ( )
D. Sizeo ( )
6. Format specifier is used to print a string is ___________
A. % d
B. % c
C. % s
D. % f
A. Yes
B. No
A. 1
B. 0
C. 2
D. -1
A. strlwr ( )
B. strcpy ( )
C. strlen ( )
D. strpr ( )
A. 16 characters
B. 8 characters
C. 32 characters
D. None of above
A. char input[100];
B. puts(„Input string‟);
C. gets(input);
D. puts("Entered string is");
6. C 7. A 8. C 9. B 10. C
Review Questions
1. Write a C program that reads a sentence from the keyboard and prints the frequency of each
letter.
2. How can you create a string type C variable? Can they be assigned to each other in the same way
as other data types? Explain.
3. Write a program that converts a string like “124” to an integer 124.
4. Write a program that replaces two or more consecutive blanks in a string by a single blank.
For example, if the input is
Further Readings
Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education, Year of
Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming With C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
Web Links
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
• Dynamic Memory Management functions
• malloc() and calloc()
• realloc() and free()
Introduction
The Dynamic Memory Allocation concept is utilized to solve the array problem. An array is a set of
values with a fixed number of elements. You can't adjust the size of an array once it's been declared.
Programmers can use Dynamic Memory Allocation to allocate memory during runtime.
Because the static representation of a linear ordered list using an array wastes resources and, in
some situations, causes overflows. We no longer want to pre-allocate memory to any linear list;
instead, we want to allocate memory to elements as they are added to the list. This necessitates
memory allocation that is dynamic.
variables get allocated permanently variables get allocated only if your program
unit gets active
Allocation is done before program execution Allocation is done during program execution
It uses the data structure called stack for It uses the data structure called heap for
implementing static allocation implementing dynamic allocation
Syntax
ptr = (cast-type*) malloc(byte-size)
Example
ptr = (int*) malloc(20 * sizeof(int));
That is to say it returns a pointer of type void * that is the start in memory of the reserved portionof
size number_of_bytes. If memory cannot be allocated a NULL pointer is returned.
Since a void * is returned the C standard states that this pointer can be converted to any type. The
size_t argument type is defined in stdlib.h and is an unsigned type.
So:
char *cp;
cp = malloc(100);
attempts to get 100 bytes and assigns the start address to cp.
Also it is usual to use the sizeof() function to specify the number of bytes:
int *ip;
ip = (int *) malloc(100*sizeof(int));
Some C compilers may require to cast the type of conversion. The (int *) means coercion to an
integer pointer. Coercion to the correct pointer type is very important to ensure pointer arithmetic
is performed correctly.
It is good practice to use sizeof() even if you know the actual size you want – it makes for device
independent (portable) code.
sizeof can be used to find the size of any data type, variable or structure. Simply supply one ofthese
as an argument to the function.
So:
inti;
struct COORD {float x,y,z};
typedefstruct COORD PT;
sizeof(int), sizeof(i),
sizeof(struct COORD) and
sizeof(PT) are all ACCEPTABLE
In the above, we can use the link between pointers and arrays to treat the reserved memory like
an array, i.e, we can do things like:
ip[0] = 100;
or
for(i=0;i<100;++i) scanf(“%d”,ip++);
When you have finished using a portion of memory you should always free() it. This allows the
memory freed to be available again, possibly for further malloc() calls.
The function free() takes a pointer as an argument and frees the memory to which the pointer
refers.
Example:
#include <stdlib.h>
int main(){
int *ptr;
ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL) {
*(ptr + 7) =80;
int main()
{
int* ptr;
int n, i;
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
It is used to dynamically allocate the specified number of blocks of memory of the specified type.
The malloc() function allocates memory and leaves the memory uninitialized. but, the calloc()
function allocates memory and initializes all bits to zero.It returns NULL if memory is not
sufficient.
realloc
If already allocated dynamically memory is insufficient or more than required, in program we can
change the size of previously allocated memory using the realloc() function.
It is used to dynamically change the memory allocation of a previously allocated memoryre-
allocation of memory maintains the already present value and new blocks will be initialized with
default garbage value. re-allocation of memory maintains the already present value and new blocks
will be initialized with default garbage value.
There are two allocation functions, calloc() and realloc(). Their prototypes
are given below:
void *calloc(size_tnum_elements, size_telement_size};
void *realloc( void *ptr, size_tnew_size);
malloc does not initialise memory (to zero) in any way. If you wish to initialise memory then
usecalloc. calloc there is slightly more computationally expensive but, occasionally, more
convenient than malloc. Also note the different syntax between calloc and malloc in that calloc
takes the number of desired elements, num_elements, and element_size, element_size, as two
individualarguments.
Thus to assign 100 integer elements that are all initially zero you would do:
int *ip;
ip = (int *) calloc(100, size of(int));
realloc is a function which attempts to change the size of a previous allocated block of memory.The
new size can be larger or smaller. If the block is made larger then the old contents
remainunchanged and memory is added to the end of the block. If the size is made smaller then the
remaining contents are unchanged.
If the original block size cannot be resized then realloc will attempt to assign a new block ofmemory
and will copy the old block contents. Note a new pointer (of different value) willconsequently be
returned. You must use this new value. If new memory cannot be reallocated then realloc returns
NULL.
Thus to change the size of memory allocated to the *ip pointer above to an array block of 50integers
instead of 100, simply do:
ip = (int *) calloc( ip, 50);
C language requires the number of elements in an array to be specified at compile time. But it isnot
practically possible with arrays. In arrays we allocate the memory first and then start usingit. This
may result in failure of a program or wastage of memory space.
The concept of dynamic memory location can be used to eradicate this problem. In this
technique,the allocation of memory is done at run time. C language provides four library functions
knownas memory management functions that can be used for allocating and freeing memory
duringprogram execution. These functions help us to build complex application programs that use
theavailable memory intelligently.
Example: Calloc
#include <stdio.h>
int main() {
int * ptr;
ptr = calloc(10, sizeof(int));
if (ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Dynamically Building 10 Blocks ");
return 0;
}
Example: realloc
#include<stdio.h>
int main()
{
char *ptr;
ptr = NULL;
ptr = realloc(ptr,10);
if(ptr != NULL)
printf("Memory created successfully\n");
return 0;
}
12.4 free
The memory allocated using functions malloc() and calloc() is not de-allocated on their ownIt is
used to dynamically de-allocate the memory.
Syntax: free(ptr);
Example: free
#include <stdio.h>
int main() {
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL){
*(ptr + 4) = 50;
printf("Value of the 4th integer is %d\n",*(ptr + 4));
}
free(ptr);
return 0;
}
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, *ptr1;
int n, i;
return 0;
}
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
malloc malloc (sz ) Allocate a block of size sz bytes from memory heap and return a pointer
to the allocated block
e.g., ptr = (cast.type*) malloc (byte_size);
calloc calloc in (sz) Allocate a block of size n x sz bytes from memory heap, initialize it to
zero and return a pointer to the allocated block
e.g., ptr = (cast_type*) calloc (n, elem_size);
realloc realloc (bl,; sz) Adjust the size of the memory block blk allocated on the heap
to sz, copy the contents to a new location if necessary and return a
pointer to the allocated block
e.g., ptr = realloc (ptr, newsize);
free free (blk) Free block of memory blk allocated from memory heap
e.g., free (ptr);
When we don't know how much memory will be required for the software ahead of time.
When we need data structures that don't have a memory restriction.
When you wish to make better use of your memory space.
For example, if you allocate memory space for a 1D array like array[20] and only use 10
memory spaces, the remaining 10 memory spaces will be squandered, and this wasted
memory will be unavailable to other programme variables.
Insertions and deletions in dynamically constructed lists may be done quickly and easily
by manipulating addresses, whereas insertions and deletions in statically allocated
memory result in additional movements and memory waste.
Dynamic memory allocation is required when using the concepts of structures and linked
lists in programming.
Summary
Dynamic memory allocation is to allocate memory at “run time”.
Dynamically allocated memory must be referred to by pointers.
Dynamic Memory Allocation can be defined as a procedure in which the size of a data structure
(like Array) is changed during the runtime.
Malloc method in C is used to dynamically allocate a single large block of memory with the
specified size.
free method in C is used to dynamically de-allocate the memory.
realloc method in C is used to dynamically change the memory allocation of a previously allocated
memory.
Keywords
Dynamic memory allocation: DMA perform manual memory allocation.
free: The free() function used to release space.
malloc: malloc() function reserves a block of memory of the specified number of bytes.
calloc: The calloc() function allocates memory and initializes all bits to zero.
Self Assessment
1. Among 4 header files, which should be included to use the memory allocation functions like
malloc(), calloc(), realloc() and free()?
A. #include<string.h>
B. #include<stdlib.h>
C. #include<memory.h>
D. All of above
A. int* malloc(int);
B. Char* malloc(char);
C. unsigned int* malloc(unsigned int);
D. void* malloc(size_t);
3. malloc() returns a float pointer if memory is allocated for storing float's and a double pointer
if memory is allocated for storing double's. A.
A. True
B. False
C. May Be
D. Can't Say
A. More efficient
B. Less efficient
C. Don’t know
D. None of above
A. Dealloc()
B. free()
C. Both A and B
D. None of the above
A. calloc() allocates the memory and also initializes the allocates memory to zero, while
memory allocated using malloc() has random data.
B. malloc() and memset() can be used to get the same effect as calloc()
C. Both malloc() and calloc() return 'void *' pointer
D. All of the above
A. Zero
B. Null
C. Nothing
D. One
A. remove(p);
B. delete(p);
C. free(p);
D. terminate(p);
A. int
B. char
C. float
D. all of above
6. A 7. A 8. B 9. D 10. C
Review Questions
1. What are the disadvantages of static memory allocation?
2. Differentiate between static memory allocation and dynamic memory allocation.
3. Write a program to demonstrate the malloc() function.
4. Differentia between free and realloc() function.
5. What are the advantages of dynamic memory allocation?
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson
Web Links
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
www.geeksforgeeks.org
Objectives
After studying this unit, you will be able to:
Define structure
Identify array within structure
Define union and deceleration
Explain union of structures
Differentiate between union and structure
Introduction
Arrays can be used to aggregate groups of variables of the same type, as you've seen. The difficulty
now is how to combine data that isn't typed in the same way. The explanation is that C is a
language that can be easily extended. It can be extended by defining data types that are built from
the basic types. That example, you can use a data type called a structure to organize variables of
various types.
The following topics are concerned in this unit:
1. Declaring and defining structures
2. Assigning values to structure members
Example:
struct class
{
int number;
char name [20];
float marks;
}
main( )
{
int x;
staticstruct class student1 = {111, “Rao”, 72.50};
staticstruct class student2 = {222, “Reddy”, 67.00};
static class student 3;
student 3 = student 2;
x = ((student3.number = = student.number) && (student3.marks = =
student2.marks)) ? 1:0;
if (x = = 1)
{
printf (“\nStudent2 and Student2 are same \n”);
printf (“%d %s %f\n”, student3.number, student3.name,
student3.marks);
}
else
printf (“\nStudent2 and Student3 are different\n”);
}
Output: Student2 and Student3 are same.
222 Reddy 67.000000
Example:
Example:
struct marks
{
int number;
float subject [3];
}
student [2];
Example:
struct pay
{
int dearness;
inthouse_rent;
int city;
};
struct salary
{
char name [20];
char department [10];
struct pay allowance;
struct pay arrears;
}
struct salary employee [100];
The pay template is defined outside the salary template and is used to define the structure of
allowance and arrears inside the salary structure.
It is also permissible to nest more than one type of structures:
structpersonal_record
{
structname_part name;
struct date date_of_birth;
------
------
};
Note
s
Lab Exercise
/* Program showing passing of structure member as function parameters * /
Lab Exercise
/* Program passing entire structure as function parameter. * /
structemp
{
charempname [25];
char company [25];
intempno;
}
main( )
{
staticstructemp emp1 = {“Prashant”, SOCEM”, 101};
display (emp1);
}
display (e)
structemp e;
{
printf (“%s\n%s\n%d”, emp.empname, emp.company,
emp.empno);
}
Output: Prashant
SOCEM
101
Example:
#include <stdio.h>
typedefstruct
{
char *name;
intacct_no;
characcttype;
float balance;
}
record;
/* transfer a structure-type pointer to a function */
The compiler allocates a piece of storage that is large enough to hold the largest variable type in the
union. As shown in the example declaration, the member x requires 4 bytes which is the largest
among the members. It is assumed that a float variable requires 4 bytes of storage and the figure
above shows how all the three variables share the same address.
Lab Exercise
main( )
{
struct a
{
inti;
char c[2];
};
struct b
{
int j;
char d[2];
};
union z
{
struct a key;
struct b data;
}strange;
strange.key.i = 512;
strange.data.d[0] = 0;
strange.data.d[1] = 32;
printf(“%d\n”, strange.key.i);
printf(“%d\n”, strange.data.j);
printf(“%d\n”, strange.key.c[0];
printf(“%d\n”, strange.data.d[0];
printf(“%d\n”, strange.key.c[1]);
printf(“%d\n”, strange.data.d[1];
}
Output: 512
512
0
0
32
32
Structures and unions may be freely mixed with arrays.
Example:
union id
{
char color[12];
Example:
#include <stdio.h>
main()
{
union id
{
char color;
int size;
};
struct
{
char manufacturer[20];
float cost;
union id description;
} shirt, trouser;
printf(“%d\n”, sizeof(union id));
Example:
Program to demonstrate initialization of union variables.
#include <stdio.h>
main( )
{
union id
{
char color[12];
int size;
};
struct clothes
{
char manufacturer[20];
float cost;
union id description;
};
staticstruct clothes shirt = {“American”, “25.00”, “White”};
printf(“%d\n”, sizeof(union id));
printf(“%s %5.2f”, shirt.manufacturer, shirt.cost);
printf(“%s %d\n”, shirt.description.color, shirt.description.size);
shirt.description.size = 12;
printf(“%s %5.2f”, shirt.manufacturer, shirt.cost);
printf(“%s %d\n”, shirt.description.color, shirt.description.size);
}
Output: 12
American 25.00 White 26743
American 25.00 ~ 12
Summary
Structure is a derived data type used to store the instances of variables of different data
types.
Structure definition creates a format that may be used to declare structure variables in the
program later on.
The structure operators like dot operator “.” are used to assign values to structure
members.
Structure variable can be initialized as any other data type. An array of structure can be
declared as any other array. In such an array, each element is a structure. Structures may
contain arrays as well as structures.
Union is a memory location that is shared by two or more variables.
When union variable is declared, compiler automatically allocates enough storage to hold
to largest member of union. Only the unions with storage class external or static can be
initialized.
Unions are useful for applications involving multiple members. They are also used in
many
DOS based application softwares. typedef and enum are two user defined data types.
Keywords
Random access file: A file, which allows accessing its records without restriction on the order of
access.
Sequential file: A file, which allows accessing its records only from the first record onwards.
Structure: A grouped data type created by user.
Self-Assessment
1. A structure is a __
A. :
B. .
C. >
D. <
A. structure
B. struct
C. structC
D. none of above
A. function by value
B. function by reference
C. both function by reference and function by value
D. none of above
A. Have one or more pointers which point to the same type of structure, as their member.
B. Can dynamically be expanded or contracted
C. Both of them
D. None of above
9. Union is _____
A. (->)
B. (+)
C. (:)
D. (:)
11. Union differs from structure in the following way
A. Array
B. Structure
C. Function
D. None of the above
13. Which of the following is a collection of multiple data types in and of itself?
A. String
B. Structures
C. Char
D. None of the above
6. C 7. C 8. C 9. D 10. A
Review Questions
1. What do you mean by „Structure‟? How it can be declared and initialized in a C program?
2. Draw a diagram to represent the internal storage of a structure.
3. What do you mean by „Union‟? How it can be declared and initialized in a C program?
4. Differentiate the followings:
(a) Arrays and structures
(b) Local and global structure
(c) Array of structure and structure within array
(d) Structure and union
5. Write short note on:
(a) Internal storage of union
(b) Function returning structures
(c) Structure within a structure
6. Write a program that compares two given dates. To store date use structure say date that
contains three members namely date, month and year. If the dates are equal then display
message as “Equal” otherwise “Unequal”.
7. Explain the usefulness of structures and unions in C.
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Web links
www.en.wikipedia.org
www.web-source.net
www.webopedia.com
Objectives
After studying this unit, you will be able to:
Introduction
Data is only stored in variables and arrays for a limited time. When a programme ends, all of this
data is lost. Files are used to store enormous volumes of data indefinitely. Secondary storage
devices, particularly disc storage devices, are used by computers to store files. We'll go through
how C programmes edit, update, and process data files in this unit.
A file is a set of data or characters that can be text or a programme. In the C programming
language, there are two sorts of files: sequential and random access. Random access files are more
difficult to create than sequential ones. The data or text will be stored or read back sequentially. In
random access file, the data can be accessed and processed randomly
Filename
It is a string of characters that makes up a valid filename for an operating system. It may contain
two parts, a primary name and an optional period with an extension.
Example:
Input.dat
Store
PROG.C
Student.C
Text.out
Data Structure
Data structure of a file is defined as file in the library of standard I/O function definitions. All files
should be declared as of type file before they are used.
Purpose: When we open a file, we must specify what we want to do with the file.
Following is the general format for declaring and opening a file:
File *fp;
fp = fopen ( “filename”, “mode”);
The first statement declares the variable fp as a “pointer to the data type file”.
Modes Description
Whenever a file is opened using fopen function, a file pointer is returned. If the file cannot be
opened for some reason, then the function returns a null pointer.
This facility can be used to test whether a file has been opened or not.
Example:
if (fp == NULL)
printf (“File could not be opened.\n”);
13.3 Closing a File
Example:
.........
FILE *p1, *p2;
p1 = fopen (“INPUT”, “w”);
p2 = fopen (“OUTPUT”, “r”);
.........
fclose(p1);
fclose(p2);
This program opens two files and closes them after all operations on them are completed.
Once a file is closed, its file pointer can be reused for another file. All files are closed automatically
whenever a program terminates. However, closing a file as soon as all operations related to it have
been completed is a good programming habit.
Example:
#include<stdio.h>
int main(){
FILE *fp;
fp=fopen(“abc.txt",“r");
if(fp==NULL)
{
printf("Error, In opening file");
exit(1);
}
fclose(fp);
return 0;
}
getw&putw Functions
The getw and putw are integer-oriented functions. They are similar to the getc and putc functions
and are used to read and write integer values on unix systems.
The general forms of getw and putw are:
putw (integer, fp); &getw (fp);
Example: fprintf (f1,”%s %d %f”, name, age, 7.5); here name is an array variable of type char
and age in an int variable.
The general syntax of fscanf is
fscanf (fp, “control string”, list);
This statement would cause the reading of the items in the list from the file specified by fp,
according to the specifications contained in the control string.
feof( ) Function
The feof function can be used to test for an end of file condition. It takes a file pointer as its only
argument and returns a non-zero integer value if all of the data from the specified file has been
read, and returns zero otherwise. If fp is a pointer to the file that has just been opened for reading,
then the statement
if (feof (fp))
printf (“End of data.\n”);
would display the message “End of data.” on reaching the end of file condition.
Text files: - Text files are the normal .txt files. You can easily create text files using any simple text
editors such as Notepad.
Binary files: -Binary files are mostly the .bin files in your computer.
Syntax
fp=fopen(“filename", “r");
while(fscanf(fp, "%s", str)!=EOF)
{
Example:
#include<stdio.h>
int main()
{
charstr[50];
FILE *fp;
fp=fopen(“abc.txt","r");
if(fp==NULL){
printf("-Error");
exit(1);
}
while(fscanf(fp, "%s", str)!=EOF)
{
printf("%s",str);
}
fclose(fp);
return 0;
}
Writing in file
In C programming writing data block in file is possible.
Syntax
fp=fopen(“filename", “w");
Example:
#include<stdio.h>
int main()
{
char name[20]=“this is C";
FILE *fp;
fp=fopen("abc.txt","w");
fprintf(fp, "%s",name);
printf("Contents written");
fclose(fp);
return 0;
}
Syntax
fp=fopen(“filename", "a");
Example:
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen(“abc.txt","a");
fprintf(fp, "\n of programming");
printf("contents added in file");
fclose(fp);
return 0;
}
Preprocessor
Preprocessor Syntax/Description
Syntax: #define
Macro This macro defines constant value and can be any of the basic data
types.
Pre-existing header files: already available in C/C++ compiler user need to import them.
User-defined header files: defined by the user and can be imported using “#include”.
Standard Header Files:
#include<stdio.h>: functions scanf() and printf().
#include<math.h>: sqrt(), pow(), etc.
#include<iostream>: cin and cout.
#include<string.h>: strlen(), strcmp(), strcpy(), size()
#include<time.h> : date() and time()
Example:
For Standard library
#include<stdio.h>
#include<string.h>
For user defined
#include”myheader.h”
Example:
#include<stdio.h>
#include"header.h"
int main(){
printf("%d",fact(5));
return 0;
}
Macros
A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define
directive.
C Macros
Predefined
User-defined
Example: Predefine
#include<stdio.h>
int main(){
printf("File name : %s\n",__FILE__);
printf("File name : %s\n",__DATE__);
printf("File name : %s\n",__TIME__);
return 0;
}
Summary
File is a collection of data or set of characters may be a text or program.
There are two types of files used in the C language: sequential file and random access file.
While creating a file, fopen() function is used which opens a stream for use and link it with
program and file. fopen() function has two string arguments which represent the name of
the file and the type of I/O to be performed. fclose() function closes a stream that was
opened by a call to fopen(). putc() is used to transfer one character into file. getc()
functions allows you to read data from a file.
Similarly to read or write strings, fgets and fputs functions are used.
The fgets() function reads a string from the file and copies it in a string variable lying in
memory.
fputs() is used to write a string in a data file.
getw() function is used to read an integer from a file.
putw() is used to write as integer value in a file. fprintf() and fscanf() are similar to printf()
and scanf()
Keywords
Data Structure: Data structure of a file is defined as file in the library of standard I/O
function definitions.
NULL: A system-defined value (not 0) that indicates various exceptional conditions such
as end of a string, a pointer referencing nothing, etc.
Random access file: A file, which allows accessing its records without restriction on the
order of access. You can access 60th record without accessing the 59th record, and so on.
Macros
User Define
Predefine
Self-Assessment
1. Text files are______
A. fp=fopen(“abc*txt","a");
B. fprintf(fp, "\n of programming");
C. printf("contents added in file");
D. fclose(fp);
A. r
B. a
C. rb
D. none of above
A. #endif
B. #define
C. #undef
D. None of above
A. .com
B. .in
C. .txt
D. .ppt
A. #endif
B. #define
C. #else
D. #ifdef
A. using “#include”.
B. using “#ifdef”.
C. using “#define”.
D. None of above
A. File extension
B. File name
C. file identifier
D. none of above
A. bytes
B. lines
C. bits
D. All of above
6. B 7. A 8. B 9. D 10. A
Review Questions
1. What do you mean by the “File Handling”? Explain the concept of file handling in C.
2. Explain the various type of files and their access mechanisms.
3. Write in detail about any five file-handling functions in C.
4. What do mean by random file access? How C implements the concept of random file access?
5. Write a program to read a file and display contents with its line numbers.
6. What is significance of Macros in programming?
7. Differentiate between user define and predefine Macros.
Further Readings
Books Ashok N. Kamthane, “Programming with ANCI & Turbo C”, Pearson Education,
Year of Publication, 2008
B.W. Kernighan and D.M. Ritchie, “The Programming Language”, Prentice Hall of India,
New Delhi
Byron Gottfried, “Programming with C”, Tata McGraw Hill Publishing Company Limited,
New Delhi
Greg W Scragg, Genesco Suny, Problem Solving with Computers, Jones and Bartlett, 1997.
R.G. Dromey, Englewood Cliffs, N.J., How to Solve it by Computer, Prentice-Hall
International, 1982.
YashvantKanetkar, Let us C
Web links
www.en.wikipedia.org
www.web-source.net
www.webopedia.com