Block-1 An Introduction To C
Block-1 An Introduction To C
Programming in C
Indira Gandhi National Open University
School of Computer and Information
Sciences (SOCIS)
and Python
An introduction to C 1
MCS-201
BLOCK 1 AN INTRODUCTION TO C
UNIT 1 Programming Fundamentals 5
UNIT 2 Data Types, Operators And Expressions 33
UNIT 3 Decision And Loop Control Statements 60
UNIT 4 Arrays And Strings 84
Happy Programming!!
Indira Gandhi
National Open University MCS-201
School of Computer and
Information Sciences PROGRAMMING IN
C AND PYTHON
Block
1
AN INTRODUCTION TO C
UNIT 1
Programming Fundamentals
UNIT 2
Data Types, Operators and Expressions
UNIT 3
Decision and Loop Control Statements
UNIT 4
Arrays and Strings
Programme / Course Design Committee
Prof. Sanjeev K. Aggarwal, IIT, Kanpur
Prof. V.V. Subrahmanyam
Prof. M. Balakrishnan, IIT , Delhi Director
SOCIS, IGNOU, New Delhi
Prof Harish Karnick, IIT, Kanpur Prof P. Venkata Suresh
SOCIS, IGNOU, New Delhi
Prof. C. Pandurangan, IIT, Madras
Dr. Shashi Bhushan
Dr. Om Vikas, Sr. Director, MIT Associate Professor
SOCIS, IGNOU, New Delhi
Prof P. S. Grover, Sr. Consultant, Shri Akshay Kumar
Prof. (Retd.) S.K. Gupta Associate Professor
IIT, Delhi SOCIS, IGNOU, New Delhi
March, 2021
All rights reserved. No part of this work may be reproduced in any form, by mimeograph or any other means,
without permission in writing from the Indira Gandhi National Open University.
Further information on the Indira Gandhi National Open University courses may be obtained from the
University’s office at Maidan Garhi, New Delhi-110 068.
Programming
UNIT 1 PROGRAMMING FUNDAMENTALS Fundamentals
Structure
1.0 Introduction
1.1 Objectives
1.2 Problem - Solving Techniques
1.2.1 Steps for Problem - Solving
1.2.2 Using Computer as a Problem-Solving Tool
1.3 Basics of Algorithms
1.3.1 Definition
1.3.2 Features of Algorithm
1.3.3 Criteria to be followed by an Algorithm
1.3.4 Top-Down Design
1.4 Flowcharts
1.4.1 Basic Symbols used in Flowchart Design
1.5 Program and a Programming Language
1.6 Structured Programming Concepts
1.7 C Programming Language
1.7.1 History of C Programming Language
1.7.2 Salient Features of C
1.8 Writing a C Program
1.9 Compiling a C Program
1.9.1 The C Compiler
1.9.2 Syntax and Semantic Errors
1.10 Link and Run the C Program
1.10.1 Run the C Program through the Menu
1.10.2 Run from an Executable File
1.10.3 Linker Errors
1.10.4 Logical and Runtime Errors
1.11 Diagrammatic Representation ofC Program Execution Process
1.12 Summary
1.13 Solutions / Answers
1.14 Further Readings
1.0 INTRODUCTION
In our daily life, we routinely encounter and solve problems. We pose
problems that we need or want to solve. For this, we make use of available
resources, and solve them. Some categories of resources include: the time and 5
An Introduction to C efforts of yours and others; tools; information; and money. Some of the
problems that you encounter and solve are quite simple.But some others may
be very complex.
In this unit we introduce you to the concepts of problem-solving, especially as
they pertain to computer programming.
The problem-solving is a skill and there are no universal approaches one can
take to solving problems. Basically one must explore possible avenues to a
solution one by one until s/he comes across a right path to a solution. In
general, as one gains experience in solving problems, one develops one’s own
techniques and strategies, though they are often intangible. Problem-solving
skills are recognized as an integral component of computer programming. It is
a demand and intricate process which is equally important throughout the
project life cycle especially – study, designing, development, testing and
implementation stages. The computer problem solving process requires:
Problem anticipation
Careful planning
Proper thought process
Logical precision
Problem analysis
Persistence and attention.
At the same time it requires personal creativity, analytic ability and expression.
The chances of success are amplified when the problem solving is approached
in a systematic way and satisfaction is achieved once the problem is
satisfactorily solved. The problems should be anticipated in advance as far as
possible and properly defined to help the algorithm definition and development
process.
Computer is a very powerful tool for solving problems. It is a symbol-
manipulating machine that follows a set of stored instructions called a
program. It performs these manipulations very quickly and has memory for
storing input, lists of commands and output. A computer cannot think in the
way we associate with humans. When using the computer to solve a problem,
you must specify the needed initial data, the operations which need to be
performed (in order of performance) and what results you want for output. If
any of these instructions are missing, you will get either no results or invalid
results. In either case, your problem has not yet been solved. Therefore, several
steps need to be considered before writing a program. These steps may free
you from hours of finding and removing errors in your program (a process
called debugging). It should also make the act of problem solving with a
computer a much simpler task.
All types of computer programs are collectively referred to as software.
Programming languages are also part of it. Physical computer equipment such
as electronic circuitry, input/output devices, storage media etc. comes under
hardware. Software governs the functioning of hardware. Operations
6 performed by software may be built into the hardware, while instructions
executed by the hardware may be generated in software. The decision to Programming
Fundamentals
incorporate certain functions in the hardware and others in the software is
made by the manufacturer and designer of the software and hardware. Normal
considerations for this are: cost, speed, memory required, adaptability and
reliability of the system. Set of instructions of the high level language used to
code a problem to find its solution is referred to as Source Program. A
translator program called a compiler or interpreter, translates the source
program into the object program. This is the compilation or interpretation
phase. All the testing of the source program as regards the correct format of
instructions is performed at this stage and the errors, if any, are printed. If there
is no error, the source program is transformed into the machine language
program called Object Program. The Object Program is executed to perform
calculations. This stage is the execution phase. Data, if required by the
program, are supplied now and the results are obtained on the output device.
The complete process is shown in fig 1.1 below:
Results
1.1 OBJECTIVES
After going through this unit, you should be able to:
apply problem solving techniques;
define an algorithm and its features;
design flowcharts;
Define a program;
Understand the history of C programming language;
Compile a C program;
Identify the syntax errors;
Run a C program; and
Understand what are run time and logical errors.
There are many ways of solving a problem and there may be several solutions.
So, it is difficult to recognize immediately which path could be more
productive. Sometimes you do not have any idea where to begin solving a
problem, even if the problem has been defined. Such block sometimes occurs
because you are overly concerned with the details of the implementation even
before you have completely understood or worked out a solution. The best
advice is not to get concerned with the details. Those can come later when the
intricacies of the problem has been understood.
The use of specific examples
To get started on a problem, we can make use of heuristics i.e., the rule of
thumb. This approach will allow us to start on the problem by picking a
specific problem we wish to solve and try to work out the mechanism that will
allow solving this particular problem. It is usually much easier to work out the
details of a solution to a specific problem because the relationship between the
mechanism and the problem is more clearly defined. This approach of focusing
on a particular problem can give us the foothold we need for making a start on
the solution to the general problem.
Similarities among problems
One way to make a start is by considering a specific example. Another
approach is to bring the experience to bear on the current problem. So, it is
important to see if there are any similarities between the current problem and
the past problems which we have solved. The more experience one has the
more tools and techniques one can bring to bear in tackling the given problem.
But sometimes, it blocks us from discovering a desirable or better solution to
the problem. A skill that is important to try to develop in problem - solving is
the ability to view a problem from a variety of angles. One must be able to
metaphorically turn a problem upside down, inside out, sideways, backwards,
forwards and so on. Once one has developed this skill it should be possible to
get started on any problem.
8
Working backwards from the solution Programming
Fundamentals
In some cases we can assume that we already have the solution to the problem
and then try to work backwards to the starting point. Even a guess at the
solution to the problem may be enough to give us a foothold to start on the
problem. We can systematize the investigations and avoid duplicate efforts by
writing down the various steps taken and explorations made. Another practice
that helps to develop the problem solving skills is, once we have solved a
problem, to consciously reflect back on the way we went about discovering the
solution.
The computer is a resource - a versatile tool - that can help you solve some of
the problems that you encounter. A computer is a very powerful general-
purpose tool. Computers can solve or help to solve many types of problems.
There are also many ways in which a computer can enhance the effectiveness
of the time and effort that you are willing to devote to solving a problem. Thus,
it will prove to be well worth the time and effort you spend to learn how to
make effective use of this tool.
In this section, we discuss the steps involved in developing a program.
Program development is a multi-step process that requires you to understand
the problem, develop a solution, write the program, and then test it. This
critical process determines the overall quality and success of your program. If
you carefully design each program using good structured development
techniques, your programs will be efficient, error-free, and easy to maintain.
The following are the steps in detail:
1. Develop an Algorithm and a Flowchart.
2. Write the program in a computer language (for example say C
programming language).
3. Enter the program using some editor.
4. Test and debug the program.
5. Run the program, input data, and get the results.
9
An Introduction to C 1.3.1 Definition
An algorithm is a finite set of steps defining the solution of a particular
problem. An algorithm is expressed in pseudocode - something resembling C
language or Pascal, but with some statements in English rather than within the
programming language. Developing an efficient algorithm requires lot of
practice and skill. It must be noted that an efficient algorithm is one which is
capable of giving the solution to the problem by using minimum resources of
the system such as memory and processor’s time. Algorithm is a language
independent, well structured and detailed. It will enable the programmer to
translate into a computer program using any high-level language.
Example 1.1
Let us try to develop an algorithm to compute and display the sum of two
numbers
1. Start
2. Read two numbers a and b
3. Calculate the sum of a and b and store it in sum
4. Display the value of sum
5. Stop
Example 1.2
Let us try to develop an algorithm to compute and print the average of a set of
data values.
1. Start
2. Set the sum of the data values and the count to zero.
3. As long as the data values exist, add the next data value to the sum and
add 1 to the count.
4. To compute the average, divide the sum by the count.
5. Display the average.
6. Stop
Example 1.3
Write an algorithm to calculate the factorial of a given number.
1. Start
2. Read the number n
3. [Initialize]
i 1 , fact 1
4. Repeat steps 4 through 6 until i = n
11
An Introduction to C 5. fact fact * i
6. i i + 1
7. Print fact
8. Stop
Example 1.4
Write an algorithm to check that whether the given number is prime or not.
1. Start
2. Read the number num
3. [Initialize]
i 2 , flag 1
4. Repeat steps 4 through 6 until i < num or flag = 0
5. rem num mod i
6. if rem = 0 then
flag 0
else
i i + 1
7. if flag = 0 then
Print Number is not prime
Else
Print Number is prime
8. Stop
Once we have defined the problem and have an idea of how to solve it, we can
then use the powerful techniques for designing algorithms. Most of the
problems are complex or large problems and to solve them we have to focus on
to comprehend at one time, a very limited span of logic or instructions. A
technique for algorithm design that tries to accommodate this human limitation
is known as top-down design or stepwise refinement.
Top down design provides the way of handling the logical complexity and
detail encountered in computer algorithm. It allows building solutions to
problems in step by step. In this way, specific and complex details of the
implementation are encountered only at the stage when sufficient groundwork
on the overall structure and relationships among the various parts of the
problem.Before the top down design can be applied to any problem, we must at
least have the outlines of a solution. Sometimes this might demand a lengthy
and creative investigation into the problem while at another time the problem
description may in itself provide the necessary starting point for the top-down
design. Top-down design suggests taking the general statements about the
solution one at a time, and then breaking them down into a more precise
subtask / sub-problem. These sub-problems should more accurately describe
how the final goal can be reached. The process of repeatedly breaking a task
12
down into a subtask and then each subtask into smaller subtasks must continue
until the sub-problem can be implemented as the program statement. With each Programming
Fundamentals
spitting, it is essential to define how sub-problems interact with each other. In
this way, the overall structure of the solution to the problem can be maintained.
Preservation of the overall structure is important for making the algorithm
comprehensible and also for making it possible to prove the correctness of the
solution.
Let us see how to represent the algorithm in a graphical form using a flowchart
in the following section.
1.4 FLOWCHARTS
The next step after the algorithm development is the flowcharting. Flowcharts
are used in programming to diagram the path in which information is
processed through a computer to obtain the desired results. Flowchart is a
graphical representation of an algorithm. It makes use of symbols which are
connected among them to indicate the flow of information and processing. It
will show the general outline of how to solve a problem or perform a task. It is
prepared for better understanding of the algorithm.
13
An Introduction to C 1.4.1 Basic Symbols used in flowchart design
Start/Stop
DECISION MAKING
(Branching)
Input/
Output
Process, Instruction
Example 1.5
Start
Read a,b
Sum = a +b
Print sum
14
Stop
Programming
Fundamentals
Example 1.6
The flowchart for the Example 1.3 (to find factorial of a given number) is
shown low:
Start
Read n
i= 1
fact= 1
is i
<= n?
No
Yes
i = i+1
Print
fact = fact*i fact
Stop
Example 1.7:
15
An Introduction to C
Start
Read num
i=2
flag = 1
no
is
i<num?
yes
no
is
flag = 0?
yes
rem =
num mod i
no
is rem
!= 0?
yes
i=i+1 flag = 0
no
Print is flag
“number is = 1?
not prime”
yes
Print
“Number
stop is prime
16
Check Your Progress 1 Programming
Fundamentals
We have seen in the earlier section’s that a computer has to be fed with a
detailed set of instructions and data for solving a problem. Such a procedure
which we call an algorithm is a series of steps arranged in a logical sequence.
Also we have seen that a flowchart is a pictorial representation of a sequence
of instructions given to the computer. It also serves as a document explaining
the procedure used to solve a problem. In practice it is necessary to express an
algorithm using a programming language. A procedure expressed in a
programming language is known as a computer program.
18
Programming
1.6 C PROGRAMMINGLANGUAGE Fundamentals
20 ……………………………………………………………………………………...
Programming
1.7 STRUCTURE OF A C PROGRAM Fundamentals
As we have already seen, to solve a problem there are three main things to be
considered. Firstly, what should be the output? Secondly, what should be the
inputs that will be required to produce this output and thirdly, the steps of
instructions which use these inputs to produce the required output. As stated
earlier, every programming language follows a set of rules; therefore, a
program written in C also follows predefined rules known as syntax. C is a
case sensitivelanguage. All C programs consist of one or more functions. One
function that must be present in every C program is main(). This is the first
function called up when the program execution begins. Basically, main()
outlines what a program does. Although main is not given in the keyword
list,it cannot be used for naming a variable. The structure of a C program is
illustrated in Figure.1.3 where functions func1() through funcn() represent user
defined functions.
Preprocessor directives
Global data declarations
main ( ) /* main function*/
{
Declaration part;
Program statements;
}
func2 ( )
{
…………
}
.
funcn ( )
{
…………
}
Figure. 1.3: Structure of a C Program.
A Simple C Program
From the above sections, you have become familiar with, a programming
language and structure of a C program. It’s now time to write a simple C
program. This program will illustrate how to print out the message “This is a C
program”.
Example 1.8: Write a program to print a message on the screen.
/*Program to print a message*/
START
INPUT
a, b
Sum = a + b
PRINT
Sum
STOP
Program
#include<stdio.h>
main()
{
int a,b,sum; /* variables declaration*/
sum=a+b;
OUTPUT
In the above program considers two variables a and b. These variables are
declared as integers (int), it is the data type to indicate integer values. Next
statement is the printf statement meant for prompting the user to input the
values of aand b. scanf is the function to intake the values into the program
provided by the user. Next comes the processing / computing part which
computes the sum. Again the printf statement is a bit different from the first
program; it includes a format specifier (%d). The format specifier indicates the 23
An Introduction to C kind of value to be printed. We will study about other data types and format
specifiers in detail in the following units. In the printf statement above, sum is
not printed in double quotes because we want its value to be printed. The
number of format specifiers and the variable should match in the printf
statement.
At this stage, don’t go much in detail. However, in the following units you will
be learning all these details.
Let the name of the program be test.c .If we compile the above program as it is
we will get the following errors:
Error test.c 1:No file name ending
Error test.c 5: Statement missing ;
Error test.c 6: Compound statement missing }
Edit the program again, correct the errors mentioned and the corrected version
appears as follows:
#include <stdio.h>
main( )
{ 25
An Introduction to C printf (“Hello, how are you\n”);
}
Apart from syntax errors, another type of errors that are shown while
compilation are semantic errors. These errors are displayed as warnings. These
errors are shown if a particular statement has no meaning. The program does
compile with these errors, but it is always advised to correct them also, since
they may create problems while execution. The example of such an error is
that say you have declared a variable but have not used it, and then you get a
warning “code has no effect”. These variables are unnecessarily occupying the
memory.
Check Your Progress 3
1. What is the basic unit of a C program?
……………………………………………………………………………………...
……………………………………………………………………………………...
……………………………………………………………………………………...
……………………………………………………………………………………...
……………………………………………………………………………………...
All these options create an executable file and when these options are used we
also get the output on user screen. To see the output we have to shift to user
screen window.
UNIX also includes a very useful program called make. Make allows very
complicated programs to be compiled quickly, by reference to a configuration
file (usually called makefile). If your C program is a single file, you can
usually use make by simply typing –
make testprog
This will compile testprog.c as well as link your program with the standard
library so that you can use the standard library functions such as printf and put
the executable code in testprog.
The first case simply means that the program is correct. In the second case, we
get wrong results; it means that there is some logical mistake in our program.
This kind of error is known as logical error. This error is the most difficult to
correct. This error is corrected by debugging. Debugging is the process of
removing the errors from the program. This means manually checking the
program step by step and verifying the results at each step. Debugging can be
made easier by a tracer provided in Turbo C environment. Suppose we have to
find the average of three numbers and we write the following code:
Example 1.11:Write a C program to compute the average of three
numbers
/* Program to compute average of three numbers *?
#include<stdio.h>
main( )
{
int a,b,c,sum,avg;
a=10;
b=5;
c=20;
sum = a+b+c;
avg = sum / 3;
printf(“The average is %d\n”, avg);
}
OUTPUT
The average is 8.
The exact value of average is 8.33 and the output we got is 8. So we are not
getting the actual result, but a rounded off result. This is due to the logical
error. We have declared variable avgas an integer but the average calculated is
a real number, therefore only the integer part is stored in avg. Such kinds of
errors which are not detected by the compiler or the linker are known as
logical errors.
The third kind of error is only detected during execution. Such errors are
known as run time errors. These errors do not produce the result at all, the
program execution stops in between and the run time error message is flashed
28 on the screen. Let us look at the following example:
Example 1.12: Write a program to divide a sum of two numbers by their Programming
Fundamentals
difference
#include <stdio.h>
main( )
{
int a,b;
float c;
a=10;
b=10;
c = (a+b) / (a-b);
printf(“The value of the result is %f\n”,c);
}
The above program will compile and link successfully, it will execute till the
first printf statement and we will get the message in this statement, as soon as
the next statement is executed we get a runtime error of “Divide by zero” and
the program halts. Such kinds of errors are runtime errors.
WRITE A C PROGRAM
DEBUG SYNTAX
ERRORS (IF ANY), SAVE
AND RECOMPILE
1.12 SUMMARY
To solve a problem different problem - solving tools are available that help in
finding the solution to problem in an efficient and systematic way. Steps
should be followed to solve the problem that includes writing the algorithm
and drawing the flowchart for the solution to the stated problem. Top down
design provides the way of handling the logical complexity and detail
encountered in computer algorithm. It allows building solutions to problems in
a stepwise fashion. In this way, specific and complex details of the
implementation are encountered only at the stage when sufficient groundwork
on the overall structure and relationships among the carious parts of the
problem. We present C language - a standardized, industrial-strength
programming language known for its power and portability as an
implementation vehicle for these problem solving techniques using computer.
In this unit, you have learnt about a program and a programming language.
You can now differentiate between high level and low level languages. You
can now define what is C, features of C. You have studied the emergence of C.
You have seen how C is different, being a middle level Language, than other
High Level languages. The advantage of high level language over low level
language is discussed.
30
You have seen how you can convert an algorithm and flowchart into a C Programming
Fundamentals
program. We have discussed the process of writing and storing a C program in
a file in case of UNIX as well as DOS environment.
You have learnt about compiling and running a C program in UNIX as well as
on DOS environment. We have also discussed about the different types of
errors that are encountered during the whole process, i.e. syntax errors,
semantic errors, logical errors, linker errors and runtime errors. You have also
learnt how to remove these errors. You can now write simple C programs
involving simple arithmetic operators and the printf( ) statement. With these
basics, now we are ready to learn the C language in detail in the following
units.
32
Data Types,
UNIT 2 DATA TYPES, OPERATORS AND Operators and
Expressions
EXPRESSIONS
Structure
2.0 Introduction
2.1 Objectives
2.2 C Language Character Set
2.3 Identifiers and Keywords
2.3.1 Rules for Forming Identifiers
2.3.2 Keywords
2.4 Data Types and Storage
2.5 Data Type Qualifiers
2.6 Variables
2.7 Declaring Variables
2.8 Initializing Variables
2.9 Constants
2.9.1 Integer Constants
2.9.2 Floating Point Constants
2.9.3 Character Constants
2.9.4 String Constants
2.10 Symbolic Constants and Others
2.11 Expressions and Operators – An Introduction
2.12 Assignment Statements
2.13 Arithmetic Operators
2.14 Relational Operators
2.15 Logical Operators
2.16 Comma and Conditional Operators
2.17 Type Cast Operator
2.18 Size of Operator
2.19 C Shorthand
2.20 Priority of Operators
2.21 Summary
2.22 Solutions / Answers
2.23 Further Readings
2.0 INTRODUCTION
As every natural language has a basic character set, computer languages also
have a character set, rules to define words. Words are used to form
statements. These in turn are used to write the programs.
Computer programs usually work with different types of data and need a way
to store the values being used. These values can be numbers or characters. C 33
An Introduction to C language has two ways of storing number values—variables and
constants—with many options for each. Constants and variables are the
fundamental elements of each program. Simply speaking, a program is
nothing else than defining them and manipulating them.
A variable is a data storage location that has a value that can change during
program execution. In contrast, a constant has a fixed value that can’t change.
This unit is concerned with the basic elements used to construct simple C
program statements. These elements include the C character set, identifiers
and keywords, data types, constants, variables and arrays, declaration and
naming conventions of variables.
2.1 OBJECTIVES
After going through this unit, you will be able to:
define identifiers, data types and keywords in C;
know name the identifiers as per the conventions;
describe memory requirements for different types of variables;
define constants, symbolic constants and their use in programs.write and
evaluate arithmetic expressions;
express and evaluate relational expressions;
write and evaluate logical expressions;
write and solve compute complex expressions (containing arithmetic, relational
and logical operators), and
use simple conditions using conditional operators.
34
Data Types,
2.3 IDENTIFIERS AND KEYWORDS Operators and
Expressions
2.3.2 Keywords
Keywords are reserved words which have standard, predefined meaning in C.
They cannot be used as program-defined identifiers.
The list of keywords in C language are as follows:
char while do typedef auto
int if else switch case
printf double struct break static
long enum register extern return
union const float short unsigned
continue for signed void default
goto sizeof volatile
Note: Generally all keywords are in lower case although uppercase of same
names can be used as identifiers.
35
An Introduction to C
2.4 DATA TYPES AND STORAGE
To store data inside the computer we need to first identify the type of data
elements we need in our program. There are several different types of data,
which may be represented differently within the computer memory. The data
type specifies two things:
1. Permissible range of values that it can store.
2. Memory requirement to store a data type.
C Language provides four basic data types viz. int, char, float and double.
Using these, we can store data in simple ways as single elements or we can
group them together and use different ways (to be discussed later) to store
them as per requirement. The four basic data types are described in the
following table 2.1:
Table 2.1: Basic Data Types
DATA TYPE TYPE OF DATA MEMORY RANGE
int Integer 2 Bytes 32,768 to 32,767
char character 1 Byte 128 to 128
float Floating point 4 bytes 3.4e 38 to 3.4e +38
number
double Floating point 8 bytes 1.7e 308 to 1.7e + 308
number with higher
precision
Memory requirements or size of data associated with a data type indicates the
range of numbers that can be stored in the data item of that type.
36
Data Types,
2.6 VARIABLES Operators and
Expressions
For example,
int a;
short int a, b;
int c, d;
long c, f;
float r1, r2;
int a = 10;
float b = 0.4 e –5;
char c = ‘a’;
37
An Introduction to C
b) Using Assignment Statement
The values are assigned just after the declarations are made.
For example,
int a;
float b;
char c;
a = 10;
b = 0.4 e –5;
c = ‘a’;
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
2.9 CONSTANTS
A constant is an identifier whose value cannot be changed throughout the
execution of a program whereas the variable value keeps on changing. In C
there are four basic types of constants. They are:
1. Integer constants
38
2. Floating point constants Data Types,
Operators and
3. Character constants Expressions
4. String constants
Integer and Floating Point constants are numeric constants and represent
numbers.
Rules to form Integer and Floating Point Constants
No comma or blankspace is allowed in a constant.
It can be preceded by – (minus) sign if desired.
The value should lie within a minimum and maximum permissible range
decided by the word size of the computer.
For example,
1 443 32767
are valid decimal integer constants.
Decimal integer
Decimal point
Decimal fraction
e or E and a signed integer exponent (optional)
Type suffix: f or F or l or L (optional)
Either decimal integer or decimal fraction (but not both) can be omitted.
Either decimal point or letter e (or E) with a signed integer exponent (but not
both) can be omitted. These rules allow conventional and scientific
(exponent) notations.
Negative floating constants are taken as positive constants with an unary
operator minus (-) prefixed. If there is a need for a floating-point constant
that exceeds these limits, user should add l or L suffix, making the constant
a long double type.
Here are some examples:
0. // is equal to 0.0
-1.23 // is equal to -1.23
23.45e6 // is equal to 23.45 X 106
2e-5 //is equal to 2.0 X 10-5
3e+10 //is equal to 3.0 X 1010
.09E34 //is equal to 0.09 X 1034
40
For example, some of the character constants are shown below: Data Types,
Operators and
‘A’, ‘x’, ‘3’, ‘$’ Expressions
Escape Sequence
Many programming languages support a concept called Escape Sequence.
When a character is preceded by a backslash (\), it is called an escape
sequence and it has a special meaning to the compiler. For example, \n in the
following statement is a valid character and it is called a new line character in
C language.
Examples:
41
An Introduction to C Advantages of using Symbolic Constants are:
They can be used to assign names to values.
Replacement of value has to be done at one place and wherever the name
appears in the text it gets the value by execution of the preprocessor.
This saves time. if the symbolic constant appears 20 times in the
program; it needs to be changed at one place only.
#include<stdio.h>
int main()
{
typedef unsigned in uint;
uint j=5, k=9;
printf(“j= %d\n”,j);
printf(“k= %d\n”,k);
return 0;
}
Check Your Progress 2
1) Write a preprocessor directive statement to define a constant PI having
the value 3.14.
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
2) Classify the examples into Integer, Character and String constants.
‘A’ 0147 0xEFH
077.7 “A” 26.4
“EFH” ‘\r’ abc
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
3) Name different categories of constants C programming language.
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
43
An Introduction to C
2.11 EXPRESSIONS AND OPERATORS - AN
INTRODUCTION
The data type of the variable on left hand side should match the data type of
constant/variable/expression on right hand side with a few exceptions where
automatic type conversions are possible. Some examples of assignment
statements are as follows:
b =a; /* b is assigned the value of a */
b=5; /* b is assigned the value 5*/
b = a+5; /* b is assigned the value of expr a+5 */
The expression on the right hand side of the assignment statement can be:
an arithmetic expression;
a relational expression;
a logical expression;
a mixed expression.
44
The above mentioned expressions are different in terms of the type of Data Types,
Operators and
operators connecting the variables and constants on the right hand side of the Expressions
variable. Arithmetic operators, relational operators and logical operators are
discussed in the following sections.
For example,
int a;
float b,c ,avg, t;
avg = (b+c) / 2; /*arithmetic expression */
a = b && c; /*logical expression*/
a = (b+c) && (b<c); /* mixed expression*/
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular Division
Some of the examples of algebraic expressions and their C notation are given below:
Expression C notation
b* g (b *g) / d
d
The arithmetic operators are all binary operators i.e. all the operators have
two operands. The integer division yields the integer result. For example, the
expression 10/3 evaluates to 3 and the expression 15/4 evaluates to 3. C
provides the modulus operator, %, which yields the reminder after integer
division. The modulus operator is an integer operator that can be used only
with integer operands. The expression x%y yields the reminder after x is
divided by y. Therefore, 10%3 yields 1 and 15%4 yields 3. An attempt to
divide by zero is undefined on computer system and generally results in a
run- time error. Normally, Arithmetic expressions in C are written in straight-
line form. Thus ‘a divided by b’ is written as a/b.
The operands in arithmetic expressions can be of integer, float, double type.
In order to effectively develop C programs, it will be necessary for you to
understand the rules that are used for implicit conversion of floating point
and integer values in C.
45
An Introduction to C They are mentioned below:
An arithmetic operator between an integer and integer always yields an
integer result.
Operator between float and float yields a float result.
Operator between integer and float yields a float result.
If the data type is double instead of float, then we get a result of double data
type.
For example,
Operation Result
5/3 1
5.0/3 1.6666666667
5/3.0 1.6666666667
5.0/3.0 1.6666666667
It may so happen that the type of the expression and the type of the variable
on the left hand side of the assignment operator may not be same. In such a
case the value for the expression is promoted or demoted depending on the
type of the variable on left hand side of = (assignment operator). For
example, consider the following assignment statements:
int i;
float b;
i = 4.6;
b = 20;
In the first assignment statement, float (4.6) is demoted to int. Hence i gets
the value 4. In the second assignment statement int (20) is promoted to float,
b gets 20.0. If we have a complex expression like:
float a, b, c;
int s;
s = a * b / 5.0 * c;
Where some operands are integers and some are float, then int will be promoted or
demoted depending on left hand side operator. In this case, demotion will take place
since s is an integer.
46
For example, Data Types,
( ((3+4)*5)/6 ) Operators and
Expressions
The order of evaluation is given below:
( ( (3+4) * 5) / 6 )
1 2 3
For example,
5*5+6*7
The order of evaluation is given below.
5*5+6*7
1 2
3
For example,
8/5-6+5/2
The order of evaluation is given below.
8/5-6+5/2
1 3 4 2
Apart from these binary arithmetic operators, C also contains two unary
operators referred to as increment (++) and decrement (--) operators, which
we are going to be discussed below:
The two-unary arithmetic operators provided by C are:
Increment operator (++)
Decrement operator (- -)
The importance of pre and post operator occurs while they are used in the
expressions. Preincrementing (Predecrementing) a variable causes the
variable to be incremented (decremented) by 1, then the new value of the
variable is used in the expression in which it appears. Postincrementing
(postdecrementing) the variable causes the current value of the variable is
used in the expression in which it appears, then the variable value is
incremented (decrement) by 1.
The explanation is given in the table below:
Expression Explanation
++a Increment a by 1, then use the new value of a
a++ Use value of a, then increment a by 1
--b Decrement b by 1, then use the new value of b
b-- Use the current value of b, then decrement by 1
The precedence of these operators is right to left. Let us consider the
following examples:
int a = 2, b=3;
int c;
c = ++a – b- -;
printf (“a=%d, b=%d,c=%d\n”,a,b,c);
OUTPUT
a = 3, b = 2, c = 0.
Since the precedence of the operators is right to left, first b is evaluated, since
it is a post decrement operator, current value of b will be used in the
expression i.e. 3 and then b will be decremented by 1.Then, a preincrement
operator is used with a, so first a is incremented to 3. Therefore, the value of
the expression is evaluated to 0.
Let us take another example,
int a = 1, b = 2, c = 3;
int k;
k = (a++)*(++b) + ++a - --c;
printf(“a=%d,b=%d, c=%d, k=%d”,a,b,c,k);
OUTPUT
a = 3, b = 3, c = 2, k = 6
The evaluation is explained below:
k = (a++) * (++b)+ ++a - --c
= (a++) * (3) + 2 - 2 step1
= (2) * (3) + 2 - 2 step2
= 6 final result
48
Check Your Progress 3 Data Types,
Operators and
Expressions
1. Give the C expressions for the following algebraic expressions:
i) a*4c2 - d
m+n
ii) ab - (e+f)4
c
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
2. Give the output of the following C code:
main()
{
int a=2,b=3,c=4;
k = ++b + --a*c + a;
printf(“a= %d b=%d c=%d k=%d\n”,a,b,c,k);
}
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
3. Point out the error:
exp = a**b;
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
50
Data Types,
2.15 LOGICAL OPERATORS Operators and
Expressions
Thus logical operators (AND and OR) combine two conditions and logical
NOT is used to negate the condition i.e. if the condition is true, NOT negates
it to false and vice versa.Let us consider the following is:
i) Suppose the grade of the student is ‘B’ only if his marks lie within the
range 65 to 75,if the condition would be:
if((marks >=65) && (marks <= 75))
printf (“Grade is B\n”);
ii) Suppose we want to check that a student is eligible for admission if his
PCM is greater than 85% or his aggregate is greater than 90%, then,
Logical negation (!) enables the programmer to reverse the meaning of the
condition. Unlike the && and || operators, which combines two conditions
(and are therefore Binary operators), the logical negation operator is a unary
operator and has one single condition as an operand. Let us consider an
example:
if!(grade==’A’)
printf (“the next grade is %c\n”, grade);
The parentheses around the condition grade==A are needed because the
logical operator has higher precedence than equality operator. The truth table
of the logical AND (&&), OR (||) and NOT (!) are given below.
These table show the possible combinations of zero (false) and nonzero (true)
values of x (expression1) and y (expression2) and only one expression in case
of NOT operator. The following table 2.3 is the truth table for && operator.
51
An Introduction to C Table 2.3: Truth table for && operator
x y x&&y
zero zero 0
Non zero zero 0
zero Non zero 0
Non zero Non zero 1
x y x || y
zero zero 0
x !x
zero 1
Non zero 0
The following table 2.6 shows the operator precedence and associativity
Operator Associativity
! Right to left
|| Left to right
52
The syntax is as follows: Data Types,
Operators and
(condition)? (expression1): (expression2); Expressions
54
else if one operand is double, the other is converted to double, Data Types,
Operators and
else if one operand is long, the other is converted to long, Expressions
(type) expression
where type is the standard C data type. For example, if you want to make sure
that the expression a/5 would evaluate to type float you would write it as
( float ) a/5
cast is an unary operator and has the same precedence as any other unary
operator. The use of cast operator is explained in the following example:
main()
{
int num;
printf(“%f %f %f\n”, (float)num/2, (float)num/3, float)num/3);
}
Tha cast operator in this example will ensure that fractional part is also
displayed on the screen.
55
An Introduction to C
2.19 C SHORTHAND
C has a special shorthand that simplifies coding of certain type of assignment
statements. For example: a = a+2;
can be written as: a += 2;
The operator +=tells the compiler that a is assigned the value of a + 2;
This shorthand works for all binary operators in C. The general form is:
variable operator = variable / constant / expression;
These operators are listed below:
Operators Examples Meaning
+= a+=2 a=a+2
-= a-=2 a=a-2
= a*=2 a = a*2
/= a/=2 a=a/2
%= a%=2 a=a%2
Operators Examples Meaning
&&= a&&=c a=a&&c
||= a||=c a=a||c
Operators Associativity
() Left to right
! ++ -- (type) sizeof Right to left
/% Left to right
+- Left to right
< <= > >= Left to right
== != Left to right
&& Left to right
|| Left to right
?: Right to left
= += -= *= /= %= &&= ||= Right to left
, Left to right
56
Check Your Progress 5 Data Types,
Operators and
1. Give the output of the following C code: Expressions
main( )
{
int a,b=5;
float f;
a=5/2;
f=(float)b/2.0;
(a<f)? b=1:b=0;
printf(“b = %d\n”,b);
}
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
2. What is the difference between && and &. Explain with an example.
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
3. Use of Bit Wise operators makes the execution of the program.
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
……………………………………………………………………………
2.21 SUMMARY
To summarize we have learnt certain basics, which are required to learn a
computer language and form a basis for all languages. Character set includes
alphabets, numeric characters, special characters and some graphical
characters. These are used to form words in C language or names or
identifiers. Variable are the identifiers, which change their values during
execution of the program. Keywords are names with specific meaning and
cannot be used otherwise.
57
An Introduction to C We had discussed four basic data types - int, char, float and double. Some
qualifiers are used as prefixes to data types like signed, unsigned, short, and
long.
The constants are the fixed values and may be either Integer or Floating point
or Character or String type. Symbolic Constants are used to define names
used for constant values. They help in using the name rather bothering with
remembering and writing the values.
In this unit, we discussed about the different types of operators, namely
arithmetic, relational, logical present in C and their use. In the following
units, you will study how these are used in C’s other constructs like control
statements, arrays etc. This unit also focused on type conversions. Type
conversions are very important to understand because sometimes a
programmer gets unexpected results (logical error) which are most often
caused by type conversions in case user has used improper types or if he has
not type cast to desired type.
C is referred to as a compact language which is because lengthy expressions
can be written in short form. Conditional operator is one of the examples,
which is the short form of writing the if/else construct (next unit). Also
increment/decrement operators reduce a bit of coding when used in
expressions.
Since logical operators are used further in all types of looping constructs and
if/else construct (in the next unit), they should be thoroughly understood.
58
ii) a*b-(e+f)*4/c
2. The output would be: Data Types,
Operators and
a=1 b=4 c=4 k=10 Expressions
59
An Introduction to C
UNIT 3 DECISION AND LOOP CONTROL
STATEMENTS
Structure
3.0 Introduction
3.1 Objectives
3.2 Decision Control Statements
3.2.1 The if Statement
3.2.2 The switch Statement
3.3 Loop Control Statements
3.3.1 The while Loop
3.3.2 The do-while Statement
3.3.3 The for Loop
3.3.4 The Nested Loop
3.4 The Goto Statement
3.5 The Break Statement
3.6 The Continue Statement
3.7 Summary
3.8 Solutions / Answers
3.9 Further Readings
3.0 INTRODUCTION
A program consists of a number of statements to be executed by the
computer. Not many of the programs execute all their statements in
sequential order from beginning to end as they appear within the program. A
C program may require that a logical test be carried out at some particular
point within the program. One of the several possible actions will be carried
out, depending on the outcome of the logical test. This is called Branching.
In the Selection process, a set of statements will be selected for execution,
among the several sets available. Suppose, if there is a need of a group of
statements to be executed repeatedly until some logical condition is satisfied,
then looping is required in the program. These can be carried out using
various control statements.
These Control statements determine the “flow of control” in a program and
enable us to specify the order in which the various instructions in a program
are to be executed by the computer. Normally, high level procedural
programming languages require three basic control statements:
Sequence instruction
Selection/decision instruction
Repetition or Loop instruction
60
Decision and Loop
Sequence instruction means executing one instruction after another, in the Control Statements
order in which they occur in the source file. This is usually built into the
language as a default action, as it is with C. If an instruction is not a control
statement, then the next instruction to be executed will simply be the next one
in sequence.
Selection means executing different sections of code depending on a specific
condition or the value of a variable. This allows a program to take different
courses of action depending on different conditions. C provides three
selection structures.
if
if…else
switch
Repetition/Looping means executing the same section of code more than once. A
section of code may either be executed a fixed number of times, or while some
condition is true. C provides three looping statements:
while
do…while
for
This unit introduces you the decision and loop control statements that are
available in C programming language along with some of the example
programs.
3.1 OBJECTIVES
After going through this unit you will be able to:
work with different control statements;
know the appropriate use of the various control statements in
programming;
transfer the control from within the loops;
use the goto, break and continue statements in the programs; and
write programs using branching, looping statements.
61
An Introduction to C
3.2.1 The if Statement
It is used to execute an instruction or sequence/block of instructions only if a
condition is fulfilled. In if statements, expression is evaluated first and then,
depending on whether the value of the expression (relation or condition) is
“true” or “false”, it transfers the control to a particular statement or a group
of statements.
Simple if statement
It is used to execute an instruction or block of instructions only if a condition
is fulfilled.
Example 3.1
Write a program to calculate the net salary of an employee, if a tax of 15% is
levied on his gross-salary if it exceeds Rs. 10,000/- per month.
#include<stdio.h>
main()
{
float gross_salary, net_salary;
if(gross_salary <10000)
net_salary= gross_salary;
if(gross_salary >= 10000)
net_salary = gross_salary- 0.15*gross_salary;
OUTPUT
If … else statement
If…else statement is used when a different sequence of instructions is to be
executed depending on the logical value (True / False) of the condition
evaluated.
Its form used in conjunction with if and the syntax is as follows:
if(condition)
Statement _1;
else
Statement_ 2;
statement_3;
63
An Introduction to C Or
if(condition)
{
Statements_1_Block;
}
else
{
Statements_2_Block;
}
Statements _3_Block;
Example:
#include<stdio.h>
main()
{
int x=2;
int y;
y = (x >= 6) ? 6 : x;
printf(“y = %d”,y);
return 0;
}
OUTPUT : y = 2
else
{
Statements_2_Block;
}
}
else
{
Statements_3_Block;
}
Statement_4_Block;
Example 3.3
Write a program to calculate an Air ticket fare after discount, given the
following conditions:
If passenger is below 14 years then there is 50% discount on fare
If passenger is above 50 years then there is 20% discount on fare
If passenger is above 14 and below 50 then there is 10% discount on
fare.
Here, the coonditions aree evaluated ini order fromm top to botttom. As soonn as
any conditiion evaluatess to true, theen the statem
ment associatted with the given
g
condition iss executed aand control iss transferredd to Statemen
nts_x skippinng the
rest of the conditions
c foollowing it.
OUTPUT
Enter the total marks of a student:
80
Grade A
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
69
An Introduction to C 2. Find the output for the following program:
#include<stdio.h>
main()
{
int a,b=0;
if(a=b=1)
printf("hello");
else
printf("world");
return 0;
}
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
3.2.2 The Switch Statement
Its objective is to check several possible constant values for an expression,
something similar to what we had studied in the earlier sections, with the
linking of several if and else if statements. When the actions to be taken
depending on the value of control variable, are large in number, then the use
of control structure Nested if…else makes the program complex. There
switch statement can be used. Its form is the following:
switch(expression){
case expression 1:
block of instructions1
break;
case expression 2:
block of instructions2
break;
.
.
default:
default block of instructions
}
It works in the following way: switch evaluates expression and checks if it is
equivalent to expression1. If it is, it executes block of instructions 1 until it
finds the break keyword, moment at finds the control will go to the end of
the switch. If expression was not equal to expression 1 it will check whether
expression is equivalent to expression 2. If it is, it will execute block of
instructions 2 until it finds the break keyword.
Finally, if the value of expression has not matched any of the previously
specified constants (you may specify as many case statements as values you
want to check), the program will execute the instructions included in the
default: section, if it exists, as it is an optional statement.
70
Decision and Loop
Let us consider a program to illustrate Switch statement, Control Statements
Example 3.5
Write a program that performs the following, depending upon the choice
selected by the user.
i). calculate the square of number if choice is 1
ii). calculate the square-root of number if choice is 2 and 4
iii). calculate the cube of the given number if choice is 3
iv). otherwise print the number as it is
main()
{
int choice,n;
printf(“\n Enter any number:\n “);
scanf(“%d”,&n);
printf(“Choice is as follows:\n\n”);
printf(“1. To find square of the number\n”);
printf(“2. To find square-root of the number\n”);
printf(“3. To find cube of a number\n”);
printf(“4. To find the square-root of the number\n\n”);
printf(“Enter your choice:\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“The square of the number is %d\n”,n*n);
break;
case 2:
case 4: printf(“The square-root of the given number is %f”,sqrt(n));
break;
case 3: printf(“ The cube of the given number is %d”,n*n*n);
default: printf(“The number you had given is %d”,n);
break;
}
}
OUTPUT
Enter any number: 4
Choice is as follows:
1. To find square of the number
2. To find square-root of the number
3. To find cube of a number
4. To find the square-root of the number
Here, test condition is an expression that controls how long the loop keeps
running. Body of the loop is a statement or group of statements enclosed in
braces and are repeatedly executed till the value of test condition evaluates to
true. As soon as the condition evaluates to false, the control jumps to the first
statement following the while statement. If condition initially itself is false,
the body of the loop will never be executed. While loop is sometimes called
as entry-control loop, as it controls the execution of the body of the loop
depending upon the value of the test condition. This is shown in the figure
5.5 given below:
Example 3.6
Write a program to calculate the factorial of a given input natural number.
#include<stdio.h>
#include<math.h>
main()
{
int x;
long int fact = 1;
printf(“Enter any number to find factorial:\n”); /*read the number*/
scanf(“%d”,&x);
while(x > 0)
{
fact = fact*x; /* factorial calculation*/
x=x-1;
}
printf(“Factorial is %ld”,fact);
}
OUTPUT
Factorial is 24
Here, condition in while loop is evaluated and body of loop is repeated until
condition evaluates to false i.e., when x becomes zero. Then the control is
jumped to first statement following while loop and print the value of factorial.
In do-while loop, the body of loop is executed at least once before the
condition is evaluated. Then the loop repeats body as long as condition is
true. However, in while loop, the statement doesn’t execute the body of the
loop even once, if condition is false. That is why do-while loop is also called
exit-control loop. This is shown in the figure 3.6 given below.
73
An Introduction to C
Example 3.7
Write a program to print first ten even natural numbers.
OUTPUT
2 4 6 8 10 12 14 16 18 20
Example 3.8
Write a program to print first n natural numbers.
75
An Introduction to C /* Program to print first n natural numbers */
#include<stdio.h>
main()
{
int i,n;
printf(“Enter value of n \n”);
scanf(“%d”,&n);
printf(“\nThe first %d natural numbers are :\n”, n);
for(i=1;i<=n;++i)
{
printf(“%d”,i);
}
}
OUTPUT
Enter value of n
6
The first 6 natural numbers are:
123456
The three statements inside the braces of a for loop usually meant for one
activity each, however any of them can be left blank also. More than one
control variables can be initialized but should be separated by comma.
d) for(;;increment/decrement)
body;
Initialization is required to be done before the loop and test condition is
checked inside the loop.
e) for(initialization;;)
body;
Test condition and control variable increment/decrement is to be done
inside the body of the loop.
76
Decision and Loop
(f) for(;condition;) Control Statements
body;
Initialization is required to be done before the loop and control variable
increment/decrement is to be done inside the body of the loop.
g) for(;;;)
body;
Initialization is required to be done before the loop, test condition and
control variable increment/decrement is to be done inside the body of the
loop.
3.3.4 The Nested Loops
C allows loops to be nested, that is, one loop may be inside another. The
program given below illustrates the nesting of loops.
Let us consider a program to illustrate nested loops,
Example 3.9
Write a program to generate the following pattern given below:
1
1 2
1 2 3
1 2 3 4
#include<stdio.h>
main()
{
int i,j;
for(i=1;i<=4;++i)
{
printf("%d\n",i);
for(j=1;j<=i;++j)
printf("%d\t",j);
}
}
Here, an inner for loop is written inside the outer for loop. For every value of
i, j takes the value from 1 to i and then value of i is incremented and next
iteration of outer loop starts ranging j value from 1 to i.
Check Your Progress 2
1. Predict the output :
#include <stdio.h>
main()
{
int i;
for(i=0;i<=10;i++)
printf("%d",i);
return 0;
}
77
An Introduction to C …………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
2. What is the output?
#include<stdio.h>
main()
{
int i;
for(i=0;i<3;i++)
printf("%d ",i);
}
…………………………………………………………………………….
…………………………………………………………………………….
…………………………………………………………………………….
3. What is the output for the following program?
#include<stdio.h>
main()
{
int i=1;
do
{
printf(“%d”,i);
}while(i=i-1);
}
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
4. Give the output of the following:
#include<stdio.h>
main()
{
int i=3;
while(i)
{
int x=100;
printf(“\n%d..%d”,i,x);
x=x+1;
i=i+1;
}
}
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
78
Decision and Loop
3.4 THE goto STATEMENT Control Statements
Here, label is an identifier that is used to label the statement to which control
will be transferred. The targeted statement must be preceded by the unique
label followed by colon.
label: statement;
goto can never be used to jump into the loop from outside and it should be
preferably used for forward jump.
Situations may arise, however, in which the goto statement can be useful. To
the possible extent, the use of the goto statement should generally be avoided.
Example 3.10
Write a program to print first 10 even numbers
#include<stdio.h>
main()
{
int i=2;
while(1)
{
printf(“%d ”,i);
i=i+2;
if(i>=20)
goto outside;
}
outside : printf(“over”);
}
OUTPUT
2 4 6 8 10 12 14 16 18 20 over
79
An Introduction to C
3.5 THE break STATEMENT
Sometimes, it is required to jump out of a loop irrespective of the conditional
test value. Break statement is used inside any loop to allow the control jump
to the immediate statement following the loop. The syntax is as follows:
break;
When nested loops are used, then break jumps the control from the loop
where it has been used. Break statement can be used inside any loop i.e.,
while, do-while, for and also in switch statement.
#include<stdio.h>
main()
{
int div,num,i;
printf(“Enter any number:\n”);
scanf(“%d”,&num);
for(i=2;i<=num;++i)
{
if((num % i) == 0)
{
printf(“Smallest divisor for number %d is %d”,num,i);
break;
}
}
}
OUTPUT
Enter any number:
9
Smallest divisor for number 9 is 3
In the above program, we divide the input number with the integer starting
from 2 onwards, and print the smallest divisor as soon as remainder comes
out to be zero. Since we are only interested in first smallest divisor and not all
divisors of a given number, so jump out of the for loop using break statement
without further going for the next iteration of for loop.
Break is different from exit. Former jumps the control out of the loop while
exit stops the execution of the entire program.
Let us see the program given below to know the working of the continue
statement.
Example 3.12
Write a program to print first 20 natural numbers skipping the numbers
divisible by 5.
#include<stdio.h>
main()
{
int i;
for(i=1;i<=20;++i)
{
if((i % 5) == 0)
continue;
printf(“%d ”,i);
}
}
OUTPUT
1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19
Here, the printf statement is bypassed each time when value stored in i is divisible
by 5.
#include<stdio.h>
main()
{
int i, n = 3;
for(i=3;n<=20;++n)
{
if(n%i == 0)
break;
if(i == n)
printf(“%d\n”,i);
}
}
…………………………………………………………………………………
…………………………………………………………………………………
…………………………………………………………………………………
3.7 SUMMARY
A program is usually not limited to a linear sequence of instructions. During
its process it may require to repeat execution of a part of code more than once
depending upon the requirements or take decisions. For that purpose, C
provides control and looping statements. In this unit, we had seen the
different looping statements provided by C language namely while,
do…while and for.
Using break statement, we can leave a loop even if the condition for its end is
not fulfilled. It can be used to end an infinite loop, or to force it to end before
its natural end. The continue statement causes the program to skip the rest of
the loop in the present iteration as if the end of the statement block would
have reached, causing it to jump to the following iteration.
Using the goto statement, we can make an absolute jump to another point in
the program. You should use this feature carefully since its execution ignores
any type of nesting limitation. The destination point is identified by a label,
82
Decision and Loop
which is then used as argument for the goto instruction. A label is made of a Control Statements
valid identifier followed by a colon (:).
2 hello
2 012
3 1
4 3..100
2..100
1..100
…..
…..
…...
till infinity
2 65
3 3
83
An Introduction to C
UNIT 4 ARRAYS AND STRINGS
Structure
4.0 Introduction
4.1 Objectives
4.2 Array Declaration
4.2.1 Syntax of Array Declaration
4.2.2 Size Specification
4.3 Array Initialization
4.3.1 Initialization of Array Elements in the Declaration
4.3.2 Character Array Initialization
4.4 Subscript
4.5 Processing the Arrays
4.6 Multi-Dimensional Arrays
4.6.1 Multi-Dimensional Array Declaration
4.6.2 Initialization of Two-Dimensional Arrays
4.7 Introduction to Strings
4.8 Declaration and Initialization of Strings
4.9 Display of Strings Using Different Formatting Techniques
4.10 Array of Strings
4.11 String Functions and Applications
4.12 Summary
4.13 Solutions / Answers
4.14 Further Readings
4.0 INTRODUCTION
C language provides four basic data types - int, char, float and double. We
have learnt about them in Unit 2. These basic data types are very useful; but
they can handle only a limited amount of data. As programs become larger and
more complicated, it becomes increasingly difficult to manage the data.
Variable names typically become longer to ensure their uniqueness. And, the
number of variable names makes it difficult for the programmer to concentrate
on the more important task of correct coding. Arrays provide a mechanism for
declaring and accessing several data items with only one identifier, thereby
simplifying the task of data management.
Many programs require the processing of multiple, related data items that have
common characteristics like list of numbers, marks in a course, or enrolment
numbers. This could be done by creating several individual variables. But this
is a hard and tedious process. For example, suppose you want to read in five
numbers and print them out in reverse order. You could do it the hard way as:
84
main n() Arrays and Strings
{
int al,a2,a3,a4,a5
a ;
scannf(“%d %d %d% %d %d”,&a1,&a2,&a3,& &a4,&a5);
printtf(“%d %d %d% %d %d”',a5,a4,a3,a2,a1);
}
Doess it look goood if the probblem is to read in 100 orr more relateed data itemss
and print
p them inn reverse ordder? Of courrse, the soluttion is the usse of the reguular
variaable names a1,
a a2 and so o on. But to remember eeach and every variable aand
perfoorm the operrations on thhe variables is
i not only teedious a job and
disaddvantageouss too. One coommon orgaanizing technnique is to usse arrays in
suchh situations. An
A array is a collectionn of similar kkind of data elements
e stoored
in addjacent memmory locationns and are referred to by a single arraay-name. In the
case of C, you have to declarre and define array befoore it can be used.
Decllaration and definition teell the compiiler the namee of the array, the type oof
eachh element, annd the size orr number off elements. To
T explain it, let us consiider
to store marks off five studennts. They cann be stored using
u five vaariables as
folloows:
int ar1,
a ar2, ar3, ar4, ar5;
Noww, if we wantt to do the saame thing foor 100 studennts in a classs then one wiill
find it difficult too handle 1000 variables. This
T can be obtained by using an arrray.
An array
a declaraation uses itss size in [] brrackets. For above exam
mple, we can
definne an array as:
a
int ar[100];
a
In th
he above figuure, as each integer value occupies 2 bytes, 200 bytes
b were
alloccated in the memory.
m
Thiss unit explainns the use off arrays, typees of arrays, declaration and
initiaalization witth the help of examples ini the first feew sections and
a later on
focuuses on stringg handling inn C program mming languaage.
4.1 OBJECTIVES
S
Afteer going through this unitt you will bee able to:
declare and use arrays of
o one dimennsion;
initialize arrrays; 85
An Introduction to C
use subscripts to access individual array elements;
write programs involving arrays;
do searching and sorting;
handle multi-dimensional arrays;
define, declare and initialize a string;
discuss various formatting techniques to display the strings; and
discuss various built-in string functions and their use in manipulation of
strings.
The declaration of an array is just like any variable declaration with additional
size part, indicating the number of elements of the array. Like other variables,
arrays must be declared at the beginning of a function.
The declaration specifies the base type of the array, its name, and its size or
dimension. In the following section we will see how an array is declared:
data-type array_name[constant-size];
Data-type refers to the type of elements you want to store
Constant-size is the number of elements
Write a program to declare and read values in an array and display them.
# include<stdio.h>
# define SIZE 5 /* SIZE is a symbolic constant */
main()
{
int i=0; /* Loop variable */
int stud_marks[SIZE]; /* array declaration */
OUTPUT:
val 1 is the value for the first array element,val 2 is the value for the second
element,and val n is the value for the n array element. Note that when you are
initializing the values at the time of declaration, then there is no need to specify
the size. Let us see some of the examples given below:
int digits [10]={1,2,3,4,5,6,7,8,9,10};
int digits[]={1,2,3,4,5,6,7,8,9,10};
int vector[5]={12,-2,33,21,13};
float temperature[10]={31.2,22.3,41.4,33.2,23.3,32.3,41.1,10.8,11.3,42.3};
double width[]={17.33333456,-1.212121213,222.191345 };
int height[10]={60,70,68,72,68 };
In the above two statements the assignments are done differently. The first
statement is not a string but simply an array storing three characters ‘T’,‘I’ and
‘N’ and is same as writing:
char thing[3]={‘T’,‘I’,‘N’};
88
Arrays and Strings
whereas,the second one is a four character string TIN\0. The change in the
first assignment, as given below, can make it a string.
char thing [4]=“TIN”;
Subscript is an integer type constant or variable name whose value ranges from
0 to SIZE - 1 where SIZE is the total number of elements in the array. Let us now see
how we can refer to individual elements of an array of size 5:
Here both arrays are of size 5. This is because the country is a char array and
initialized by a string constant “India” and every string constant is terminated
by a null character ‘\0’. And stud is an integer array. country array occupies 5
bytes of memory space whereas stud occupies size of 10 bytes of memory
space. The following table: 4.1 shows how individual array elements of
country and stud arrays can be referred:
Table 4.1: Reference of individual elements
Element Subscript country array stud array
no.
Reference Value Reference Value
1 0 country [0] ‘I’ stud [0] 1
2 1 country [1] ‘n’ stud [1] 2
3 2 country [2] ‘d’ stud [2] 3
4 3 country [3] ‘i’ stud [3] 4
5 4 country [4] ‘a’ stud [4] 5
Example 4.2
Write a program to illustrate how the marks of 10 students are read in an array
and then used to find the maximum marks obtained by a student in the class.
#include< stdio.h>
#define SIZE 10 /* SIZE is a symbolic constant */
main()
{
int i=0;
int max=0;
int stud_marks[SIZE]; /* array declaration */
/* find maximum */
for(i=0;i<SIZE;i ++)
{
if(stud_marks[i]>max)
max= stud_marks[i];
}
printf(“\n\nThe maximum of the marks obtained among all the 10 students is: %d
”,max);
}
OUTPUT
The maximum of the marks obtained among all the 10 students is: 49
Write a program to display the average marks of each student, given the marks
in 2 subjects for 3 students.
for(i=0;i<SIZE;i++)
{
total_marks[i]=stud_marks1[i]+ stud_marks2[i];
avg[i]=total_marks[i]/2;
printf(“Student no.=%d,Average= %f\n”,i+1,avg[i]);
}
}
OUTPUT
Let us now write another program to search an element using the linear search.
Example 4.4
Write a program to search an element in a given list of elements using Linear Search.
/* Linear Search*/
# include<stdio.h>
# define SIZE 05
main()
{
int i =0;
int j;
int num_list[SIZE]; /* array declaration */
OUTPUT
Example 4.5
Write a program to sort a list of elements using the selection sort method
#include <stdio.h>
#define SIZE 5
main()
{
int j,min_pos,tmp;
int i; /* Loop variable */
int a[SIZE]; /* array declaration */
for(i=0;i<SIZE;i++)
{
printf(“Element no.=%d”,i+1);
printf(“Value of the element: “);
scanf(“%d”,&a[i]);
}
for(i=0;i<SIZE;i++)
{
93
An Introduction to C min_pos=i;
for(j=i+1;j<SIZE;j++)
if(a[j] < a[min_pos])
min_pos= j;
tmp=a[i];
a[i]=a[min_pos];
a[min_pos]=tmp;
}
OUTPUT
94 ………………………………………………………………………………
Arrays and Strings
4.6 MULT
TI-DIME
ENSIONA
AL ARR
RAYS
Supppose that youu are writingg a chess-plaaying prograam. A chessbboard is an 8- 8
by-88 grid. What data structure would you use to reprresent it? Yoou could use an
arrayy that has a chessboard-l
c like structuree, i.e. a two-ddimensional array
a , to storre
the positions
p of the
t chess pieeces. Two-diimensional aarrays use tw wo indices too
pinp
point an indivvidual elemeent of the arrray. This is vvery similar to what is
calleed "algebraicc notation", commonly
c u
used in chesss circles to reecord gamess
and chess probleems.
In prrinciple, therre is no limitt to the numbber of subscripts(or dim
mensions) an
arrayy can have. Arrays
A with more than oneo dimensioon are calledd multi-
dimeensional arrayys. While hu umans cannot easily visuualize objectss with more
than three dimennsions, repreesenting multi-dimensionnal arrays prresents no
probblem to compputers. In praactice, howeever, the amoount of mem mory in a
comp
mputer tends to t place limiits on the sizze of an arrayy . A simple four-
dimeensional arraay of double-precision nuumbers, merrely twenty elements
e widde
in eaach dimensioon, takes up 20^4 * 8, orr 1,280,000 bbytes of mem mory - aboutt a
megabyte.
For example,
e 1 elementss.
yoou have ten rows and ten columns, foor a total of 100
It’s really
r no bigg deal. The first
fi number in brackets iis the numbeer of rows, thhe
secoond number in i brackets is the numbeer of columnss. So, the uppper left cornner
of anny grid woulld be elemennt [0][0]. Thee element too its right woould be [0][1],
and so on. Here is a little illuustration to help.
h
Threee-dimensionnal arrays(an nd higher) arre stored in tthe same way as the twoo-
dimeensional onees. They are kept in comp puter memorry as a lineaar sequence oof
variaables, and th
he last index is always thhe one that varies fastest((then the nexxt-
to-laast, and so onn).
In th
he above exaample, variabble_type is thet name of ssome type of variable, suuch
as in
nt. Also, sizee1 and size2 are the sizess of the arrayy’s first and second
dimeensions, resppectively. Heere is an exaample of defi fining an 8-by y-8 array off
integ
gers, similar to a chessbooard. Remem mber, becausse C arrays are a zero-baseed,
95
An Introduction to C
the indices on each side of the chessboard array run 0 through 7, rather than 1
through 8. The effect is the same: a two-dimensional array of 64 elements.
int chessboard [8][8];
The neutral order in which the initial values are assigned can be altered by
including the groups in {} inside main enclosing brackets, like the following
initialization as above:
int table [2][3]={{1,2,3},{4,5,6} };
The value within innermost braces will be assigned to those array elements
whose last subscript changes most rapidly. If there are few remaining values
in the row, they will be assigned zeros. The number of values cannot exceed
the defined row size.
int table [2] [3]={{1, 2, 3},{4}};
table[0][0]=1;
table[0][1]=2;
table[0][2]=3;
table[1][0]=4;
table[1][1]=0;
table[1][2]=0;
96
Arrays and Strings
Check Your Progress 3
1. Declare a multi-dimensioned array of floats called balances having three
rows and five columns.
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
2. Write a for loop to total the contents of the multi-dimensioned float array
balances.
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
3. Write a for loop which will read five characters(use scanf) and deposit
them into the character based array words, beginning at element 0.
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
For example,
char name[20];
char address[25];
char city[15];
Initialization of Strings
The string can be initialized as follows:
char name[8]={‘P’,‘R’,‘O’,‘G’,‘R’,‘A’,‘M’,‘\0’};
Each character of string occupies 1 byte of memory (on 16 bit computing). The
size of character is machine dependent, and varies from 16 bit computers to 64
bit computers. The characters of strings are stored in the contiguous (adjacent)
memory locations.
The C compiler inserts the NULL (\0) character automatically at the end of the
string. So initialization of the NULL character is not essential.
You can set the initial value of a character array when you declare it by
specifying a string literal. If the array is too small for the literal, the literal will
be truncated. If the literal (including its null terminator) is smaller than the
array, then the final characters in the array will be undefined. If you don’t
specify the size of the array, but do specify a literal, then C will set the array to
the size of the literal, including the null terminator.
98
char str[4]={‘u’, ‘n’, ‘i’, ‘x’}; Arrays and Strings
char str[5]={‘u’, ‘n’, ‘i’, ‘x’, ‘\0’};
char str[3];
char str[]=“UNIX”;
char str[4]=“unix”;
char str[9]=“unix”;
All of the above declarations are legal. But which ones don’t work? The first
one is a valid declaration, but will cause major problems because it is not null-
terminated. The second example shows a correct null-terminated string. The
special escape character \0 denotes string termination. The fifth example
suffers the size problem, the character array ‘str’ is of size 4 bytes, but it
requires an additional space to store ‘\0’. The fourth example however does
not. This is because the compiler will determine the length of the string and
automatically initialize the last character to a null-terminator. The strings not
terminated by a ‘\0’ are merely a collection of characters and are called as
character arrays.
String Constants
String constants have double quote marks around them, and can be assigned to
char pointers. Alternatively, you can assign a string constant to a char array -
either with no size specified, or you can specify a size, but don’t forget to leave
a space for the null character! Suppose you create the following two code
fragments and run them:
/* Fragment 1 */
{
char *s;
s=hello”;
printf(“%s\n”,s);
}
/* Fragment 2 */
{
char s[100];
strcpy(s,“ hello”);
printf(“%s\n”,s);
}
These two fragments produce the same output, but their internal behaviour is
quite different. In fragment 2, you cannot say s="hello";. To understand the
differences, you have to understand how the string constant table works in C.
When your program is compiled, the compiler forms the object code file,
which contains your machine code and a table of all the string constants
declared in the program. In fragment 1, the statement s="hello"; causes s to
point to the address of the string hello in the string constant table. Since this
string is in the string constant table, and therefore technically a part of the
executable code, you cannot modify it. You can only point to it and use it in a
read-only manner. In fragment 2, the string hello also exists in the constant
table, so you can copy it into the array of characters named s. Since s is not an
address, the statement s="hello"; will not work in fragment 2. It will not even
compile.
99
An Introduction to C Example 4.6
Write a program to read a name from the keyboard and display message Hello onto
the monitor”.
/*Program that reads the name and display the hello along with your name*/
#include <stdio.h>
main()
{
char name[10];
printf(“\nEnter Your Name :);
scanf(“%s”, name);
printf(“Hello %s\n”,name);
}
OUTPUT
In the above example declaration char name [10] allocates 10 bytes of memory
space(on 16 bit computing) to array name []. We are passing the base address
to scanf function and scanf() function fills the characters typed at the keyboard
into array until enter is pressed. The scanf() places ‘\0’ into array at the end of
the input. The printf() function prints the characters from the array on to
monitor, leaving the end of the string ‘\0’. The %s used in the scanf() and
printf() functions is a format specification for strings.
We can also specify the accuracy with which character array (string) is
displayed. For example, if you want to display first 5 characters from a field
width of 15 characters, you have to write as:
printf(“%15.5s”, name);
If you include minus sign in the format (e.g. % –10.5s), the string will be
printed left justified.
printf(“% -10.5s”, name);
Example 4.7
Write a program to display the string “UNIX” in the following format.
U
UN
UNI
UNIX
UNIX
UNI
100
UN Arrays and Strings
U
/* Program to display the string in the above shown format*/
# include<stdio.h>
main()
{
int x, y;
static char string[]=“UNIX”;
printf(“\n”);
for( x=0; x<4; x++)
{
y=x + 1;
/* reserves 4 character of space on to the monitor and minus sign is for left
justified*/
printf(“%-4.*s \n”, y, string);
U
UN
UNI
UNIX
UNIX
UNI
UN
U
0 1 2 3 4 5 6 7 8 9
m a r t i n \0
p h i l \0
c o l l i n s \0
Example 4.9
#include <stdio.h>
main()
{
int n;
char names[3][10]={“Alex”, “Phillip”, “Collins” };
for(n=0; n<3; n++)
printf(“%s \n”,names[n] ); }
OUTPUT
Alex
Phillip
Collins
Check Your Progress 4
1. Which of the following is a static string?
A. Static String;
B. “Static String”;
C. ‘Static String’;
D. char string[100];
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
2. Which character ends all strings?
A. ‘.’
B. ‘ ‘
C. ‘0’
D. ‘n’
………………………………………………………………………………
………………………………………………………………………………
102 ………………………………………………………………………………
Arrays and Strings
3. What is the Output of the following programs?
(a) main()
{
char name[10]=“IGNOU”;
printf(“\n %c”, name[0]);
printf(“\n %s”, name);
}
(b) main()
{
char s[]=“hello”;
int j=0;
while( s[j] !=‘\0’ )
printf(“ %c”,s[j++]);
}
(c) main()
{
char str[]=“hello”;
printf(“%10.2s”, str);
printf(“%-10.2s”, str);
}
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
4 Write a program to read 'n' number of lines from the keyboard using a
two-dimensional character array (ie., strings).
………………………………………………………………………………
………………………………………………………………………………
………………………………………………………………………………
The header file <string.h> contains some string manipulation functions. The
following is a list of the common string managing functions in C.
where str is name of the string and n is the length of the string, returned by
strlen function.
Example 4.10
Write a program to read a string from the keyboard and to display the length of
the string on to the monitor by using strlen( ) function.
103
An Introduction to C /* Program to illustrate the strlen function to determine the length of a string */
#include <stdio.h>
#include <string.h>
main()
{
char name[80];
int length;
printf(“Enter your name: ”);
gets(name);
length=strlen(name);
printf(“Your name has %d characters\n”, length);
}
OUTPUT
Example 4.11
Write a program to read a string from the keyboard and copy the string onto
the second string and display the strings on to the monitor by using strcpy( )
function.
/* Program to illustrate strcpy function*/
#include <stdio.h>
#include <string.h>
main()
{
char first[80], second[80];
printf(“Enter a string: ”);
gets(first);
strcpy(second, first);
printf(“\n First string is : %s, and second string is: %s\n”, first, second);
}
OUTPUT
104
Arrays and Strings
4.11.3 Strcmp Function
The strcmp function in the string library function which compares two strings,
character by character and stops comparison when there is a difference in the
ASCII value or the end of any one string and returns ASCII difference of the
characters that is integer. If the return value zero means the two strings are
equal, a negative value means that first is less than second, and a positive value
means first is greater than second. The syntax is as follows:
n=strcmp(str1, str2);
where str1 and str2 are two strings to be compared and n is returned value of
differed characters.
Example 4.12
/* The following program uses the strcmp function to compare two strings. */
#include <stdio.h>
#include <string.h>
main()
{
char first[80], second[80];
int value;
printf(“Enter a string: ”);
gets(first);
printf(“Enter another string: ”);
gets(second);
value=strcmp(first,second);
if(value ==0)
puts(“The two strings are equal”);
else if(value < 0)
puts(“The first string is smaller ”);
else if(value > 0)
puts(“the first string is bigger”);
}
OUTPUT
where str1 and str2 are two string arguments, string str2 is appended to string
str1.
105
An Introduction to C Example 14.13
Write a program to read two strings and append the second string to the first
string.
#include <stdio.h>
#include <string.h>
main()
{
char first[80], second[80];
printf(“Enter a string:”);
gets(first);
printf(“Enter another string: ”);
gets(second);
strcat(first, second);
printf(“\nThe two strings joined together: %s\n”, first);
}
OUTPUT
Example 4.14
Write a program to convert the string into lower case characters using in-built
function.
/* Program that converts input string to lower case characters */
#include <stdio.h>
#include <string.h>
main()
{
char first[80];
printf("Enter a string: ");
gets(first);
printf("Lower case of the string is %s”, strlwr(first));
}
OUTPUT
Example 4.15
Write a program to reverse a given string.
/* Program to reverse a given string */
#include <stdio.h>
#include <string.h>
main()
{
char first[80];
printf(“Enter a string:”);
gets(first);
printf(“\n Reverse of the given string is : %s ”, strrev(first));
}
OUTPUT
where first and second are two strings to be compared, n is the number of
character from which first string does not match with second string.
Example 4.16
Write a program, which returns the position of the string from where first
string does not match with second string.
/*Program which returns the position of the string from where first string does
not match with second string*/
#include <stdio.h>
#include <string.h>
main()
{
char first[80], second[80];
printf("Enter first string: “);
gets(first);
printf(“\n Enter second string: “);
gets(second);
printf(“\n After %d characters there is no match”,strspn(first, second));
}
OUTPUT
stricmp function
The stricmp function is same as strcmp, except it compares two strings
ignoring the case(lower and upper case). The syntax is as follows:
n=stricmp(str1, str2);
strncmp function
The strncmp function is same as strcmp, except it compares two strings up to
a specified length. The syntax is as follows:
n=strncmp(str1, str2, 10);
where 10 characters of str1 and str2 are compared and n is returned value of
differed characters.
strchr function
The strchr funtion takes two arguments(the string and the character whose
address is to be specified) and returns the address of first occurrence of the
character in the given string. The syntax is as follows:
cp=strchr(str, c);
where str is string and c is character and cp is character pointer.
strset function
The strset funtion replaces the string with the given character. It takes two
arguments the string and the character. The syntax is as follows:
strset(first, ch);
where string first will be replaced by character ch.
strchr function
The strchr function takes two arguments(the string and the character whose
address is to be specified) and returns the address of first occurrence of the
character in the given string. The syntax is as follows:
cp=strchr(str, c);
where str is string and c is character and cp is character pointer.
strncat function
The strncat function is the same as strcat, except that it appends upto specified
length. The syntax is as follows:
108
Arrays and Strings
strncat(str1, str2,10);
where 10 character of the str2 string is added into str1 string.
strupr function
The strupr function converts lower case characters of the string to upper case
characters. The syntax is as follows:
strupr(str1);
where str1 is string to be converted into upper case characters.
strstr function
The strstr function takes two arguments address of the string and second
string as inputs. And returns the address from where the second string starts in
the first string. The syntax is as follows:
cp=strstr(first, second);
where first and second are two strings, cp is character pointer.
4.12 SUMMARY
Like other languages, C uses arrays as a way of describing a collection of
variables with identical properties. The group has a single name for all its
members, with the individual member being selected by an index. We have
learnt in this unit, the basic purpose of using an array in the program,
declaration of array and assigning values to the arrays and also the string
handling functions. All elements of the arrays are stored in the consecutive
memory locations. Without exception, all arrays in C are indexed from 0 up to
one less than the bound given in the declaration. This is very puzzling for a
beginner. Watch out for it in the examples provided in this unit. One important
point about array declarations is that they don't permit the use of varying
subscripts. The numbers given must be constant expressions which can be
evaluated at compile time, not run time. As with other variables, global and
static array elements are initialized to 0 by default, and automatic array
elements are filled with garbage values. In C, an array of type char is used to
represent a character string, the end of which is marked by a byte set to 0(also
known as a NULL character).
Whenever the arrays are passed to function their starting address is used to
access rest of the elements. This is called – Call by reference. Whatever
changes are made to the elements of an array in the function, they are also
made available in the calling part. The formal argument contains no size
specification except for the rightmost dimension. Arrays and pointers are
closely linked in C. Multi-dimensional arrays are simply arrays of arrays. To
use arrays effectively it is a good idea to know how to use pointers with them.
More about the pointers can be learnt from Unit -7 (Block -2).
Strings are sequence of characters. Strings are to be null-terminated if you
want to use them properly. Remember to take into account null-terminators
when using dynamic memory allocation. The string.h library has many useful
functions. Losing the ‘ \0’ character can lead to some very considerable bugs.
Make sure you copy \0 when you copy strings. If you create a new string, make
sure you put \0 in it. And if you copy one string to another, make sure the
receiving string is big enough to hold the source string, including \0. Finally, if
you point a character pointer to some characters, make sure they end with \0.
110
Arrays and Strings
String Functions Its Use
strlen Returns number of characters in string.
strlwr Converts all the characters in the string into lower case
strcat characters
strcpy Adds one string at the end of another string
strcmp Copies a string into another
strdup Compares two strings and returns zero if both are equal.
strchr Duplicates a string
strstr Finds the first occurrence of given character in a string
strset Finds the first occurrence of given string in another string
strrev Sets all the characters of string to given character or symbol
Reverse a string
1. B
2. C
3. (a) I
IGNOU
(b) hello
(c) hehe
1. D
2. C
3. /*Program to concatenate two strings without using the strcat() function*/
#include<stdio.h>
#include<string.h>
main()
{
char str1[10];
char str2[10];
char output_str[20];
int i,j,k;
i=0;
j=0;
k=0;
printf("Input the first string: ");
gets(str1);
112
printf("\nInput the second string: "); Arrays and Strings
gets(str2);
while(str1[i]!='\0'
output_str[k++]=str1[i++];
while(str2[j]!='\0')
output_str[k++]=str2[j++];
output_str[k]='\0';
puts(output_str);
}
4. /* Program to find the string length without using the strlen() funtion */
#include<stdio.h>
#include<string.h>
main()
{
char string[60];
int len,i;
len=0;
i=0;
printf("Input the string : ");
gets(string);
while(string[i++]!='\0')
len++;
printf("Length of Input String=%d",len);
getchar();
}
5. /* Program to convert the lower case letters to upper case in a given string
without using strupp() function*/
#include<stdio.h>
main()
{
int i=0;
char source[10],destination[10];
printf(“Input the string in lower-case”);
gets(source);
while(source[i]!=‘\0’)
{
if((source[i]>=97)&&(source[i]<=122))
destination[i]=source[i]-32;
else
destination[i]=source[i];
i++;
}
destination[i]=‘ \0 ’;
puts(destination);
}
114