sanet.st_Concepts_and_Techniques_of_Programming_in_C
sanet.st_Concepts_and_Techniques_of_Programming_in_C
Programming in C
Concepts and Techniques of
Programming in C
Manoranjan Pradhan
Professor and HOD
Department of Computer Science and Engineering
Gandhi Institute for Technological Advancement
Bhubaneswar, Odisha
©Copyright 2020 I.K. International Pvt. Ltd., New Delhi-110002.
This book may not be duplicated in any way without the express written consent of the publisher,
except in the form of brief excerpts or quotations for the purposes of review. The information
contained herein is for the personal use of the reader and may not be incorporated in any commercial
programs, other books, databases, or any kind of software without written consent of the publisher.
Making copies of this book or any portion for any purpose other than your own is a violation of
copyright laws.
Limits of Liability/disclaimer of Warranty: The author and publisher have used their best efforts in
preparing this book. The author make no representation or warranties with respect to the accuracy or
completeness of the contents of this book, and specifically disclaim any implied warranties of
merchantability or fitness of any particular purpose. There are no warranties which extend beyond the
descriptions contained in this paragraph. No warranty may be created or extended by sales
representatives or written sales materials. The accuracy and completeness of the information provided
herein and the opinions stated herein are not guaranteed or warranted to produce any particulars
results, and the advice and strategies contained herein may not be suitable for every individual.
Neither Dreamtech Press nor author shall be liable for any loss of profit or any other commercial
damages, including but not limited to special, incidental, consequential, or other damages.
Trademarks: All brand names and product names used in this book are trademarks, registered
trademarks, or trade names of their respective holders. Dreamtech Press is not associated with any
product or vendor mentioned in this book.
ISBN: 978-93-89633-08-5
EISBN: 978-93-89976-52-6
Edition: 2020
Dedicated to
My Father
Digambar Sethi
&
Mother
Kanchan Bala Sethi
Preface
The C programming language is one of the most widely offered courses at many
institutions and universities in the undergraduate programmes (all branches of BTech,
BSc Computer Science, and BCA) as well as various postgraduate programmes (MCA,
MSc Computer Science and others). Apart from students, the book will also be useful
to aspirants of various competitive examinations and budding programmers at work.
The book is straightforward and simple in its approach, deals with fundamentals of
computer, algorithms and flowcharts, error handling, different data types, variables,
operators, input/output operations, decision statements, looping, unconditional
statements, functions, arrays, strings, pointers, dynamic memory management,
structure and union, file and file handling, and preprocessor directives.
Chapter 1 deals with the fundamentals of computer which include the basic block
diagram of a computer, RAM, ROM, input devices, output devices, number systems,
problem solving, etc.
Chapter 2 discusses the algorithm and flowchart.
Chapter 3 presents C programming with introduction, general terminology, different
types of error in C programming.
Chapter 4 deals with different types of data types, variables, rules of naming a
variable, and different types of constant, token, keyword, identifier and others.
Chapter 5 focuses on different types of operator, e.g., arithmetic operator, logical
operator, conditional, increment/decrement operator, relational, logical, bitwise
operator and others.
Chapter 6 deals with input/output operations in C programming and includes
introduction, reading a single character, writing a single character, escape sequences,
delimiters, formatted input and output.
Chapter 7 discusses decision making statements, e.g., if statement, if else statement,
nested if-else statement and switch statement.
Chapter 8 discusses and presents different types of looping in C programming, e.g.,
while loop, do while loop, for loops with their programming examples.
viii Preface
Chapter 9 presents unconditional statements, e.g., breaks, goto, continue and exit
statements.
Chapter 10 focuses on the functions, i.e., library functions and user defined functions,
different types of function, formal parameter, actual parameter, recursion, storage
classes, etc.
Chapter 11 discusses arrays with program and theories of one-dimensional array,
two-dimensional arrays and three-dimensional arrays.
Chapter 12 deals with string which hold different function getchar(), gets(), putchar(),
puts(), strlen(), strcpy(), strcmp(), strcat(), strrev().
Chapter 13 deals with pointer, declaration, null pointer, generic pointer, pointer to
pointer, pointer to array, array of pointer and dynamic memory management.
Chapter 14 discusses the structure, union, type definition, bit filed and others.
Chapter 15 discusses the file, text file vs binary files, file I/O function, file opening
mode, error happed during I/O operation and others.
Chapter 16 deals with the preprocessor directives.
Preface vii
Acknowledgements ix
1. Computer Fundamentals........................................................................................ 1
1.1 Introduction 1
1.2 Block Diagram of a Computer 1
1.3 Bits and Bytes 5
1.4 Memory 6
1.5 Number System Representation 8
1.6 Problem Solving 11
3. C Programming...................................................................................................... 32
3.1 Introduction 32
3.2 General Terms a Programmer Should Know Before Writing any Program 33
3.3 Types of Errors in C Programming 36
3.4 Logical Steps for Writing a Program 37
3.5 How to Write a Simple C Program 37
3.6 Different Ways to Write the Main () Function 40
3.7 Basic Structure of C Program 42
3.8 Steps of Writing a C Program Using Editor 44
3.9 Diagrammatic Representation of Internal Structure of C Program Execution 45
3.10 Common Mistakes the Beginner Does and Its Correction 47
3.11 Useful C Programing Examples Without Using Control Statement 48
xii Contents
5. C Operator............................................................................................................... 77
5.1 Introduction 77
5.2 Types of Operator 77
5.3 Type Conversion/Type Casting 95
5.4 Precedence and Order of Evaluations 98
8. Looping.................................................................................................................. 160
8.1 Introduction 160
8.2 Concept of Looping 160
Contents xiii
Appendix.................................................................................................................... 395
Bibliography.............................................................................................................. 397
Index............................................................................................................................ 399
1
Computer
Fundamentals
1.1 INTRODUCTION
A computer is an electronic device or machine (consisting of monitor, central processing
unit, keyboard, mouse, printer and modem) which can accept data as input and
processes it to give expected output and store in a secondary storage unit permanently.
Processing of input data into output is done by software applied on hardware. The
computer has three main parts or components, e.g., hardware, software and people.
The computer system which consists of different equipment or parts is called hardware,
for example, keyboard, mouse, monitor, hard disk, mother board and disk drives. The
computer program which tells the hardware what to do is called software. The software
is again divided into two types, e.g., system software and application software. The
system software is a computer program designed to run computer hardware and
application programs. It is the interface between the hardware and user applications.
Examples of system software are operating system, BIOS (Basic Input Output System),
assembler, compiler, device, driver, etc. Application software is a computer program
designed for end users, for example, Microsoft Office, Excel, Google Chrome, Mozilla
Firefox, Skype and others. People are an important part of computer system who can
use the computer for their requirements.
OCR (Optical Character Recognizer), OMR (Optical Mark Reader), MICR (Magnetic
Ink Character Recognizer), BIOMETRIC sensors, Web Camera, Smart Card Reader,
Graphics Tablets, Touch Screen, Joystick, Scanner, Pen Drive. Some of are explained
below.
(a) Keyboard
The keyboard is the set of keys and it is one of the primary input devices used by
computers. The keyboard design is same as typewriter keyboard which arranges letters
and numbers in such way that it is prevents type bar from getting jammed when typing
quickly.
(c) Scanner
A scanner is a device used for capturing the images from photographic prints, magazine
pages, answer sheet of exams and other sources for computer editing and display. The
scanner comes in hand-held, feed-in types and for scanning color or black and white.
High resolution scanners give high quality output.
(d) Mouse
It is an input device used to control the movement of insertion point on the computer
screen.
(a) Monitor
It is an electronic device used for displaying picture on computer screen.
(b) Printer
Printer is a device which accepts instructions from computer in the form of text and
graphics and transfers the information on paper. Printers vary in speed, size and cost.
Computer Fundamentals 5
1.4 MEMORY
The computer memory is like a human brain. Its work is to store the data and instructions.
It is the storage space in a computer where data is processed and instructions required
for processing are stored. The memory unit consists of a large number of small memory
units called memory cells. Each cell or location has specific address which varies from
0 to memory size minus one. If the computer has 64k words, then the memory unit
has 64*1024=65536 memory cells. The address of memory cells varies from 0 to 65535.
There are three types of memory:
1. Primary memory/main memory
2. Cache memory
3. Secondary memory
EXPLANATION:
1.4.1 Primary Memory/Main Memory
The primary memory holds the instructions and data on the computer when it is
working. It has limited capability to hold the data and when power is switched off all
the data is lost. The primary memory is made of semiconductor device. The primary
memory is again divided into two types, i.e., RAM, and ROM.
1.4.3.3 CD
Fig. 1.12 Block diagram of
CD (compact disk) is a flat, round, small, portable, a computer floppy
round medium made of molded polymer for electronic disk
recording, storing and playing audio, video, text and
other information in digital form.
8 Concepts and Techniques of Programming in C
1.4.3.4 CD-ROM
CD-ROM stands for compact disk-read only memory is an optical disk which contains
audio or software data whose memory is read only.
Again to represent the number 201 in base 10 we know that the position of 1 is 1’s
column, the position 0 is 10’s column and position of 2 is 100’s column. The tabular
form of 201 whose base is 10 is given below.
28 27 26 25 24 23 22 21 20
256 128 64 32 16 8 4 2 1
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
1 1 0 0 1 0 0 1
88 87 86 85 84 83 82 81 80
16M 2M 262k 32k 4k 512 64 8 1
Suppose the octal number 1238 and convert into decimal form.
1238=1*82+2*81+3*80=64+16+3=8310
We know that one octal digit or number is equivalent to 3 binary digits.
0 0 000
1 1 001
2 2 010
3 3 011
4 4 100
5 5 101
6 6 110
7 7 111
10 Concepts and Techniques of Programming in C
Suppose the octal number is again 1238 and then convert into binary form. Since
each octal number consists of 3 bits. Then from right side of number choose the 3-bit
form from the above table.
1238=(001 010 111)2
0 0 0000
1 1 0001
2 2 0010
3 3 0011
4 4 0100
5 5 0101
6 6 0110
7 7 0111
8 8 1000
9 9 1001
10 A 1010
11 B 1011
12 C 1100
13 D 1101
14 E 1110
15 F 1111
Suppose the hexadecimal number is 1D216 its is converted into binary numbers as:
1D216= (0001 1101 0010)2
The binary form of each hexadecimal digit consists of 4 bits.
Computer Fundamentals 11
EXPLANATION:
1. Understanding the Problem
If a person does not understand the problem then he cannot solve it. And it is true
that if the person understands the problem definitely he can solve it. To understand
the problem one can extract the important features or part or points of the problem.
SUMMARY
SHORT QUESTIONS
1. What is computer?
2. What is hardware?
3. What is software?
4. What is the difference between system software and application software?
5. What is input device and give its example?
6. What is output device and give its example?
7. What is memory?
8. Differentiate between RAM and ROM?
9. What are ALU and CU?
10. What is cache memory?
LONG QUESTIONS
1. Draw a basic computer block diagram and explain its functional parts.
2. What is memory and explain different types of memory?
3. What is secondary memory and explain different types of secondary memory?
MULTIPLE-CHOICE QUESTIONS
2.1 INTRODUCTION
The word algorithm derives from the phonetic pronunciation of Arabic mathematician
Abu Jafar Mohammad ibn Musa al-Khowarizmi who invented a set of rules for doing
the arithmetic operations, e.g., addition, subtraction, division and multiplication on
decimal number systems. Thus, an algorithm is the formula or step-by-step methods
for solving a particular problem. Algorithms are used for the logical analysis of the
program.
1. Finiteness
It means the algorithm should stop in a finite number of steps.
2. Definiteness
Definiteness means each step of the algorithm should be clearly defined.
3. Input
The input of the algorithm is given by the user.
4. Output
The algorithm should have the correct output.
5. Effectiveness
Effectiveness means the algorithm to be developed using basic operations and it
should be complete in a finite amount of time by a person by drawing the paper and
pencil.
3. It gives step-wise procedure to refine the problem and get the solution. This
process is called iterative refinement.
12. Write the Algorithm to Convert Days to Months and Days. (Sequential)
Step 1: Start
Step 2: Declare the variable days and months
Step 3: Enter days as input
Step 4: months=days/30
days= days %30
Step 5. Print months, days
Step 6: Stop
13. Write an Algorithm to Find the Sum of the Digits of a Given Positive Integer
Number. (Iteration/Looping)
Step 1: Start
Step 2: input the integer number n
Step 3: sum=0
Step 4: while(n!=0)
Step 5: {
Step 6: reminder=n%10;
Step 7: sum=sum+reminder;
Step 8: n=n/10;
Step 9 :}
Step 10: Print sum
Step 11: Stop
14. Algorithm to Calculate the Factorial of a Number. (Iteration/Looping)
Step 1. Start
Step 2. Initialize the variable I=1, fact=1
Step 3. Read the integer number x
Step 4. Repeat step 4 through 6 until i<=x
Step 5. fact=fact*i
Step 6. i=i+1
Step 7. Print the value of fact
Step 8. Stop
2.2 FLOWCHART
A flowchart is a diagrammatic/graphical representation of algorithm and it describes
the flow of the solution process. The solution process works by breaking up the problem
into smaller steps or sub/smaller problems and binds them to describe the flow. So
the last step of a flowchart gives the solution. Each step of the solution process is
represented by different symbols and contains the description of the processing steps.
The flowchart symbols are connected with arrow symbols displaying the process flow
direction. A flowchart shows the flow of data in a process and its operations in details
by a pictorial format. A flowchart can be called to drawing the blueprint of the building.
Flowcharts are used in designing, analyzing, documenting a process or the program
in various field.
1. Terminator
DESCRIPTION
The terminator symbol is visualized as oval symbol and it is used to start/begin
and stop/end of the flowchart.
2. Process
DESCRIPTION
The process symbol is visualized as rectangle to represent any single operation
in an algorithm. Generally, this operation is either a calculation or an assignment
statement. In calculation phase one or more inputs are converted into a result by
using either arithmetic or logical operations.
3. Input/output
DESCRIPTION
The input/output symbol is visualized as a parallelogram with text inside
indicating the type of input or output operation.
4. Decision
DESCRIPTION
The decision symbol is visualized as a diamond with text inside indicating the
condition to be evaluated.
Algorithm and Flowchart 21
5. Connector
DESCRIPTION
The connector symbol is visualized as a circle and it is used to connect to flow
line symbols on a logical path.
6. (Arrow/flow lines)
DESCRIPTION
The flow line symbol is visualized as a unidirectional arrow connecting to
flowchart items. Flow line symbol connects the various steps of the logical
process. A flowline symbol should be thought of a logical path between the steps
of a logical process.
Start
Input
Radius R
Area=3.14*R*R
Circum=2*3.14*R
Print Area,
Circumference
Stop
2. Draw the Flowchart for Finding the Average of Three Numbers. (Sequential
Flowchart)
Start
Input
X, Y, Z
SUM=X+Y+Z
AVG=SUM/3
Display
AVG
Stop
3. Find the Greatest Number between Two Integer Numbers (Selection Flowchart)
Start
Input X, Y
X>Y
Print X Print Y
Stop
Fig. 2.3 Flowchart for finding the greatest number between two integer numbers
Algorithm and Flowchart 23
Start
Input X, Y, Z
False Yes
Stop
Start
Input
A, B, C
D = sqrt (B*B-4*A*C)
X1 = (-B+D)/(2*A)
X2 = (-B–D)/(2*A)
Display
X1, X2
Stop
6. Draw a Flowchart to Print the Sum of the Digits of a Given Number. (Iteration/
Looping Flowchart)
Start
Sum=0
Input N
False
N!=0?
True
Remainder=N%10
Sum=Sum+Remainder
N=N/10
Display
sum
Stop
Fig. 2.6 Flowchart for finding the sum of digits of an integer number
Algorithm and Flowchart 25
Start
Input
num
I=1
Fact=1
Is False
I<=Num
?
True
I=I+1
Fact=Fact*I
Print
fact
Stop
Start
Declare num
Input
num
Is False
nium%2==
0?
True Print
odd
Print
even
Stop
9. Draw the Flowchart for Checking the Number is Armstrong Number or Not.
(Iteration Flowchart)
Start
Read num,
sum=0
X=num
Is False
num>=1?
True
R=X%10
Sum=Sum+(R*R*R*)
Num=Num/10
True Is False
X==Sum
Display Display
num is num is not
armstrong armstrong
Stop
Start
Input Fahrenheit
Celsius=5.0/9.0(Fahrenhit-32.0)
Display Celsius
Stop
Start
Input Celsius
Fahrenheit=
(Celsius*9.0/5.0)+32.0
Display
Fahrenheit
Stop
12. Draw The Flowchart of Exchange Two Integer Numbers using Third Variable.
(Sequential Flowchart)
Start
Input X, Y
X=X
X=Y
Y=Z
Display X, Y
Stop
Fig. 2.12 Flowchart for swapping two integer numbers using third variables
13. Draw Flowchart of Exchange Two Integer Numbers without using Third
Variable. (Sequential Flowchart)
Start
Input X, Y
X=X+Y
X=Y–Y
Y=Z–Y
Display X, Y
Stop
Fig. 2.13 Flowchart for swapping two integer numbers without the third variable
30 Concepts and Techniques of Programming in C
Summary
Short Questions
1. What is algorithm?
2. Why is algorithm required?
3. What are the advantages and disadvantages of algorithm?
4. What is flowchart?
5. What are the advantages and disadvantages of flowchart?
Long Questions
1. Write the algorithm and flowchart of converting decimal to binary number using
looping.
2. Write the algorithm and flowchart of multiplication of digits of an integer number.
3. Write the algorithm and flowchart of factorial of a number using recursion.
4. Write the algorithm and flowchart of Fibonacci series.
5. Write the algorithm and flowchart of checking palindrome.
6. Write the algorithm and flowchart of finding the roots of a quadratic equation
using if else statements.
7. Write the algorithm and flowchart of a leap year.
8. Write the algorithm and flowchart to find the prime numbers between the input
m and n.
9. Write the algorithm and flowchart of GCD of two integer numbers using recursion.
Multiple-Choice Questions
2. The rectangle with the horizontal lines on two side’s symbol in a flowchart is
used for ________
(a) Defined statements (b) Predefined process
(c) Error fix (d) Variable defined
[Answer: b]
3. The connectors or link with another part of the program in a flowchart is
represented as_____________
(a) Rhombus (b) Parallelogram
(c) Circle (d) Trapezoid
[Answer: c]
4. The part of algorithm which is repeated for a fixed number of times is called
______________________
(a) Iteration (b) Selection
(c) Reverse action (d) None of the above
[Answer: a]
3
C Programming
3.1 Introduction
C program is a structured, high level and machine independent language. The structured
oriented programming means it divide a larger problem in top down manner as
smaller modules which are called functions or procedures and each of the function
does its own calculation. The structured programming uses three control statements
sequence, selection and iteration or looping. It restricts the use of GOTO statement.
High level language means it is a language which is written in English language.
Machine independent language means the language which can run in any platform
(operating system) with small modification or no modification.
C programming language was developed from the disadvantages of ALGOL, BCPL
and B programming language. It was developed by Dennis Ritchie at Bell Laboratories
in 1972. The C programming language uses the concepts of data types and many
additional features. Preliminarily C programming language was associated with UNIX
operating systems. Because UNIX operating system was developed by using the C
programming. The ALGOL was the first computer programming language introduced
in 1960. Then BCPL (Basic Combined Programming Language) was written by Martin
Richards in 1967. In 1970 B programming language was developed by Ken Thompson
which was the improved version of BCPL. Then C programming language came
in 1978 by Brian Kerningham and Dennis Ritchie. Then ANSI C came in 1989 by
American National Standard Institute (ANSI). In 1990, C++ programming language
came based on C programming with a number of changes called a true object-oriented
programming. The applications of C programming languages are development of
Operating Systems, Compilers, Assemblers, Text Editors, Print Spoolers, Network
Drivers, Modern Programs, Databases, Interpreters, etc.
C Programming 33
C programming
language
3.2.2 Program
Program is the set of instructions.
3.2.3 Software
Software is the set of programs.
3.2.6 Compiler
A compiler is a system software which is used to translate the entire program written
in high level language into machine language. The basic work of a compiler is detecting
the syntax errors in the entire program if any; otherwise it translates into object file.
When compiling the entire program its runtime increases and occupies large amount
of memory space and its execution speed becomes slow. Because the compiler compiles
the entire program at a time and converts it into the machine code only once. If a
compiler runs on a computer and produces the machine code for the same computer
then it is called a self compiler. If a compiler runs on a computer and produces the
machine code for some other computer then that compiler is called a cross compiler.
3.2.7 Interpreter
The interpreter is the system software which is used to execute the entire programming
statements by interpreting line by line. The interpreter does not check the error in the
entire program once at a time but it would interpret line by line multiple times. We can
again say that it reads one statement at a time and translates it into machine code and
executes it. Then it reads next statement of the program and translates it to machine
code and executes until it reaches the end of the program.
C Programming 35
3.2.8 Assembler
Assembler is a system software which is used to translate assembly level language
into machine level language. The assembler is classified into two types, i.e., one pass
assembler and two pass assemblers. In one pass assembler memory address is assigned
to the variables and it translates the source code to the machine code in the first pass
simultaneously. But in two-pass assembler which reads the source code two times,
i.e., in the first pass, it reads all the variables and creates the memory location. In the
second pass, it reads the source code and translates the source code into object code.
3.2.9 Linker
Linker is the last step of the compilation process. It links the object file with library
function to create .exe file. The library file is the predefined functions which are
essential for executing the program. If the linker does not find the library functions used
in the source program then it informs the compiler and generates an error. Example of
linking error is variable or function is used, but not defined anywhere in the program.
3.2.10 Loader
Loader is the part of the operating system that loads the machine codes of a program
into the system memory and brings the execution file from system memory into
primary memory (e.g. RAM) and starts it running.
they all need to access the CPU, memory and storage in that case the OS coordinates
all of these. All modern operating systems are graphical user interface. In GUI user
can choose any icon on the desktop using mouse. The examples of OS are Microsoft
Window xp, Window 7, Window 8 and other higher versions, Linux, Google android.
The applications of OS are:
1. It manages the sharing of internal memory among multiple applications.
2. It supports multitasking which means that multiple programs can run
simultaneously (at the same time). In that case the OS determines which program
will run in what order and how much time it will take before allowing the other
application program.
3. It manages input and output to and from attached hardware device, i.e., hard
disks, printers, etc.
4. It can send information to each application program about error that may have
occurred.
SUGGESTION
Overall, if the programmer knows the logic of the problem then he/she can easily write
any program.
Output:
I LOVE MY INDIA
38 Concepts and Techniques of Programming in C
EXPLANATION:
From the above program we find the format for writing a C program.
(a) The first line is called comment line statement e.g. /*****/ which holds or
contains different pieces information about the program, e.g., name of the file
with their extension name, name of the program, name of the author, date on
which the program was executed and name of the files with their extension
names. The comment line is optional to write a program. It only gives the
information about the programming details to the unknown person. You can
write comments in between the /* */ starting asterisk and end asterisk.
/*******************************************************************
FILE NAME: simple(program name).c
AUTHOR DETAILS: Write Full Name, Semester, Branch Name, Your College
Name, Place.
DATE OF PROGRAM EXECUTE: 31/7/2015
NAME OF THE PROGRAM: simple C program
*******************************************************************/
In the above comment line the FILE NAME may be given by your name
(only first name not full name) with extension.c e.g. suppose my name is
Dhabal Prasad Sethi so we can give the file name as dhabal.c and do not write
dhabalprasadsethi.c. Alternatively, the file name may be given as program
name, i.e., simple.c and do not write simpleprogram.c.
(b) The second line #include<stdio.h> is called a preprocessor directive, which
tells or gives data (or information) to the C compiler to include the standard
input output (e.g. “stdio.h”) file with the programming statements written in
the editor before compilation of the program.
(c) Third line void main () is called the entry point of the C program (e.g. where the
program execution starts and it does not return any value, since void keyword
is used).
(d) Fourth line { (left curly brace) indicates it is the start of the main function.
(e) Fifth line printf(“I LOVE MY INDIA”); The printf statement is used to display
the message on the computer screen and the message is generally written
in between the double quotes of printf function. The double quotes are not
displayed on the computer screen and it only helps to display the output
(message).
(f) Sixth line (right curly brace) } is called the end/stop of the main function
program execution.
C Programming 39
TIPS TO REMEMBER
1. If arguments (e.g. int argc, char** argv) are passed inside the main() function.
It is called command line arguments. A good programmer always uses these
arguments. It is optional, i.e., you may or may not use the int argc, char** argv
as an argument.
Example:
void main(int argc, char** argv) { }
2. printf(“ ”); function is used to display the message where scanf(“ ”); function is
used to take input from the keyboard and stored in a variable.
The above programs are tested under Turbo c4.5 editor. If you want to write the
above program in Turbo C editor then type the program as
/*************************************************************************
FILE NAME: simple.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA.
DATE OF PROGRAM EXECUTE: 31/7/2015
NAME OF THE PROGRAM: simple C program
*************************************************************************/
#include<stdio.h>
#include<conio.h>
int main(void)
{
clrscr();
printf(“I LOVE MY INDIA”);
getch();
return 0;
}
Output:
I LOVE MY INDIA
EXPLANATION:
Here #include<conio.h> is a header file which is used for clrscr(); and getch(); function.
The clrscr(); function is used for clearing the screen. Generally, when a program is
written and after executing, it will display the output on the screen and again when
write the another program and run it. After running, it will display the previous output
along with the current output. So to remove previous output clrscr() is used. The benefit
of other function getch() ; is that when we press any key from the keyboard we will
see the next line but won’t see the key which is pressed. After displaying the output
window when any key is again pressed it will close the window.
40 Concepts and Techniques of Programming in C
TIPS TO REMEMBER
If you are using Turbo C editor for writing C program then you may write
#include<conio.h> after #include<stdio.h> and use clrscr(); and getch(); function
inside the main()function for normal program execution. If you are using Turbo
C4.5 editor or other higher version editor it is not mandatory to use clrscr(); and
getch();function inside the main() function and #include<conio.h> header file. Its
uses is optional.
Output:
I AM DHABAL PRASAD SETHI
EXPLANATION:
In the above program the entry point is main function. The empty parenthesis shows
that there is no parameter.
2. /* Entry point int main() function uses */
#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
printf(“I AM DHABAL PRASAD SETHI”);
getch();
return 0;
}
Output:
I AM DHABAL PRASAD SETHI
C Programming 41
EXPLANATION:
In the above program the entry point is int main() function therefore int before main()
function shows that the function returns an integer type value to the operating system.
When int is used before the main function then we should write return 0; at the end
of the program.
3. /*Entry point void main() function uses */
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
printf(“I AM DHABAL PRASAD SETHI”);
getch();
}
Output:
I AM DHABAL PRASAD SETHI
EXPLANATION:
In the above program the entry point, void main(), shows that the keyword void before
main function indicates the function does not send replay any value to the operating
system.
4. /* Entry point main(void) function uses */
#include<stdio.h>
#include<conio.h>
main(void)
{
clrscr();
printf(“I AM DHABAL PRASAD SETHI”);
getch();
}
Output:
I AM DHABAL PRASAD SETHI
EXPLANATION:
In the above program the entry point, void inside the parenthesis of main function,
shows that nothing is passed as an argument.
5. /* Entry point void main(void) function uses */
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
42 Concepts and Techniques of Programming in C
Output:
I AM DHABL PRASAD SETHI
EXPLANATION:
In the above entry point void main(void) void indicates no value returns to OS with
no argument is passed as an argument.
6. /* Entry point int main(void) function uses */
#include<stdio.h>
#include<conio.h>
int main(void)
{
clrscr();
printf(“I AM DHABAL PRASAD SETHI”);
getch();
return 0;
}
Output:
I AM DHABAL PRASAD SETHI
EXPLANATION:
In the above entry point, int main(void) means int before main()shows, it returns a
value to OS and void inside the parenthesis shows that no argument is passed as an
argument.
EXPLANATION:
Line 1: The document part is the comment line part and it contains the details about a
program, i.e., program name, program name with their extension, name of the author,
date on which program is executed by author.
Line 2: The link part gives information to the compiler to link the functions used in the
program from C library. Generally, header files are included in this link part.
Line 3: The definition part is to define the symbolic constant.
Line 4: The global declaration part is the declaration of global variable.
Line 5: The function prototype part gives the details about a function to the compiler,
i.e., return type, function name and parameter list, etc.
Line 6: In each C program the programmer must define one main() function and this
is called the entry point of a C program . The declaration part and execution part
inside the main function indicate the declaration of variables and later these variables
are used for execution. In each C program there should be minimum one statement for
execution. Program execution should start with opening brace and stop by using the
closing brace. The opening and closing braces generally are the logical opening and
stop of the main function. The declaration statements and executable statements of a
C program always end with a semicolon.
Line 7: The alternative name of subprogram part is the user-defined part/function part
and it is called from the main function. These user-defined functions are placed after
the main function or before the main function. If it is placed before the main function
then the function declaration does not require else it requires to declare the function.
TIPS TO REMEMBER
Before writing the complete C program, the programmer should know a preprocessor
directive? main function, variables, constant, data types, local variable, global
variable, functions. Some are described in this chapter and others are described in
next chapter.
/***********************************************************************
FILE NAME: x.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c basic program example
***********************************************************************/
#include <stdio.h> /* Link section */
#include<conio.h>
int x,y,z; /* Global declaration and definition section */
int mul(int p, int q); /* Function declaration(function prototype) section */
44 Concepts and Techniques of Programming in C
Output:
This is an example of basic structure of C program
Input the two numbers: 4 6
Multiplication of inputted two integer numbers is: 24
Source program
(x.c)
Preprocessor directive
Expanded source
program (x.i)
Compiler
Assembly program
(x.asm)
Assembler
Linker
1. Source Program
While writing a C program the language used in the editor is called the source program
(code) and after writing it, again it is stored as x.c. Then it is further expanded by the
preprocessor directive, e.g., #include and stored in the intermediate code with the file
extension. i, example: x.i. The expanded source program x.i is the C language. The
extension .i varies from compiler to compiler.
2. Role of Complier
The compiler then finds out the syntax error, i.e., comma (,), semicolon (;) etc, of
the expanded source code. If the expanded source code/program is an error-free
program then the role of the compiler is to convert the expanded source program into
assembly programming language. The assembly programming language is stored with
an extension .asm in the file e.g. x.i is converted into x.asm.
3. Role of Assembler
The assembler converts the source code x.asm into x.obj file. The object file is the
combination of machine instruction, data and information and it is required to place
in proper place of the memory.
The format of object file is
The object file header describes the size and position of the other pieces of the
file. Text segment holds the machine instructions and it is same as expanded source
program. Data segment holds binary representation of data in assembly file. Relocation
information identifies instructions and data that depend on absolute addresses. Symbol
table associates addresses with external labels and lists unresolved references.
4. Role of Linker
The linker links the object code with library function to form exe file. Generally, the
linker detects the errors like miss spelled library function name in the source program.
If the linker does not find the error then it searches the memory locations that code from
each module will occupy and relocates its instructions by adjusting absolute reference.
5. Role of Loader
When .exe file is created then it is stored in the hard drive and it is ready for execution.
When a beginner executes it, at that time the operating system is brought from the
C Programming 47
hard drive into RAM called program loader. The program loader places the .exe file
any vacancy locations in the drive.
4. Wrong: Use & operator in printf function but do not use in scanf function.
Correct: Do not use “& “operator in printf statement but use “&” in scanf function.
Example:
Wrong
scanf(“%d”,x);
printf(“%d”,&x);
Correct
scanf(“%d”,&x);
printf(“%d”,x);
5. Wrong: The comment line starts with /* and should not end properly.
Correct: Every comment line should start with /* and end with */. All the statements
about a program are written inside the given symbol.
Example:
Wrong
/* my first c program
Correct
/*my first c program*/
6. Wrong: The programmer gives semicolon in function definition but does not give in
function declaration.
Correct: The programmer should not give semicolon in function definition but should
give in function declaration.
7. Wrong: In reading the string by using scanf(); function, the programmer uses &
operator.
Correct: Do not use & operator in reading the string by using scanf(): function.
TIPS TO REMEMBER
Students should ensure that printf(); function is used to print the value or message,
scanf();function is used to take data values through keyboard or read data values
through keyboard and both functions, header file is #include<stdio.h>. The stdio.h
stands for standard input output dot header.
TIPS TO REMEMBER
Sometimes after running the programs if the output is infinite and we do not stop
that program then try to use the keyword: CTR + BREAK.
#include<stdio.h>
#include<conio.h>
#define PI 3.14 /*symbolic constant*/
void main(void)
{
float x, y, z;
clrscr();
printf(“Input the radius of circle:”);
scanf(“%f”, &x);
y=PI*x*x;
z=2*PI*x;
printf(“The area of circle is:%5.2f\n”, y);
printf(“The perimeter of circle is:%5.2f”,z);
getch();
}
Output:
Input the radius: 2.0
The area of circle is: 12.56
The perimeter of circle is: 12.56
EXPLANATION:
Here the user input the radius as 2.0 .Then apply the formula to find the area of the
circle e.g. formula is 3.14*radius*radius and to find the perimeter of the circle the
formula is 2*3.14*radius. Here x is declared radius and instead of 3.14, PI is used which
is called symbolic constant. Here symbolic constant is used because 3.14 is used two
times to avoid typing exact value of 3.14 programmer gives a name PI which is called
symbolic constant. So first PI is multiplied with radius two times and the results is
stored in y and then to find perimeter 2 is multiplied with PI and x. The result of the
perimeter is stored in z and last prints the y and z to get the result.
Q3. C Program to Calculate the Area and Perimeter of a Rectangle.
Solution:
/*************************************************************************
FILE NAME: prog3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to calculate the area and perimeter of a
rectangle
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
float x,y,z,m;
clrscr();
C Programming 51
Output:
Input the length and breadth of a rectangle: 3.0 2.0
The area of rectangle is: 6.0
The perimeter of rectangle is: 10.0
EXPLANATION:
Here the user input length and breadth of a rectangle through scanf() function and
the variable x is taken as length and y as breadth. To find the area of a rectangle the
formula is length*breadth and to find the perimeter of the rectangle the formula is
2*(length +breadth).Therefore, x is multiplied with y and the result is stored in variable
z. Then to find the perimeter multiply 2 with sum of length and breadth e.g2*(x+y) and
the result is stored in variable m. Lastly print the variable z and m to get the results.
Q4. C Program to Convert Temperature in Fahrenheit to Celsius.
Solution:
/*************************************************************************
FILE NAME: prog4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to convert temperature in Fahrenheit to
Celsius
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
float x,y;
clrscr();
printf(“Input the temperature in Fahrenheit :”);
scanf(“%f”,&x);
y=5.0/9.0*(x-32.0);
printf(“The conversion of temperature in Fahrenheit to Celsius is:%5.2f”,y);
getch();
}
Output:
Input the temperature in Fahrenheit: 98
The conversion of temperature in Fahrenheit to Celsius is: 36.67
52 Concepts and Techniques of Programming in C
EXPLANATION:
To find the Celsius the formula is 5.0/9.0*(farenhit-32.0) and in the printf() statements
%5.2f means it is the formatted out e.g. the output will be displayed in a fomat.5.2f
means the length of the output is 5 memory locations and after dot there will be 2
decimal memory locations. e.g. 36.67 is stored in the form shown below.
3 6 . 6 7
Output:
Input the temperature in Celsius: 37
The conversion of temperature in Celsius to Fahrenheit is: 98.60
EXPLANATION:
Here the user enters the Celsius and to define the formula of converting the Celsius
to Fahrenheit, i.e., Fahrenheit = (Celsius*9.0/5.0)+32.0 and in the last printf function
displays the Fahrenheit.
Q6. C Program to Compute the Sum and Average of Three Integer Numbers.
Solution:
/*************************************************************************
FILE NAME: prog6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
C Programming 53
Output:
Input the three integer numbers: 2 3 4
The sum of input three integer numbers is: 9
The avg is: 3.000000
EXPLANATION:
In the above program the user entered three integer numbers 2, 3 and 4 then sum
variable stores the results and then divides the sum into 3 and stores the result in avg
variable then print that value.
Q7. C Program to Swap/Exchange Two Numbers using the Third Variable.
Solution:
/*************************************************************************
FILE NAME: prog7.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to swap/exchange to numbers using third
variable
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
54 Concepts and Techniques of Programming in C
int x,y,z;
clrscr();
printf(“Input the two integer numbers to be swapped:”);
scanf(“%d%d”,&x,&y);
/*logic of swapping two integer numbers using third variable*/
z=x;
x=y;
y=z;
printf(“After swapping/exchanging the two integer numbers are:%d %d”,x,y);
getch();
}
Output:
Input the two integer numbers to be swapped: 5 6
After swapping/exchanging the two integer numbers are: 6 5
EXPLANATION:
Logic of swap two numbers using third variable:
Step1:z=x;
Step2:x=y;
Step3:y=z;
x=5, y=6, z is the third variable which holds data temporary according to our logic.
z=x, i.e., value of x is assigned to z, So z=5
after value of x becomes blank then
x=y, i.e., value of y is assigned to x, So x=6
after value of y becomes blank
y=z, i.e., value of z is assigned to y, So y=5
After applying the logic the value of x becomes 6 and value of y=5
Q8. C Program to Swap Two Numbers without using Third Variable.
Solution:
/*************************************************************************
FILE NAME: prog8.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to swap two numbers without using third
variable
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,y,z;
clrscr();
printf(“Input the two numbers to be swapped:”);
C Programming 55
scanf(“%d%d”,&x,&y);
/*logic of swapping without third variable*/
x=x+y;
y=x-y;
x=x-y;
printf(“After swapping/exchanging the numbers are:%d %d”,x,y);
getch();
}
Output:
Input the two numbers to be swapped: 3 4
After swapping/exchanging the numbers are: 4 3
EXPLANATION:
Logic of swapping two numbers without using the third variable:
Step1: x=x+y;
Step2: y=x-y;
Step3: x=x-y;
Example:
x=3 ,y=4
step1:x=3+4=7
step2:y=7-4=3
step3:x=7-3=4
thus after swapping the value of x=4 and value of y=3
Q9. C Program to Calculate the Simple Interest.
Solution:
/*************************************************************************
FILE NAME: prog9.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to calculate the simple interest
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,y,z,m;
clrscr();
printf(“Input the price, time and rate:”);
scanf(“%d%d%d”,&x,&y,&z);
m=(x*y*z)/100;
printf(“After calculation the simple interest is:%d”,m);
getch();
}
56 Concepts and Techniques of Programming in C
Output:
Input the price, time and rate: 100 2 5
After calculation the simple interest is: 10
EXPLANATION:
In the above program the user enters the price, time and rate of interest as 100,2,5
then multiplies all of them, i.e., 100*2*5=1000 and divides it by 100 and the result 10
is stored in variable interest and last print it. Here, the variable x is declared as price,
y is time and rate is z.
Q10. C Program to Find Area of Any Triangle.
Solution:
/************************************************************************
FILE NAME: prog10.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: c program to find area of any triangle
*************************************************************************/
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main(void)
{
float x,y,z;
float s,area;
clrscr();
printf(“Input the size of each side of triangle:”);
scanf(“%f%f%f”,&x,&y,&z);
s=(x+y+z)/2;
area=sqrt(s*(s-x)*(s-y)*(s-z));
printf(“The area of triangle is: %.3f”,area);
getch();
}
Output:
Input the size of each side of triangles: 2 3 4
The area of triangle is: 2.905
EXPLANATION:
Here the user enters the sides of the triangle then sums these sides and divides by 2
and stores in s. Then applies the formula, area = √(s*(s-x)*(s-y)*(s-z)), where s = (x + y
+ z)/2. And last print the area.
math.h is the header file used for mathematical operation.
C Programming 57
x y
Output:
Input the size of side of the equilateral triangle: 3
The area of equilateral triangle is: 3.897
EXPLANATION:
Formula of area of equilateral triangle:
area = (√3)/4 * x2
x x
58 Concepts and Techniques of Programming in C
Output:
Input the height and width of the right angled triangle: 3 2
The area of right angled triangle is: 3.000
EXPLANATION:
Here the user input the height and width of the right angled triangle, e.g., 3 as
height and 2 as width. The formula of calculating the area of right angled triangle is
½*height*width. So after multiplying (0.5*3*2=3) the result is 3. Since the data type is
float so 3.000 is the result.
w
C Programming 59
Output:
Input the principal amount: 200
Input the rate of interest: 4
Input the time period in year: 2
After calculation the compound interest is: 16.320000
Q14. C Program to Convert Centimeter into Meter and Kilometer.
Solution:
/************************************************************************
FILE NAME: prog14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 31/7/2015
NAME OF THE PROGRAM: C program to convert centimeter into meter and kilometer
*************************************************************************/
#include <stdio.h>
#include<conio.h>
60 Concepts and Techniques of Programming in C
void main(void)
{
float x;
clrscr();
float y,z;
printf(“Input the length in centimeter: “);
scanf(“%f”, &x);
y=x/100.0;
z=x/100000.0;
printf(“The length in Meter is:%.2f\n”,y);
printf(“The length in Kilometer is:%.2f”,z);
getch();
}
Output:
Input the length in centimeters: 100000
The length in meters is: 1000.00
The length in kilometer is: 1.00
EXPLANATION:
Here the user input the length as 100000. Then that length in cm was divided by 100
to get meter, i.e., 1000 meters and to convert again cm into km again divide centimeter
into 100000 to get km.
Summary
13. The printf ()function is used to display the output on the computer screen.
14. The scanf()function is used to take input through the keyboard into the memory.
15. The preprocessor directive is an instruction to the preprocessor.
16. #include<stdio.h> is called preprocessor directive, which tells to the C compiler
to include the standard input output, i.e., stdio.h file before compilation of the C
program.
SHORT QUESTIONS
LONG QUESTIONS
1. Write a C program to find the area and perimeter of circle and rectangle.
2. Write a C program to covert temperature in Fahrenheit to Celsius.
3. Write a C program to convert temperature from Celsius to Fahrenheit.
4. Write a C program to exchange to exchange the two integer numbers using third
variable.
5. Write a C program to exchange the two integer numbers without using the third
variable.
6. Write a C program to compute simple interest.
7. Write a C program to compute the compound interest.
8. Write a C program to find the area of right angled triangle.
9. Write a C program to find area of any triangle.
10. Write a C program to find area of equilateral triangle.
MULTIPLE-Choice QUESTIONS
4.1 Introduction
When a person sits in a chair then it takes some physical space. Like that in programming
concept when a variable is declared it takes some logical memory space. So we can say
that a variable is a memory location which is used to store some data values. Someone
can also say that a variable is a place holder because it holds some memory. At different
times during program execution, a variable can take different data values. But at a
single time the variable cannot take many values instead of single values. A variable
name should be given by the programmer in such a way that it is easy to execute the
program.
TIPS TO REMEMBER
Try to choose a simple variable name. So that it easy to perform the operation/
implementation.
EXPLANATION:
The above variable declaration shows that the first position in the syntax is the place
of data type then the variable name. The programmer chooses a single data type
according to his requirement from the fundamental types and the fundamental data
type means int, char, float and double.
Example:
int x; /*one variable declaration*/
EXPLANATION:
In the above example is the declaration of single variable. Here x is the variable name
and int is the integer data type. So x is a variable of data type int. In the declaration of
variable both data type and variable names are important to place in their position and
without both of these we cannot say that it is a valid variable declaration. We cannot
change their position also.
1000
1735
Here 1735 is the garbage value assigned by the compiler to variable x when it is
declared and the address of variable x is 1000. The variable stores the garbage value
1735 because the variable is not initialized. Therefore, we know that unused/initialized
variable will take the garbage value.
Like integer variable declaration we can also declare char type, float and double type
variable and the examples are:
char c;
float x;
double r;
EXPLANATION:
Here c is a variable which stores char type value, x is a variable which stores floating
type values and r is a variable which stores double precision floating type values.
EXPLANATION:
Here the first position is the place of fundamental data type and then variable1 is the
name of first variable, variable2 is the name of second variable-----variable-N is the
name of last variable.
Example:
int x,y,z; /*multiple variable declaration in single line*/
EXPLANATION:
In the above syntax the three variables x, y, z are declared in a single statement instead
of multiple statement. So x is a variable of int type and same y and z are variables of
int data type.
EXPLANATION:
The above declaration consists of data type, variable name, assignment operator and
constant values.
Example:
int x=20;
Here 20 is an integer constant value that is assigned to the variable x. e.g. in the location
x, 20 is stored. The logical representation of storing a variable x is shown below.
x Variable name
20 Value
2000 Address of variable x
Fig. 4.2 Initialization variable x
66 Concepts and Techniques of Programming in C
1. The variable name can begin with underscore (-), letter (it may be a lower case letter
or upper case letter).
Examples: _Total; or Total; or total; or TOTAL;
2. The length of a variable should not exceed 31 characters. But many compilers allowed
normally maximum eight characters.
3. The variable names are case sensitive, i.e., upper case and lower case alphabets are
different, e.g., number is not same as NUMBER.
4. Keywords are not allowed, e.g., for, if, while, do while.
Example:
wrong: int for;
correct: int student_id;
5. White space/blank spaces are not allowed.
Example:
wrong: int student id;
correct is: int student_id;
6. Special characters e.g. %, $, #, @ are not allowed.
Example:
wrong: int #student_id;
correct is: int student_id;
TIPS TO REMEMBER
From Table 4.1 we conclude that name of the variable can be written in lower case
or upper case letters. But a good programmer always prefers lower case letters.
z=x+y;
printf(“Sum of two integer numbers is:%d”,z);
}
Output:
Input two integer numbers: 2 3
Sum of two integer numbers is: 5
Constant
Numeric Character
constant constant
Integer Real
constant constant Single character
constant
String
constant
When is it Required?
When the programmer wants to use a constant multiple times then he can use a
substitute name for that character, for example, if the programmer is to use the p (pi)
value 3.14 in several places of the program, then he can give the alternative name PI
or other instead of 3.14 and use it everywhere in the program. This type of constant
is called symbolic constant.
Variables, Constants and Data Types 69
The syntax is
#define new_name constant_value
In the above declaration the new_name is the symbolic name for that substitute of
constant value and it is generally written in upper case letters. The constant_value may
be numeric, string or character.
TIPS TO REMEMBER
In symbolic constant do not give semicolon at the end of the statements, e.g.,
#define new_name constant_value;
Because #define is not a statement rather it is a preprocessor directive.
Output:
DHABAL
4.9 TOKENS
A token is the smallest individual unit in C programming. In text messages each word
and punctuation symbols are called tokens. There are six types of tokens in C. They
are: Keywords, constants, strings, operators, identifier, special symbols.
Tokens
Special
Keywords Constants Strings Operators Identifier symbols
4.10 KEYWORDS
Keywords are the words which are reserved in C compiler and its meaning has been
explained to the compiler and these word meaning cannot be changed. There are 32
keywords reserved in C programming. These keywords are generally written in lower
case character. They are:
Variables, Constants and Data Types 71
4.11 IDENTIFIER
Identifier means the naming of function, array and variables. These are user-defined
names and consist of letters and digits. Lowercase and upper case are allowed to give
identifier name. But lower case letters are generally used by the programmer.
Example:
(a) int x;
(b) int y[10];
(c) int z()
{
}
In the above first example int x; where x is called the variable or identifier. Liked
second example int y[10]; y is the array name or identifier y, int z(){ } where z is the
called the identifier or function name.
Identifier
Data types
Table 4.3 Different types of fundamental data types and its sizes
int --- ÆThese data type stores the integer value whose size is ---- Æ2 bytes (16-bit
compiler)
char- ÆThese data types stores the single character values whose size is------ Æ1 byte.
(16-bit compiler)
float - ÆThese data types stores floating point numbers whose size is ---- Æ4 bytes.
(16-bit compiler)
double ÆThese data type stores double precision floating point numbers whose size is
---8 bytes. (16-bit compiler)
long double - ÆThese data types whose size is ---- Æ10 bytes. (16-bit compiler)
Two types of qualifiers are used in the above fundamental data type, i.e., sign qualifier
and size qualifier. Sign qualifier is again of two types, i.e., signed and unsigned. When
signed qualifier is used before an integer number it means that the integer may be a
positive number or negative number. Unsigned integer means only positive integer
numbers. When no qualifier is mentioned, its default is signed. The size of data types
is a machine dependent. In some platform int data types occupy two bytes of memory
whereas in some other platform it may occupy four bytes of memory.
Variables, Constants and Data Types 73
Example:
typedef int marks;
Example 1:
enum months
{
January, February, march
};
Example 2:
enum month
{
January=1,february,march
};
Here January is assigned to 1 and by default February and March will be assigned to
2 and 3 respectively
/*Programming Example 3 of Enumerator*/
#include <stdio.h>
void main()
{
enum MONTH
{
January=0,February,March,April
};
enum MONTH month =April;
if(month == 0)
printf(“Value of January”);
else if(month == 1)
printf(“Month is February”);
if(month == 2)
printf(“Month is March”);
if(month == 3)
printf(“Month is April”);
}
Output:
Month is April
EXPLANATION:
In the above program the output is April because January starts width index 0, so
February index is 1, March index is 2 and April index is 3. Since enum variable is
initialized with April .Therefore 3 is assigned to variable month and when it matches
with last condition then it displayed the output “month is April”.
/*Programming Example 4 of Enumerator*/
#include<stdio.h>
enum numbers
{
zero,one,two,three,four=3,five,six,seven=0,eight
};
void main()
{
printf(“%d,%d,%d,%d,%d,%d,%d,%d,%d”,zero,one,two,three,four,five,six,seven,eight);
}
Variables, Constants and Data Types 75
Output:
0,1,2,3,3,4,5,0,1
EXPLANATION:
In the above program enum member begins at zero with default index 0 then one with
index 1, two with index 2, three with index 3, four initialized with index 3, five increase
the next index of previously initialized index so five assigned with index 4, six with
5, seven initialed with 0 and then eight increase the previous member index with one
e.g. eight with one.
Summary
Short questions
1. What is a variable?
2. What is a constant?
3. What is a symbolic constant. Give examples?
4. What are tokens? Explain different types of token.
5. How many keywords are availed in C program?
6. What is an identifier? Give examples.
76 Concepts and Techniques of Programming in C
Long question
5.1 INTRODUCTION
An operator is a symbol used in C programming to perform (or do) the mathematical and
logical operations (calculations) in an expression. These operators are generally added
with constants or variables in the expression. Operators are used in C programming
to input data values to the variables. Generally, an expression consists of operator,
variables and function constant. Examples: a*b-5 is an expression where a, b are
operands,*.- are operators and 5 is the constant.
EXPLANATION:
5.2.1 Arithmetic Operator
The arithmetic operators are used to do arithmetic calculations.
78 Concepts and Techniques of Programming in C
Q1. C Program to Add, Sub, Mul, Div, Mod of Two Integers Numbers using
Arithmetic Operator.
Solution:
/*************************************************************************
FILE NAME: operator1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: C program to add, sub, mul, div, mod of two integer
numbers using arithmetic operator.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,a,s,m,d,r;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
a=x+y;
s=x-y;
m=x*y;
d=x/y;
r=x%y;
printf(“Addition of inputted two integer numbers is:%d\n”,a);
printf(“Subtraction of inputted two integer numbers is:%d\n”,s);
printf(“Multiplication of inputted two integer numbers is:%d\n”,m);
printf(“Division of inputted two integer numbers is:%d\n”,d);
printf(“Remainder of inputted two integer numbers is:%d\n”,r);
}
Output:
Input the two integer numbers: 2 3
Addition of input two integer numbers is: 5
Subtraction of input two integer numbers is:-1
Multiplication of input two integer numbers is: 6
Division of input two integer numbers is: 0
Module of input two integer numbers is: 2
C Operator 79
Output:
Input the two integer numbers: 12 4
The arithmetic operations (sub, add, multiply, div and mod) done on 12 and 4 are:
8 16 48 3 0
Output:
Value of x is: 5
80 Concepts and Techniques of Programming in C
EXPLANATION:
Here = symbol is used to assign value 5 to variable x.
What is the major difference between prefix operators applied to single operand
vs. postfix operator applied to single operand?
Answer: When the operator is applied to single operand, e.g., x++ and ++x, then the
result will be same. But when it applies in an expression of right side of assignment
operator then the result will be different.
Let’s see the difference of prefix operator and postfix operator applied in single
operand x from Example 1 to Example 4, i.e., x++ and ++x.
/*Example 1 of Postfix Operator*/
#include<stdio.h>
void main()
C Operator 81
{
int x=1;
x++;
printf(“Value of x is:%d”,x);
}
Output:
Value of x is: 2
/*Example 2 of Prefix Operator*/
#include<stdio.h>
void main()
{
int x=1;
++x;
printf(“Value of x is:%d”,x);
}
Output:
Value of x is: 2
Output:
Value of x is: 1
/*Example 4 of Prefix Operator*/
#include<stdio.h>
void main()
{
int x=1;
printf(“Value of x is:%d”,++x);
}
Output:
Value of x is: 2
82 Concepts and Techniques of Programming in C
Output:
Value of x is: 5
Value of y is: 4
/*Example 6 of Prefix Operator applied in an Expression*/
#include<stdio.h>
void main()
{
int x=4,y;
y=++x;
printf(“Value of x is:%d\n”,x);
printf(“Value of y is:%d”,y);
}
Output:
Value of x is: 5
Value of y is: 5
/*Example 7*/
#include<stdio.h>
void main()
{
int x=5;
x=x++ + ++x;
printf(“%d”,x);
}
Output:
13
Explanation:
Here the x value is 5 and after incrementing the values of x++ becomes 6 and it assigns
to variable x, i.e., x value becomes 6, and then ++x becomes 7 and last addition of x++
and ++x value 6+7 becomes 13 and stored in variable x=13.
/*Example 8*/
#include<stdio.h>
void main()
{
int x=5,y;
y=x++ + ++x;
printf(“%d”,y);
}
Output:
12
/*Example 9*/
#include<stdio.h>
void main()
{
int x=5;
x=x++ + x++;
printf(“%d”,x);
}
Output:
12
Explanation:
Here x value is 5 and after increments the x++ value is 6 and stored in variable x and
then x++ value becomes
84 Concepts and Techniques of Programming in C
/*Example 10*/
#include<stdio.h>
void main()
{
int x=5,y;
y=x++ + x++;
printf(“%d”,y);
}
Output:
10
Explanation:
More increment and decrement programming examples are shown in objective question
with answer section of this chapter.
/*Example 11*/
#include<stdio.h>
void main()
{
int x=5;
printf(“%d %d %d %d %d”,x++,x--,++x,--x,x);
}
Output:
45545
Explanation:
Here the values of x are pushed into the stack format. Stack is a collection of elements
where values are inserted or deleted into the stack trough top, e.g., value of x=5 is
pushed first then - -x, ++x, x- -, x++.
Let’s see the input of x into the stack.
x++ (4)
x--(5)
++x( 5)
--x (4)
x( 5)
Stack
Let’s see more explanation about increment and decrement values of the stack are
pushed into the stack.
C Operator 85
(a)
5 Top
(b)
4 Top
5
(c)
5 Top
4
5
(d)
5 Top
5
4
5
(e)
4 Top
5
5
4
5
Output
The inputs of stack are stored from bottom to top. But the results will not display from
bottom to top. These will display from top to bottom. So the result is: 4 5 5 4 5.
86 Concepts and Techniques of Programming in C
Output:
Input the two integer numbers: 2 3
Among these two numbers 3 is the greatest number
C Operator 87
TIPS TO REMEMBER
The difference between = and == is that first one (=) is the assignment operator. The
objective of this assignment operator is to assign the value to the variable, e.g., a=10.
But the second one (==) is the comparison operator and it is used to compare the
two values for measuring the equality, e.g., if (a==5)
Output:
Input the three integer numbers: 3 2 1
Among these three numbers 3 is the greatest
Q. What will be the Output?
#include<stdio.h>
int main()
{
int i=6;
if(((++i<7)&&(i++/6))||(++i<=9));
printf(“%d\n”,i);
return 0;
}
Output:
8
88 Concepts and Techniques of Programming in C
Output:
Input the two integer numbers: 5 9
The greatest number between input two integer numbers is 9
EXPLANATION:
Here suppose the user entered the input 5 and 9 then if condition checked, i.e., 5>9?
5:9. In the conditional expression since the condition 1, i.e., 5>9 is not satisfied, so, i.e.,
condition 2 became the output, i.e., 9 is assigned to variable z and printf statement
printed the output 9 is the greatest.
C Operator 89
Q5. C Program for Finding the Greatest Number between Three Integer Numbers
using Conditional Operator.
Solution:
/************************************************************************
FILE NAME: operator5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: c program of finding greatest number between three
integer numbers using conditional operator.
*************************************************************************/
#include<stdio.h>
void main()
{
int x, y, z, a;
printf(“Input the three numbers:”);
scanf(“%d%d%d”,&x,&y,&z);
a=(x>y)? (x> z)? x: z:(y>z)?y:z;
printf(“Greatest number among inputted three numbers is:%d”, a);
}
Output:
Input the three numbers: 2 3 4
Greatest number among three numbers is: 4
EXPLANATION:
Here one conditional statement is nested with another conditional statement in
expression1.if x>y condition becomes true then the second conditional statement x>z
will check. If condition is satisfied then x value is assigned to variable a otherwise z
value is assigned to variable a. else if y>z is satisfied then y value is assigned to a or z
value assigned to a. Then last printf statement prints the value of a.
TIPS TO REMEMBER
Instead of the expression a=(x>y)?(x>z)?x:z:(y>z)?y:z; We can also write a=(x>y?(x>z?
x:y):(y>z? y:z));
Q6. C Program to Check the Number is Even or Odd using Conditional Operator.
Solution:
/*************************************************************************
FILE NAME: operator6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
90 Concepts and Techniques of Programming in C
NAME OF THE PROGRAM: c program to check the number is even or odd using
conditional operator.
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
clrscr();
printf(“Input an integer number:”);
scanf(“%d”,&x);
x%2==0?printf(“Inputted %d is an even number”, x): printf(“Inputted %d is
Odd number”, x);
getch();
}
Output:
Input an integer number: 6
Number 6 is an even number
EXPLANATION:
Here the user input the number 6 then expression will be evaluated, i.e., 6%2==0
condition is satisfied then expreesion 2 is the output, i.e., 6 is an even number.
Q7. C Program to Check Vowel or Consonant using Conditional Operator.
Solution:
/*************************************************************************
FILE NAME: operator7.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: C program to check vowel or consonant using conditional
operator.
*************************************************************************/
#include<stdio.h>
void main()
{
char x;
printf(“Input the character:”);
scanf(“%c”, &x);
(x==’a’||x==’A’||x==’e’||x==’E’||x==’i’||x==’I’||x==’o’||x==’O’||x==’u’||x
==’U’)?printf(“Inputted character %c is the vowel”, x): printf(“Inputted
character %c is the consonant”, x);
}
Output:
Input the character: r
Input character r is a consonant
C Operator 91
EXPLANATION:
Here input r is matched with the given condition. Since r does not match so the third
expression is the output, e.g., r is the consonant.
Output:
Size of integer data type is: 2
EXPLANATION:
The sizeof() is the keyword which is used to measure the size of each fundamental data
types. Here it measures the sizeof( int) data type.
TIPS TO REMEMBER
Instead of sizeof(int) ,we can also write sizeof(x), e.g., x is a variable which is int data
types and both give the same result according to respective data type.
/*C program of Checking Size of Character Data Type using sizeof() Operator*/
#include<stdio.h>
void main()
{
char x;
printf(“Size of character data type is:%d”,sizeof(char));
}
Output:
Size of character data type is: 1
/*C Program for Checking Size of Float Data Type using sizeof() Operator*/
#include<stdio.h>
void main()
{
92 Concepts and Techniques of Programming in C
float x;
printf(“Size of float data type is:%d”, sizeof(float));
}
Output:
Size of float data type is: 4
/*C program to Check Size of Double Data Type using sizeof() Operator*/
#include<stdio.h>
void main()
{
double x;
printf(“Size of double data type is:%d”, sizeof(double));
}
Output:
Size of double data type is:8
Q. What will be the Output?
#include<stdio.h>
#define int char
void main(void)
{
int x=65;
printf(“Size of variable x is:%d”,sizeof(x));
}
Output:
Size of variable x is: 1
EXPLANATION:
The output is 1 instead of 2 because the before main function the symbolic constant is
defined e.g. size of char is assigned to integer e.g. int size become 1.
(b) Examples of “&” Operator
#include<stdio.h>
void main()
{
int x=3;
printf(“ address of variable x is:%d”,&x);
}
Output:
Address of variable x is: 8698
EXPLANATION:
The address 8698 is address generated by system. It may vary from one operating
system to another.
C Operator 93
Output:
Value of x is:3
EXPLANATION:
This *(pointer) is called indirect operator and it indirectly prints the variables value.
Operator Purpose
& ------------- Æ bitwise AND
|--------------- Æ bitwise OR
<< ------------ Æ shift left
>> ------------ Æ shift right
^ ------------- Æ bitwise exclusive OR
Q8. C Programs to Check the Number Even or Odd using Bitwise Operator.
Solution:
/*************************************************************************
FILE NAME: operator8.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: c program to check the number even or odd using
bitwise operator
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
clrscr();
94 Concepts and Techniques of Programming in C
Output:
Input an integer number to check even or odd: 6
Input number is even
Q9. C Program to Swap Two Numbers using Bitwise XOR.
Solution:
/*************************************************************************
FILE NAME: operator9.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG. GCE, KEONJHAR, ODISHA
DATE OF PROGRAM EXECUTION: 2/8/2015
NAME OF THE PROGRAM: C program to swap two numbers using bitwise XOR
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main()
{
int x,y;
clrscr();
printf(“Input the two integer numbers:”);
scanf(“%d%d”, &x, &y);
printf(“Before swapping the inputted two integer numbers are :x = %d\ y
=%d\n”, x, y);
x=x^y;
y=x^y;
x=x^y;
printf(“After swapping the inputted two integer numbers are :x = %d\ y =
%d\n”, x, y);
getch();
}
Output:
Input the two integer numbers: 6 7
Before swapping the input two integer numbers are: x=6 y=7
After swapping the input two integer numbers are: x=7 y=6
C Operator 95
EXPLANATION:
In the following Example 1 will give the result 98. Since the variable y is an integer
type it holds the value 98.
Let’s convert it into programming.
/*Programming Conversion of Example 1*/
#include<stdio.h>
void main()
{
float x=98.92;
int y=x;/*automatic type casting*/
printf(“Value of x is:%f and value of y is:%d”, x, y);
}
Output:
Value of x is: 98.920000 and value of y is: 98
Example 2 of Implicit Type Casting
float y;
y=9/2;
EXPLANATION:
In the above Example 2 will give the result 4.0 instead of 4.5. Because 9/2 is taken
as an integer division and its result is integer type. To get the floating type value the
expression should like this:
y=9.0/2;
or
y=9.0/2.0;
or
y=9/2.0;
The above expression can give the result 4.5.
96 Concepts and Techniques of Programming in C
Output:
Value of x=4.50000
Example 3 of Implicit Type Casting
float z;
int x=5;
int y=2;
z=x/y;
EXPLANATION:
In the example the z value will be 2.0 instead of 2.5. To get the value 2.5 we need to
convert it into explicit type.
Example 4 of implicit Type Casting:
int z;
float x=3.0;
float y=2.0;
z=x/y;
EXPLANATION:
The output will be 1 because after dividing the two float values the result will be 1.5.
But compiler will type cast it to int type and assigned to z. so the value will be 1.
/*Programming Conversion of Example 6*/
#include<stdio.h>
void main()
{
int z;
float x=3.0;
float y=2.0;
z=x/y;
printf(“Value of z=%d”,z);
}
Output:
Value of z is: 1
C Operator 97
Output:
Value of z is: 2.50000
/*Program to Input Two Floating Point Numbers and Add the Two Values and Print
the Result as Integer Value*/
#include<stdio.h>
void main()
{
float x,y;
int z;
printf(“Input two floating values:”);
scanf(“%f%f”,&x,&y);
z=(int)x+(int)y;
printf(“Value of z:%d”,z);
}
98 Concepts and Techniques of Programming in C
Output:
Input two floating values: 5 4.8
Value of z is: 9
TIPS TO REMEMBER
When converting one data type to another data types it is best to convert lower data
types to higher data types because it avoids loss of data values.
When higher data type is going to convert into lower data type then data is truncated.
Example:
PASS 1:
Q: X=8-6/2+5*2-1
Step 1:
Q: X=8-6/2+5*2-1
Go to the expression from left to right. Since in the first pass the objective is to find out
the highest priority operator, i.e., in that expression there are two operator, i.e., and
*.Since these two operators have equal priority, so these come first and it will evaluate
it, i.e., operator will be evaluated first.
Ans: X=8-3+5*2-1
Step 2:
Q: X=8-3+5*2-1
Ans: X=9-3+10-1
C Operator 99
PASS 2:
Q: X=9-3+10-1
Step 3:
Q: X=9-3+10-1
Ans: X=6+10-1
Step 4:
Q: X=6+10-1
Ans: X=16-1
Step 5:
Q: X=16-1
Ans: X=15 (FINAL)
Summary
SHORT QUESTIONS
1. What is an operator?
2. What is the difference between prefix operators and postfix operators?
3. What is major difference between = and == operator?
4. What is the role of sizeof operator?
5. What is relational operator. Give examples.
6. What two symbols are used in conditional operator?
7. What is a conditional operator?
8. What is increment and decrement operator?
9. What is type casting?
10. What is implicit type casting?
11. What is explicit type casting?
100 Concepts and Techniques of Programming in C
LONG QUESTIONS
6.1 INTRODUCTION
In writing a complete computer program three basic operations are required. They
are reading data (taking data as input), processing the data and writing the data
(displaying the data). Generally, in writing any computer program the dates are taken
as input through keyboard and displayed on the computer screen as output. We have
seen in programming concept two important techniques are used to provide data to the
variable of that program. First one is assigning the values to the variable and second
one is to use the scanf() function which can take data from a keyboard. For displaying
the output the printf() function is used.
The C program does not have any built-in input or output statements as a part in
its syntax. So the input output operations are done through by using the scanf() and
printf() functions. There are several functions which are used for input and output
operations are called standard input/output library function. These functions are
predefined functions by the compiler. If the programmer wants to use any functions
from the standard I/O library then he should use the header file stdio.h in two different
ways, i.e., #include”stdio.h” or #include<stdio.h> compulsory.
In the current chapter we will study the different I/O functions that are not changed
by any machine.
{
char m;
printf(“Search your Name\n”);
printf(“If yes type in keyboard X :”);
scanf(“%c”,&m);
if(m==’X’)
printf(“ I AM DHABAL PRASAD SETHI”);
else
printf(“your name do not find”);
}
Output:
Search your Name
If yes type in keyboard X: X
I AM DHABAL PRASAD SETHI
Here in the above declaration getchar() function reads/takes only a single character
as input through keyboard and assigns it to the variable.
Example:
char ch;
ch=getchar();
Output:
Search your name
If yes type X: X
I AM DHABAL PRASAD SETHI
Input and Output Operations in C 111
Output:
Input a character: r
The inputted character is: r
/*Displaying a Character using putchar() Function*/
#include<stdio.h>
void main(void)
{
char x;
printf(“Input a character:”);
x=getchar(); /*Reading(taking) input by using getchar() function*/
printf(“The inputted character is:”);
putchar(x); /*Displaying output by using putchar() function*/
}
Output:
Input a character: d
The input character is: d
/*Another Example of putchar() Function*/
#include<stdio.h>
#include<ctype.h>
void main(void)
{
112 Concepts and Techniques of Programming in C
char x;
printf(“Input the alphabet(lowercase or uppercase):”);
x=getchar();
if(islower(x))
{
printf(“The Upper case is:”);
putchar(toupper(x));
}
else
{
printf(“The Lower case is:”);
putchar(tolower(x));
}
}
Output:
Input the alphabet (lower case or upper case): d
The upper case is: D
EXPLANATION:
The specifications are used in printf and scanf functions to read/take the data as input
or display output on the computer screen. If you want to read integer type data then
use %d. If you want to print the address of a variable then use %u. If you want to read
floating type input then use %f. If you want to read character type input then use %c.
If you want to read string types input then use %s.
Input and Output Operations in C 113
EXPLANATION:
The above table contains the escape characters .These are non-printable characters but
they have special meaning in displaying the output. These characters are generally used
in printf and scanf functions and must be preceded by a back slash (\).
These header files are frequently used by programmers whenever they write a C
program.
114 Concepts and Techniques of Programming in C
6.7 DELIMITERS
These are the symbols used in C programming for syntactic meaning (Table 6.4).
Symbol Meaning
:------------------colon Used for label
;-------------------semicolon Used for end of the statement
()------------------parenthesis Used for passing arguments
[]-----------------square braces Used in array
{}-----------------curly braces Used for block of statements
#------------------hash Used for preprocessor directive
,-------------------comma Used for separating the variables
The percentage (%) specifies that the conversion specification character, w stands for
integer number that represents the field width of the integer number, d is the format
specification character.
Example:
scanf(“%3d %5d”,&x,&y);
In above data 300 is assigned to variable x and 40555 to y. if we reverse the above
data then
Here, the first three digits 405 are assigned to variable x because %3d and rest value
of 40555, e.g., 55 is assigned to variable y. The value of 300 will be assigned to the next
scanf call. Let’s see the example
/*Examples of Inputting Integer Numbers*/
#include<stdio.h>
void main(void)
{
int x,y,a,b;
printf(“Input the two integer numbers:”);
scanf(“%3d%5d”,&x,&y);
printf(“You have inserted:”);
printf(“%3d %5d”,x,y);
printf(“\nInput the second two integer numbers:”) ;
scanf(“%3d %5d”,&a,&b);
printf(“You have inserted:”);
printf(“%3d %5d”,a,b);
}
Output:
Input the two integer numbers: 30455 300
You have inserted: 304 55
Input the second two integer numbers: 200 30455
You have inserted: 300 200
Explanation:
To solve the above error, do not use the width of the conversion specification character,
i.e., write the simple code of the scanf function.
scanf(“%d %d”,&x,&y);
116 Concepts and Techniques of Programming in C
If we use the same data 30455 300 then 30455 will be assigned to x and 300 are
assigned to y.
The control string contains the format specification character and it should be within
double quotes. The variable should not be preceded by an ampersand (&) sign.
Example:
#include<stdio.h>
void main(void)
{
int x=10,y=20,z;
z=x+y;
Printf(“Sum of two number is:%d”,z);
}
Output:
Sum of two number is: 30
(a) If the input number is greater than the field width, then it will print the full
number.
Let’s see the example
#include<stdio.h>
void main(void)
{
printf(“%2d”,590);
}
Output:
5 9 0
(b) If the input number is less then the specified field width then that number is
right justified with leading blank.
Let’s see
#include<stdio.h>
void main(void)
{
printf(“%5d”,590);
}
Output:
0 0 5 9 0
(c) It is possible to left justify the input number by placing the sign(-)minus after
the percentage sign.
#include<stdio.h>
void main(void)
{
printf(“%-5d”,590);
}
Output:
5 9 0
(d) It is possible to add zero, the leading blank, by placing a zero (0) after percentage
sign.
#include<stdio.h>
void main(void)
{
printf(“%05d”,590);
}
118 Concepts and Techniques of Programming in C
Output:
0 0 5 9 0
Output:
2 0 . 3 4 5
2 0 . 3 4 4 9 9 9
0 2 0 . 3 4
2 0 . 3 4
SUMMARY
1. The library functions which are used for input and output operations are called
input and output in C.
2. The getchar() function is used to read a single character.
3. The putchar() function is used to display/write a single character.
4. Formatted input means the input data is arranged in a particular format.
5. Formatted output means the output data is displayed in a particular format.
Input and Output Operations in C 119
SHORT QUESTIONS
LONG QUESTION
MULTIPLE-Choice QUESTIONS
7.1 INTRODUCTION
When a beginner starts writing a C program, he tries to write the programming
statements which are generally executed in one sentence after another because he /she
does not know about selection or looping statements and these programming sentences
are called sequential programming. But practically all real-time programs are not
always executed in sequential order. There are some programming statements which
require to give condition. These statements are called decision making statements or
selection statements or branching statements or conditional statements. And there
are some other programming statements which require to be executed a number of
times and these statements are called iteration statements or looping statements. The
examples of conditional statements are: if the weather condition is sunny then probably
T20 cricket match may be played otherwise it will be cancelled. Other condition is, if
the bowler bowls fultos then it may be six/four otherwise he may be out.
There are three selection statements present in C programming. They are: 1) if
statement, 2) switch statement, 3) conditional operator.
In the above decision making or selection statements, the if statement is a two-way
branching statement whereas switch statement is a multiway branching statement.
Another decision making statement named conditional operator is explained in chapter
on operator.
TIPS TO REMEMBER
From the above statements we conclude that decision making statements mean
that it is a subset of control statements which decide some statements are going
to execute based on condition and other statements are going to execute based on
other condition.
7.2 if STATEMENTS
The if statements are broadly categorized into different forms; e.g.
False
Condition
True
Statements
Output:
x and y are equal
126 Concepts and Techniques of Programming in C
EXPLANATION:
Here both x and y are initialized with the value 10.The if condition compared the two
values of x and y. Since the two values of x and y are matched, therefore x and y are
equal.
Q2. C Program for Finding Greatest Number between Two Integer Numbers using
if Statement
Solution:
/*************************************************************************
FILE NAME: if2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program of finding Greatest number between two integer
numbers using if statement
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main( void)
{
int x,y;
clrscr();
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
if (x > y )
{
printf(“Inputted %d is greater than %d”,x,y);
}
getch();
}
Output:
Input the two integer numbers: 4 3
Input 4 is greater than 3
EXPLANATION:
Here the user entered the value 4 and 3 through keyboard by using the scanf() function.
Since the if condition is satisfied, i.e., if(4>3) so printf statement prints 4 is greater than 3.
Q3. C Program to Calculate the Absolute Value of an Integer Number.
Solution:
/*************************************************************************
FILE NAME: if3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to calculate the absolute value of an
integer number
*************************************************************************/
Decision Making Statements (Conditional Statements) 127
#include<stdio.h>
void main(void)
{
int x;
printf(“Input the integer number:”);
scanf(“%d”,&x);
if(x<0)
{
x=-x;
}
printf(“The absolute value of inputted integer number is:%d”,x);
}
Output:
Input the integer number:-5
The absolute value of input integer number is: 5
EXPLANATION:
Here the user entered the value as -5. The if condition checked, i.e., if( -5<0). Since
condition is satisfied then body part of if statement becomes x=-(-5), i.e., 5. So the printf
statement prints the absolute value is 5.
Q4. C Program to Find Greatest Number between Three Integer Numbers using if
Statement
Solution:
/************************************************************************
FILE NAME: if2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to find greatest number between three integer
numbers using
if statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,z;
printf(“Input the three integer numbers:”);
scanf(“%d%d%d”,&x,&y,&z);
if(x>=y&&x>z)
printf(“Among the inputted three integer numbers %d is the largest”,x);
if(y>x&&y>=z)
printf(“Among the inputted three integer numbers %d is the largest”,y);
if(z>=x&&z>y)
printf(“Among the inputted three integer numbers %d is the largest”,z);
if(x==y&&y==z)
printf(“All three integer numbers are equal”);
}
128 Concepts and Techniques of Programming in C
Output:
Input the three integer numbers: 3 10 1
Among the input three integer numbers 10 is the largest
EXPLANATION:
Here the user entered the three integer numbers, i.e., 3, 10 and 1. Then each if condition
is checked. In the above program the second condition, i.e., if(10>1&&10>=1) is satisfied.
So 10 is the largest number. When more than one if condition are satisfied then each
printf statement followed by if will print the value.
False
Condition?
True
Statement Statement
block 1 block 2
Statement
block 3
Output:
Input the integer number: 4
Input 4 is an even number
EXPLANATION:
Here suppose the user entered the integer number as 4. The if condition is checked,
i.e., if (4%2==0). Since that condition is true so 4 is an even number. Here % is called
module operator or remainder operator.
Q2. C Program to Check the Character is Vowel or Consonant using if-else
Statements.
Solution:
/*************************************************************************
FILE NAME: ifelse2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to check the character is vowel and consonant
using if-else statements.
*************************************************************************/
#include<stdio.h>
void main(void)
{
char x;
130 Concepts and Techniques of Programming in C
printf(“Input a character:”);
scanf(“%c”,&x);
if(x==’a’||x==’A’||x==’e’||x==’E’||x==’i’||x==’I’||
x==’o’||x==’O’||x==’u’||x==’U’)
printf(“Inputted %c is the vowel “,x);
else
printf(“Inputted %c is the consonant “,x);
}
Output:
Input a character: a
Inputted a is the vowel
EXPLANATION:
Here the user entered the character ‘a‘ as input. Since ’a’ is matched with the given
condition so ‘a’ is a vowel. Hereafter if statement curly braces are not used because after
if statement single printf statement is there. Therefore, it is optional to use curly braces.
Q3. C Program to Check the Character is an Alphabet or Not.
Solution:
/*************************************************************************
FILE NAME: ifelse3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to check the character is alphabet or not
*************************************************************************/
#include<stdio.h>
void main(void)
{
char x;
printf(“Input the character(alphabet or any /,’,””.etc):”);
scanf(“%c”,&x);
if((x>=’a’&&x<=’z’)||(x>=’A’&&x<=’Z’))
printf(“Inputted %c is an alphabet”, x);
else
printf(“Inputted %c is not the alphabet”,x);
}
Output:
Input the character (alphabet or any/, ’, ””, .etc): .
Input is not the character
EXPLANATION:
Here the user entered the character (.) as input. Then it checked the if condition. The
if condition does not match with(.) So else bock is executed, i.e., it prints(.) is not the
alphabet.
Decision Making Statements (Conditional Statements) 131
Q4. C Program to Check the Year is Leap Year or not using if-else Statements.
Solution:
/*************************************************************************
FILE NAME: ifelse4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to check the year is leap year or not using
if else statements
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x;
printf(“Input the year to check leap year:”);
scanf(“%d”,&x);
if((x%4==0 && x%100!=0)||(x%400==0))
{
printf(“Inputted %d is a leap year”,x);
}
else
{
printf(“Inputted %d is not a leap year”,x);
}
}
Output:
Input the year to check leap year: 2020
Input 2020 is a leap year
EXPLANATION:
Here the user entered the year 2020 to check the year is leap year or not. The if statement
is used to check the condition, i.e., if(2020%4==0&&2020%100!=0)||(2020%400==0).
As 2020%4==0 true and 2020%100=20 is true and condition 2020%400==0 is false. So
in if statement two conditions are given, i.e., first condition inside parenthesis true and
second condition inside parenthesis is false. Since in between two conditions OR symbol
is used. It means any of the above two conditions if any one condition becomes true
then the expression becomes true. As a result the year 2020 is a leap year.
Q5. C Program to Find Roots of the Quadratic Equation using if-else Statements.
Solution:
/*************************************************************************
FILE NAME: ifelse5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
132 Concepts and Techniques of Programming in C
Output:
Input the floating values of x, y, z: 2.0 4.0 -20.0
root1 is: 2.32, root2=-4.32
EXPLANATION:
Here the user entered the floating values 2.0, 4.0 and -20.0 as input. Then find the
discriminate. Since the discriminate values is greater than 0, so if condition is satisfied
and prints the two roots values.
Q6. C Program to Find the Greatest Number between Two Integer Numbers using
if-else Statements.
Solution:
/*************************************************************************
FILE NAME: ifelse6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to find greatest number between two integer
numbers using if-else statements.
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main(void )
{
int x,y;
Decision Making Statements (Conditional Statements) 133
clrscr();
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
if (x > y )
{
printf(“Inputted %d is greater than %d”,x,y);
}
else
{
printf(“Inputted %d is less than %d”,x,y);
}
getch();
}
Output:
Input the two integer numbers: 2 3
Input 2 is less than 3
EXPLANATION:
Here the two inputs x and y are given, i.e., 2 and 3. In if condition the x value is not
greater than y. So the else block prints the result 2 is less than 3.
False
Condition 1?
True
False
Condition 2?
True
Statement
block 4
if(x>=80&&x<90)
printf(“Your grade is E”);
else
{
if(x>=70 &&x<80)
printf(“your grade is A”);
else
printf(“your grade is B”);
}
}
}
Output:
Input the marks between [90-60]:80
Your grade is E
EXPLANATION:
Here the user entered the marks 80 as input. That marks will check with the given
condition. In the above program if(80>=80&80<90) condition is satisfied. So it prints
your grade is E.
Q2. C Program for Finding the Greatest Number between Three Integer Numbers
using nested if-else Statements.
Solution:
/*************************************************************************
FILE NAME: nestif2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program of finding greatest number between three
integer numbers using nested if-else Statements
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,z;
printf(“Input the three integer numbers:”);
scanf(“%d%d%d”,&x,&y,&z);
if(x>=y)
{
if(x>z)
{
printf(“Among the inputted three integer numbers %d is the greatest”,x);
}
else
{
printf(“Among the inputted three integer numbers %d is the greatest”,z);
}
}
136 Concepts and Techniques of Programming in C
else
{
if(y>z)
{
printf(“Among the inputted three integer numbers %d is the greatest”,y);
}
else
{
printf(“Among the inputted three integer numbers %d is the greatest”,z);
}
}
}
Output:
Input the three integer numbers: 3 18 1
Among the input three integer numbers 18 is the greatest
EXPLANATION:
Here the three inputs are entered, i.e., 3 18 and 1. The three values are checked in each
condition. In nested if else statement if the first condition is true then it will check the
inner condition. Since the first condition is not true so control goes to the else block.
In else block the if conditions satisfied, i.e., if(18>1) So 18 is the result as the greatest
number.
The else if is the way of arranging the else statement with the if statement.
Let’s see the difference in the boxes
if(x==1)
printf(“good morning”);
else
{
if(x==2)
printf(“good evening”);
}
if(x==1)
printf(“good morning”);
else if(x==2)
printf(“good evening”);
Condition 1?
Condition 2?
Statement
block1
Condition-N?
Statement
block2
Default
statement
Statement
block-N
Q1. C Program to Find Greatest Number between Three using Else if Statement.
138 Concepts and Techniques of Programming in C
Solution:
/************************************************************************
FILE NAME: elseif1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to find greatest number between three using
else if statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,z;
printf(“Input the three integer numbers:”);
scanf(“%d%d%d”, &x, &y, &z);
if(x>=y&&x>z)
printf(“Among the inputted three integer numbers %d is the greatest “, x);
else if(y>x && y>=z)
printf(“Among the inputted three integer numbers %d is the greatest “, y);
else if(z>=x&&z>y)
printf(“Among the inputted three integer numbers %d is the greatest “, z);
else
printf(“All the three integer numbers are equal”);
}
Output:
Input the three integer numbers: 3 10 6
Among the input three integer numbers 10 is the greatest
EXPLANATION:
Here inputs are x as 3, y as 10 and z as 6. The inputs are checked with each condition.
When any one condition satisfies then it will stop for checking next condition and
control does not move to the next statements. In the above three inputs are checked
with the first condition, i.e., 3 is not greater than equal to y and 3 is not greater than 6
so the first condition is not satisfied. Then it check with the second condition, i.e., 10>3
and 10>6. Since this condition is satisfied so it will print 10 as the greatest number.
Q2. C Program to Determine the Year is Leap Year or not using else-if Statement.
Solution:
/************************************************************************
FILE NAME: elseif2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to determine the year is leap year or not
using else if statement.
*************************************************************************/
Decision Making Statements (Conditional Statements) 139
#include <stdio.h>
#include<conio.h>
int main(void)
{
int y;
clrscr();
printf(“Input the year to check leap year or not:”);
scanf(“%d”,&y);
if(y%400== 0)
printf(“Inputted %d is a leap year”, y);
else if(y%100== 0)
printf(“Inputted %d is not a leap year”, y);
else if(y%4==0)
printf(“Inputted %d is a leap year”, y);
else
printf(“Inputted %d is not a leap year”, y);
getch();
return 0;
}
Output:
Input the year to check leap year or not: 2012
Input 2012 is a leap year.
EXPLANATION:
Here the user entered the year 2012. The input is checked with each condition. In the
above example the first condition 2012%400 is not equal to zero, then it checked the
second condition, i.e., 2012 %100 is not equal to zero so checked the third condition,
i.e., 2012%4 is equal to zero. So the third condition will print the 2012 is a leap year.
Q3. C Program to Determine the Temperature Condition of each Day entered by User
using else-if Statements.
Solution:
/*************************************************************************
FILE NAME: elseif3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to determine the temperature condition of
each day entered by user using else if statements
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
float x;
clrscr();
printf(“Input the Temperature:”);
140 Concepts and Techniques of Programming in C
scanf(“%f”,&x);
if(x<=0)
{
printf(“The weather condition of today is very cold”);
}
else if(x>0&&x<=10)
{
printf(“The weather condition of today is cold”);
}
else if(x>10&&x<=20)
{
printf(“The weather condition of today is cool out”);
}
else if(x<=30&&x>20)
{
printf(“The weather condition of today is warm”);
}
else
{
printf(“The weather condition of today is hot”);
}
getch();
}
Output:
Input the temperature: 50
The weather condition of today is hot.
EXPLANATION:
The input 50 is checked in the above each condition. Since the input is not matched
with the above condition so else block will display the output.
Q4. C Program to Select your Favorite Color using else-if Statements.
Solution:
/************************************************************************
FILE NAME: elseif4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to select your favorite color using else
if statements
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x;
printf(“MY FAVORITE COLORS\n”);
Decision Making Statements (Conditional Statements) 141
Output:
1st Run
MY FAVORITE COLORS
1. RED COLOR
2. GREEN COLOR
3. YELLOW COLOR
4. BLUE COLOR
5. PINK COLOR
6. ORANGE COLOR
From [1 to 6] to select the colors: 6
My favorite color is ORANGE COLOR
2nd Run
MY FAVORITE COLORS
142 Concepts and Techniques of Programming in C
1. RED COLOR
2. GREEN COLOR
3. YELLOW COLOR
4. BLUE COLOR
5. PINK COLOR
6. ORANGE COLOR
From [1 to 6] to select the colors:7
You did not select your favorite color
EXPLANATION:
Here the user enters the number 6 .The else if statement tells that when one condition
in the above conditions is true then it does not go to the next condition. When all
conditions become false the else block is the result. So from the definition, the condition,
i.e., else if(6==6) is satisfied so orange color is the output.
Q5. C Program to Print Day of Your Birthday.
Solution:
/*************************************************************************
FILE NAME: elseif5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to print day of your birthday name
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x;
printf(“WEEK_SRNO BIRTHDAY\n1.MONDAY\n2.TUESDAY\n3.WEDNESDAY\n4.THRUSDAY\
n5.FRIDAY\n 6.SATURDAY\n”);
printf(“Input your birthday serial number[1-7]:”);
scanf(“%d”,&x);
if(x==1)
{
printf(“My birthday falls on MONDAY”);
}
else if(x==2)
{
printf(“My birthday falls on TUESDAY”);
}
else if(x==3)
{
printf(“My birthday falls on WEDNESDAY”);
}
else if(x==4)
{
printf(“My birthday falls on THURSDAY”);
Decision Making Statements (Conditional Statements) 143
}
else if(x==5)
{
printf(“My birthday falls on FRIDAY”);
}
else if(x==6)
{
printf(“My birthday falls on SATURDAY”);
}
else if(x==7)
{
printf(“My birthday falls on SUNDAY”);
}
else
{
printf(“Invalid number”);
}
}
Output:
WEEK_SRNO BIRTHDAY
1. MONDAY
2. TUESDAY
3. WEDNESDAY
4. THURSDAY
5. FRIDAY
6. SATURDAY
Input your birthday in serial number [1-7]:6
My birthday falls on SATURDAY
EXPLANATION:
Follow the same principle of above else if condition.
Q6. C Program to Print Number of Days in a Month.
Solution:
/************************************************************************
FILE NAME: elseif6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to print number of days in a month.
*************************************************************************/
#include <stdio.h>
int main(void)
{
int x;
printf(“Input the month number[1-12]:”);
scanf(“%d”,&x);
144 Concepts and Techniques of Programming in C
if(x==1)
{
printf(“The month Jan is 31 days”);
}
else if(x==2)
{
printf(“The month Feb is 28/29 days”);
}
else if(x==3)
{
printf(“The month March is 31 days”);
}
else if(x==4)
{
printf(“The month April is 30 days”);
}
else if(x==5)
{
printf(“The month May is 31 days”);
}
else if(x==6)
{
printf(“The month Jun is 30 days”);
}
else if(x==7)
{
printf(“The month July is 31 days”);
}
else if(x==8)
{
printf(“The month August is 31 days”);
}
else if(x==9)
{
printf(“The month September is 30 days”);
}
else if(x==10)
{
printf(“The month October is 31 days”);
}
else if(x==11)
{
printf(“ The month November is 30 days”);
}
else if(x==12)
{
printf(“The month December is 31 days”);
}
else
{
Decision Making Statements (Conditional Statements) 145
EXPLANATION:
Follow the same principle of above else if condition.
Output:
1. BTECH
2. MTECH
3. MCA
4. BPHARMA
5. MPHARMA
6. DIPPLOMA
Select your favorite courses [1-6]:3
You liked MCA
You liked BPHARMA
You liked MPHARMA
You liked DIPPLOMA
EXPLANATION:
In the above program the menu contains different courses. When the user entered the
choice 3 then four statements are displayed instead of selecting one. Because break
statement is not used in that program. Therefore, to select any one course in the list,
always use break keyword in each case statement at the end. The correct program is
written in Q2.
Q2. C Program to Select the Favorite Courses using switch case Statement without
using Break Statement.
OR
Q. Example of not using Break Statement in switch case Statements.
Solution:
/*************************************************************************
FILE NAME: switch2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program to check the selecting the favorite courses
using switch case statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
148 Concepts and Techniques of Programming in C
int ch;
printf(“1.BTECH\n 2.MTECH\n 3.MCA\n 4.BPHARMA\n 5.MPHARMA\n 6.DIPPLOMA”);
printf(“Select your favorite course[1-6]:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“You liked BTECH\n”);
break;
case 2:
printf(“You liked MTECH\n”);
break;
case 3:
printf(“You liked MCA\n”);
break;
case 4:
printf(“You liked BPHARMA\n”);
break;
case 5:
printf(“You liked MPHARMA\n”);
break;
case 6:
printf(“You liked DIPPLOMA\n”);
break;
default:
printf(“You entered Invalid choice”);
break;
}
}
Output:
1. BTECH
2. MTECH
3. MCA
4. BPHARMA
5. MPHARMA
6. DIPPLOMA
Select your favorite course [1-6]:4
You liked BPHARMA
EXPLANATION:
Since break keyword is used in each case statement at the end therefore when the user
enters 4 as his choice then it will display BPHARAMA.
Q3. C Program for Selecting the Favorite Day using switch case Statement.
Solution:
/*************************************************************************
FILE NAME: switch3.c
Decision Making Statements (Conditional Statements) 149
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program of selecting the favorite day using switch
case statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int day;
printf(“1.Sunday\n 2.Monday\n 3.Tuesday\n 4.Wednessday\n 5.Thrusday\n
6.Friday\n 7.Saturday\n”);
printf(“Select your favorite day[1-6]:”);
scanf(“%d”,&day);
switch(day)
{
case 1:
printf(“You liked Sunday”);
break;
case 2:
printf(“You liked Monday”);
break;
case 3:
printf(“You liked Tuesday”);
break;
case 4:
printf(“You liked Wednesday”);
break;
case 5:
printf(“You liked Thursday”);
break;
case 6:
printf(“You liked Friday”);
case 7:
printf(“You liked Saturday”);
break;
break;
default:
printf(“you entered invalid choice”);
}
}
Output:
1. Sunday
2. Monday
3. Tuesday
4. Wednesday
5. Thursday
150 Concepts and Techniques of Programming in C
6. Friday
7. Saturday
Select your favorite day [1-6]:2
You liked Monday
Q4. C Program of Simple Calculator using switch case Statement.
Solution:
/*************************************************************************
FILE NAME: switch4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program of simple calculator using switch case
statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,z,m;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
printf(“Menu\n1.Addition\n2.Subtarction\n3.Multiplication\n4.Division\
n5.Reminder\n”);
printf(“Select your choices[1-5]:”);
scanf(“%d”,&m);
switch(m)
{
case 1:
z=x+y;
printf(“The addition of inputted two integer numbers is:%d\n”,z);
break;
case 2:
z=x-y;
printf(“The subtraction of inputted two integer numbers is:%d\n”,z);
break;
case 3:
z=x*y;
printf(“The multiplication of inputted two integer numbers is:%d\n”,z);
break;
case 4:
z=x/y;
printf(“The division of inputted two integer numbers is:%d\n”,z);
break;
case 5:
z=x%y;
printf(“The reminder of inputted two integer numbers is:%d\n”,z);
break;
default:
Decision Making Statements (Conditional Statements) 151
EXPLANATION:
In the above program the output is 10 because the two integer numbers 2 and 8 are
added.
Q5. C Program to Check the Alphabet is a Vowel or a Consonant.
Solution:
/*************************************************************************
FILE NAME: switch4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: c program to check the alphabet is vowel or consonant
*************************************************************************/
#include<stdio.h>
void main(void)
{
char x;
printf(“Input the alphabets:”);
scanf(“%c”,&x);
switch(x)
{
case’a’:
case ‘A’:
case’e’:
case ‘E’:
case’i’:
case ‘I’:
case’o’:
case ‘O’:
case’u’:
case ‘U’:
printf(“%c is the vowel”,x);
break;
152 Concepts and Techniques of Programming in C
default:
printf(“The Inputted %c is the consonant”);
}
}
Output:
Input the alphabets: u
The inputted u is a vowel
Q6. C Program of Award Grades by Bput In Lieu of Marks in the Ranges using
switch case Statement.
Solution:
/************************************************************************
FILE NAME: switch5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 3/8/2015
NAME OF THE PROGRAM: C program of award grades by BPUT in lieu of marks
in the ranges using switch case statement
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,marks;
printf(“ BPUT GRADATAION SYSTEM\n1.90% and above\n 2.80% to 89%\n 3.70% to
79%\n 4.60% to 69%\n 5.50% to 59%\n 6.37% to 49%\n 7.Less then 37%\n”);
printf(“Select the choice[1-6]:”);
scanf(“%d”,&x);
printf(“Input the marks:”);
scanf(“%d”,&marks);
switch(x)
{
case 1:
if(marks>=90&&marks<=100)
printf(“Your grade is O”);
break;
case 2:
if(marks>=80&&marks<=89)
printf(“Your grade is E”);
break;
case 3:
if(marks>=70&&marks<=79)
printf(“Your grade is A”);
break;
case 4:
if(marks>=60&&marks<=69)
printf(“Your grade is B”);
break;
Decision Making Statements (Conditional Statements) 153
case 5:
if(marks>=50&&marks<59)
printf(“Your grade is C”);
break;
case 6:
if(marks>=37&&marks<=49)
printf(“Your grade is D”);
break;
case 7:
if(marks>=0&&marks<37)
printf(“Your grade is F”);
break;
default:
printf(“Invalid choice”);
}
}
Output:
BPUT GRADATION SYSTEM
1. 90% and above
2. 80% to 89%
3. 70% to 79%
4. 60% to 69%
5. 50% to 59%
6. 37% to 49%
7. Less then 37%
Select the choice [1-6]:2
Input the marks: 85
Your grade is E
Summary
SHORT QUESTIONS
1. What is if statements?
2. What is an if-else statement?
3. What is an else-if statement?
4. What is switch statement?
LONG QUESTIONS
1. C program to find the greatest number between the three using else-if statements.
2. C program to find roots of the quadratic equation using if-else statements.
3. C program to check alphabet is a vowel or a consonant.
4. C program for detecting the grade of marks in the ranges using switch case
statements.
5. C program to evaluate the power series ex=1+x+x2/2!+x3/3!+----------xn/n! Using
if else statement
printf(“ODISHA”);
}
Output:
ODISHA
Explanation:
The relational operator (>) is uses only two operands. Since it is applied on three
operands, inside the if condition therefore it is false. As a result else block will
display output as ODISHA.
8. What will be the output?
#include<stdio.h>
void main()
{
auto int x=6;
if(--x)
{
printf(“%d”,x);
}
}
Output:
5
9. What will be the output?
#include<stdio.h>
void main()
{
int x=3;
switch(x)
{
case 1:
printf(“INDIA\n”);
case 2:
printf(“ODISHA\n”);
case 3:
continue;
default:
printf(“LORD JAGATTNATH\n”);
}
}
Output:
Error(misplaces continue)
Explanation:
The output is error because continue keyword should not be used in switch case
statement. Continue keywords are allowed in looping.
158 Concepts and Techniques of Programming in C
Explanation:
The output is ODISHA because x value is 1 and it matched with case 1.
12. What will be the output?
#include<stdio.h>
void main()
{
int a=1;
switch(a/2)
{
case NULL:
printf(“case NULL\n”);
break;
case 0:
printf(“case ZERO\n”);
break;
default:
printf(“DEAFAULT”);
break;
}
}
Output:
Compilation error
Explanation:
Duplicate case in function main, i.e., case NULL: and case 0: both are same.
8
Looping
8.1 INTRODUCTION
8.1.1 When is Looping Required?
Loops are very useful and basic needs to programmers. When he/she wants to execute
any block of statements repeatedly and can be controlled by giving the condition. The
advantage of looping is that it saves time as well as writing the same programming
code multiple times. Suppose beginner wants to write a C program to print your name
and address 20 (or more) times. So, it creates headache for beginner to write 20 printf
statements to display the name and address. So to solve this problem he tries to use
looping. In looping he uses any one among three looping statements (e.g., while, do
while and for) and a printf statement is used inside the loop to print the name and
address 20 times.
loop. If the condition is true then body of the loop is executed otherwise it becomes
false and control goes out from the loop. But in exit controlled loop, the conditional
statements are examined at the end of the loop. When the condition becomes false then
body of the loop executes at least once.
The important things done by each programmer in looping are: first they initialize
the conditional variable, second make a test for each conditional variable, third to use
curly brace because those statements require executing number of times then they put
these inside curly braces, fourth is to increment and decrement the conditional variable.
There are three types of looping operations working in C programming. They
are: (a) while loop, (b) do while loop, (c) for loop.
EXPLANATION:
A while loop is a control structure which is used to check the condition and the
condition is kept inside the parentheses preceded by using the keyword while at the
beginning of the loop. Generally, the conditions are numeric or alphanumeric. When
the condition becomes true then the statement block is executed inside the curly braces
repeatedly. When the condition is false, the while loop is stopped. After stopping the
loop, the program control moves to the next statements immediately after skipping
the body of the loop. This loop is also called an entry-controlled loop because at the
beginning condition is checked and if it is true, the statements inside the curly braces
are executed.
TIPS TO REMEMBER
• This is a good looping process with numeric applications.
• The programmer uses while loop when he does not know the number of iterations
required.
162 Concepts and Techniques of Programming in C
Input statement
Condition
TIPS TO REMEMBER
• Do not give semicolon at the end of while statement but do not forget to give a
semicolon at the end of while in do while statement.
• When one statement is present inside the loop, then there is no requirement to
use the curly braces but good programmers can use it.
• Putting semicolon at the end of while and for statement is not a syntax error but
it is a logical error.
printf(“ %d “,x);
x=x+1;
}
}
Output:
This is a program for displaying integer numbers from 1 to 15 using while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
EXPLANATION:
Here x=1, while(1<=15) then print 1 and x increases to 2 and continue the loop until
x=15. When x=16 then the loop terminates. Therefore, the outputs are 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15
Q2. C Program of Conversion of Binary Number to Decimal Number.
Solution:
/*************************************************************************
FILE NAME: while2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: program of conversion of binary number to decimal number
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y=0,i=1,z;
printf(“This is a program of binary to decimal conversion\n”);
printf(“Input the binary Number:”);
scanf(“%d”,&x);
while(x!=0)
{
z=x%10;
y=y+z*i;
i=i*2;
x=x/10;
}
printf(“Decimal value of inputted binary number is:%d”, y);
}
Output:
This is a program of binary to decimal conversion
Input the binary Number:1111
Decimal value of input binary number is:15
EXPLANATION:
In the above program x = binary number, y = decimal number, z = remainder variable.
164 Concepts and Techniques of Programming in C
1st iteration
binary number=x=1111
while(1111!=0)
{
Remainder z=x%10=1111%10=1 e.g z=1
Decimal number =y=y+z*i=0+1*1=1
i=i*2=1*2=2
Binary number x=x/10=1111/10=111
}
2nd iteration
binary number=x=111
while(111!=0)
{
Remainder z=x%10=111%10=1 e.g z=1
Decimal number =y=1+1*2=3
i=2*2=4
Binary number x=x/10=111/10=11
}
3rd iteration
binary number=x=11
while(11!=0)
{
Remainder z=x%10=11%10=1 e.g z=1
Decimal number =y=y+z*i=3+1*4=7
i=i*2=4*2=8
Binary number x=x/10=11/10=1
}
4th iteration
binary number=x=1
while(1!=0)
{
Remainder z=x%10=1%10=0 e.g z=1
Decimal number =y=y+z*i=7+1*8=15
i=i*2=8*2=16
Binary number x=x/10=1/10=0
}
5th iteration
Loop terminates since binary number 0 is not equal to 0.
Q3. C Program to Convert Decimal to Binary using While Loop.
Solution:
/*************************************************************************
FILE NAME: while3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
Looping 165
Output:
This is a program of decimal to binary conversion
Enter the decimal number:12
The input value 12 in binary form is:1100
EXPLANATION:
The user enters the integer input as 12 then it assigns to y, i.e., y=12
1st iteration
while(12!=0)
{
reminder=12%2=0
z=0+0*1=0
x=12/2=6
a=1*10=10
}
2nd iteration
while(6!=0)
{
reminder=6%2=0
z=0+0*10=0
x=6/2=3
a=10*10=100
}
166 Concepts and Techniques of Programming in C
3rd iteration
while(3!=0)
{
reminder=3%2=1
z=0+1*100=100
x=3/2=1
a=100*10=1000
}
4th iteration
while(1!=0)
{
reminder=1%2=1
z=100+1*1000=1100
a=1000*10=10000
}
5th loop
Loop terminates.
Q4. C Program of Summation of Nth Term Natural Numbers E.G 1+2+3---N=N(N+1)/2
using While loop.
Solution:
/*************************************************************************
FILE NAME: while4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program of summation of nth term natural numbers
e.g 1+2+3---n=n(n+1)/2 suing while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,count=1,sum=0;
printf(“This is a program of summation of nth natural number\n”);
printf(“Input the nth term of natural number:”);
scanf(“%d”,&x);
while(count<=x)
{
sum=sum+count;
count++;
}
printf(“Summation of inputted nth term natural number is:%d”,sum);
}
Output:
This is a program of summation of nth natural number.
Looping 167
EXPLANATION:
Suppose x=5
1st iteration
while(1<=5)
{
sum=0+1=1;
count=2;
}
2nd iteration
while(2<=5)
{
sum=1+2=3;
count=3;
}
3rd iteration
while(3<=5)
{
sum=3+3=6
count=4
}
4th iteration
while(4<=5)
{
sum=6+4=10;
count=5
}
5th iteration
while(5<=5)
{
sum=10+5=15
count=6
}
6th iteration
Loop terminates.
Q5. C Program of Count the Number of Digits of an Integer Number using While
Loops.
Solution:
/*************************************************************************
FILE NAME: while5.c
168 Concepts and Techniques of Programming in C
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of count the number of digits of an integer
number using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,count=0;
printf(“This is a program of counting the number of digits of an integer
numbers\n”);
printf(“Input the integer number:”);
scanf(“%d”,&x);
while(x!=0)
{
x=x/10;
count++;
}
printf(“Number of digits of an inputted integer number is:%d”,count);
}
Output:
This is a program of counting the number of digits of integer numbers
Input the integer number: 123
Number of digits of an input integer number is: 3
EXPLANATION:
Suppose the input x=123
1st iteration
while(123!=0)
{
x=123/10=12;
count=1
}
2nd iteration
while(12!=0)
{
x=12/10=1
count=2
}
3rd iteration
while(1!=0)
{
x=1/10=0
count=3
}
Looping 169
4th iteration
Loop terminates.
Q6. C Program to Reverse a Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to reverse a number a using while loop
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,reminder,rev=0;
printf(“This is a program of reverse an integer number\n”);
printf(“Input the integer number :”);
scanf(“%d”,&x);
while(x!=0)
{
reminder=x%10;
rev=rev*10+reminder;
x=x/10;
}
printf(“The reverse of inputted integer number is:%d”,rev);
}
Output:
This is a program of reverse an integer number
Input the integer number: 123
The reverse of input integer number is: 321
EXPLANATION:
Suppose the input x=123
1st iteration
while(123!=0)
{
reminder=123%10=3;
rev= rev*10+reminder =0*10+3=3
X=x/10=123/10=12
2nd iteration
while(12!=0)
{
reminder=12%10=2
rev= rev*10+reminder =3*10+2=32
170 Concepts and Techniques of Programming in C
X=x/10=12/10=1
}
3rd iteration
while(1!=0)
{
reminder=1%10=1
rev= rev*10+reminder =32*10+1=321
x=x/10=1/10=0
}
Output:
This is a program to check a number is palindrome or not;
Input the integer number: 121
The input number 121 is a palindrome
EXPLANATION:
Looping 171
TIPS TO REMEMBER
A number is called palindrome when its digits are reversed and it remain the same.
Examples of palindrome number are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77,
88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191.
Before going to loop the user inputs number through scanf function and stored in
variable y and again that number is assigned to another variable rev. in reverse a
number logic, that number y is compared with another variable rev, if matched then
it is a palindrome number.
The logic of reverse a number is
1st iteration
while(121!=0)
{
reminder=121%10=1
rev=0*10+1;
x=121/10=12
}
2nd iteration
while(12!=0)
{
reminder=12%10=2
rev=1*10+2=12
x=12/10=1
}
3rd iteration
while(1!=0)
{
reminder=1%10=1
rev=12*10+1=121
x=1/10=0
}
4th iteration
In the 4th iteration the loop terminates.
After terminating the loop, the reversed number is compared with y which contains
the input number. If matches then that number is a palindrome number.
Q8. C Program to Check Number is Armstrong Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while8.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
172 Concepts and Techniques of Programming in C
Output:
This is a program to check a number is Armstrong number or not
Input the integer number: 153
Input number 153 is an Armstrong number
EXPLANATION:
TIPS TO REMEMBER
Those numbers whose sum of the cube of its digits is equal to that number are called
Armstrong numbers.
Example: 153=13+53+33=1+125+9=153
370=33+73+03=27+343=370
Others are 371,407
Before going to loop, enter the number through scanf function and assign it to another
variable y, then write the logic of program to find sum of the cube of digits of a number.
After that resultant number stored in sum and is compared with y variable, if matched
then it is an Armstrong number.
1st iteration
while(153!=0)
{
Looping 173
reminder=153%10=3
sum=0+(3*3*3)=27
x=153/10=15
}
2nd iteration
while(15!=0)
{
reminder=15%10=5
sum=27+(5*5*5)=152
x=15/10=1
}
3rd iteration
while(1!=0)
{
reminder=1%10=1
sum=152+(1*1*1)=153
x=1/10=0
}
4th iteration
The loop terminates.
After the loop terminates, sum is compared with y. If matches then that number is an
Armstrong number.
Q9. C Program to Display the Sum of Digits of an Integer Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while9.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to display the sum of digits of any integer
number using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,sum=0,r;
printf(“This is a program of sum of digits of an integer number\n”);
printf(“Input an integer number:”);
scanf(“%d”,&x);
while(x>0)
{
r=x%10;
sum=sum+r;
x=x/10;
}
printf(“Summation of digits of an inputted integer number is:%d”, sum);
}
174 Concepts and Techniques of Programming in C
Output:
This is a program of sum of digits of an integer number
Input an integer number: 123
Summation of digits of an inputted integer number is: 6
EXPLANATION:
Here the user enters the number through scanf function e.g. 123.
1st iteration
while(123>0)
{
r=123%10=3
sum=0+3=3
x=123/10=12
}
2nd iteration
while(12>0)
{
r=12%10=2
sum=3+2=5
x=12/10=1
}
3rd iteration
while(1>0)
{
r=1%10=1
sum=5+1=6
x=1/10==0
}
In the 4th iteration loop terminates.
Q10. C Program of Multiplication of Digits of an Integer Number using While
Loop.
Solution:
/*************************************************************************
FILE NAME: while10.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program of multiplication of digits of a integer
number using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
Looping 175
int x,multi=1,r;
printf(“This is a program of multiplication of digits of an integer
number\n”);
printf(“Input the integer number:”);
scanf(“%d”,&x);
while(x>0)
{
r=x%10;
multi=multi*r;
x=x/10;
}
printf(“Multiplication of digits of an inputted integer number is:%d”,multi);
}
Output:
This is a program of multiplication of digits of an integer number
Input the integer number: 123
Multiplication of digits of the input integer number is: 6
EXPLANATION:
Follow the above program, instead of addition use multiplication.
Q11. C Program to Find the Power of an Integer Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while11.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find the power of an integer number using
while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int power,x,i=1,total=1;
printf(“This is a program of finding the power of an integer number\n”);
printf(“Input the integer number:”);
scanf(“%d”,&x);
printf(“Input the power of that number:”);
scanf(“%d”,&power);
while(i<=power)
{
total=total*x;
i++;
}
printf(“Power of inputted number %d is: %d “,x,total);
}
176 Concepts and Techniques of Programming in C
Output:
This is a program of finding the power of an integer number
Input the integer number: 2
Input the power of that number: 3
Power of input number 2 is: 8
EXPLANATION:
In the above program the user enters the number as 2 and power as 3.
1st iteration
while(1<=3)
{
total=total*x e.g 1*2=2
i++ e.g 2
}
2nd iteration
while(2<=3)
{
total=2*2=4
t++ e.g 3
}
3rd iteration
while(3<=3)
{
total=4*2=8
}
4th iteration
Loop terminates
Q12. C Program to Check the Number is a Perfect Number or not Using While Loop.
Solution:
/*************************************************************************
FILE NAME: while12.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to check the number is a perfect number or
not using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,j=1,sum=0;
printf(“This is a program to check a number is a perfect number or not\n”);
printf(“Input the integer number:”);
Looping 177
scanf(“%d”,&x);
while(j<x)
{
if(x%j==0)
sum=sum+j;
j++;
}
if(sum==x)
printf(“Inputted number %d is a perfect number”, x);
else
printf(“Inputted number %d is not a perfect number”, x);
}
Output:
This is a program to check a number is a perfect number or not
Input the integer number: 6
Input number 6 is a perfect number
EXPLANATION:
Because if the sum of the divisor of the number is equal to that number then we call
them perfect numbers. Examples of perfect number is 6 because divisor of 6 are 1, 2,
3. So sum of 1+2+3=6.
Q13. C Program to Find Gcd and Lcm of two Integer Numbers using While Loop.
Solution:
/*************************************************************************
FILE NAME: while13.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find GCD and LCM of two integer numbers
using while loop
*************************************************************************/
#include <stdio.h>
void main(void)
{
int m,n,x,y,t,gcd,lcm;
printf(“This is a program to find GCD and LCM of two integer numbers\n”);
printf(“Input two integer numbers:”);
scanf(“%d%d”,&x,&y);
m=x;
n=y;
while(n!=0)
{
t=n;
n=m%n;
m=t;
}
178 Concepts and Techniques of Programming in C
gcd=m;
lcm=(x*y)/gcd;
printf(“Greatest common divisor of inputted %d and %d is:%d\n”,x,y,gcd);
printf(“Least common multiple of inputted %d and %d is:%d\n”,x,y,lcm);
}
Output:
This is a program to find GCD and LCM of two integer numbers
Input two integer numbers: 2 3
Greatest common divisor of input 2 and 3 is: 1
Least common multiple of input 2 and 3 is: 6
Q14. C Program to Find Gcd (Greatest Common Divisor) of two Numbers using
While Loop.
Solution:
/*************************************************************************
FILE NAME: while14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find GCD(greatest common divisor) of two
numbers using while loop.
*************************************************************************/
#include<stdio.h>
void main()
{
int x,y;
printf(“This is a program to find GCD two integer numbers\n”);
printf(“input two integer numbers:”);
scanf(“%d%d”,&x,&y);
printf(“Gcd of two integer numbers[%d and %d] is:”,x,y);
while(x!=y)
{
if(x>y)
x=x-y;
else
y=y-x;
}
printf(“%d”,x);
}
Output:
This is a program to find GCD two integer numbers
Input two integer numbers: 4 2
GCD of two integer numbers [4 and 2]is:2
Looping 179
Q15. C Program to Find Lcm Between Two Integers using While Loop.
Solution:
/*************************************************************************
FILE NAME: while14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to find LCM between two integer numbers
using while loop.
*************************************************************************/
#include<stdio.h>
void main()
{
int x,y,z,t1,t2;
printf(“This is a program to find LCM of two integer numbers\n”);
printf(“Input two integer numbers:”);
scanf(“%d%d”,&x,&y);
printf(“LCM of two integer numbers[%d and %d] is:”,x,y);
t1=x;
t2=y;
while(t1!=t2)
{
if(t1>t2)
t1=t1-t2;
else
t2=t2-t1;
}
z=(x*y)/t1;
printf(“%d”,z);
}
Output:
This is a program to find LCM of two integer numbers
Input two integer numbers: 4 2
LCM of two integer numbers [4 and 2]is: 4
Q16. C Program to Find Sum of the First and the Last Digit of an Integer Number.
Solution:
/*************************************************************************
FILE NAME: while14.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to find sum of first and last digit of an
integer number.
*************************************************************************/
180 Concepts and Techniques of Programming in C
#include <stdio.h>
#include<conio.h>
void main(void)
{
int i,x,t=0;
clrscr();
printf(“This is a program to find sum of first and last digit of an integer
number\n”);
printf(“Input the integer number:”);
scanf(“%d”,&x);
if(x>10)
{
t=t+x%10;
}
while(x>10)
{
x=x/10;
}
t=t+x;
printf(“Sum of first and last digit of that inputted number is:%d”,t);
getch();
}
Output:
This is a program to find the sum of the first and the last digits of an integer number
Input the integer number:123
Sum of first and last digits of that input number is: 4
Q17. Factorial of a Number using While Loop.
Solution:
/*************************************************************************
FILE NAME: while15.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: factorial of a number using while loop.
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,j,fact;
fact=j=1;
clrscr();
printf(“This is a program to calculate factorial of a number\n”);
printf(“Input the integer number to find factorial:”);
scanf(“%d”,&x);
Looping 181
while(j<=x)
{
fact*=j;
j++;
}
printf(“The Factorial of inputted %d is:%d”,x ,fact);
getch();
}
Output:
This is a program to find the sum of the first and the last digits of an integer number
Input the integer number to find factorial: 4
The factorial of input 4 is: 24
Q18. Fibonacci Series up to Nth Term using While Loop.
Solution:
/*************************************************************************
FILE NAME: while15.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: Fibonacci series up to nth term using while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=0,y=1,z=0,n;
printf(“This is a program to find Fibonacci series upto nth term\n”);
printf(“Input the number of terms:”);
scanf(“\n%d”,&n);
printf(“Fibonacci series are:%d %d”,x,y);
z=x+y;
while(z<n)
{
z=x+y;
x=y;
y=z;
printf(“ %d “,z);
}
}
Output:
This is a program to find Fibonacci series up to nth term
Input the number of terms: 5
Fibonacci series are: 0 1 1 2 3
182 Concepts and Techniques of Programming in C
EXPLANATION:
In do while loop the condition is examined at the end of the loop instead of beginning,
whether it is true or false. If the condition becomes true then the program repeatedly
evaluates the statement blocks of the loop again and again. This evaluation process
continues until condition does not become false. When the condition is false then the
loop will stop immediately and control passes to the next statement after skipping the
while statements. This loop is also called exit-controlled loop therefore the body of the
loop is executed at least once.
True
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to display the numbers from 1 to 15 using
do while loop
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=1;
do
{
printf(“ %d “,x);
x=x+1;
}
while(x<=15);
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Explanation:
In the above example of do while loop first the value x=1 is printed inside the do
part and x value increments, i.e., x=2. And the last while condition is checked, i.e.,
while(2<=15); condition satisfied then control goes to the do part of the program again
and prints the value and continue the loop until it terminates.
Q2. C Program of Sum of Nth Natural Numbers using do While Loop.
Solution:
/*************************************************************************
FILE NAME: dowhile2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of sum of nth natural numbers using do
while loop
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,n,x=1;
printf(“Input the nth natural numbers:”);
scanf(“%d”,&n);
do
{
sum=sum+x;
x++;
184 Concepts and Techniques of Programming in C
}while(x<=n);
printf(“The summation of inputted nth natural number is:%d”,sum);
}
Output:
Input the nth natural number: 4
The sum of input nth natural number is: 10
Q3. C Program of Binary to Decimal Conversion using Do-While Loop.
Solution:
/*************************************************************************
FILE NAME: dowhile3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of binary to decimal conversion using do
while loop
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y=0,i=1,z;
printf(“Input the binary Number:”);
scanf(“%d”,&x);
do
{
z=x%10;
y=y+z*i;
i=i*2;
x=x/10;
}
while(x!=0);
printf(“Decimal value of inputted binary number is:%d”,y);
}
Output:
Enter the binary number: 110
Decimal value of input binary number is: 6
EXPLANATION:
Here, user enters the input as 110
1st iteration
do
{
z=110%10=0
y=0+0*1=0
Looping 185
i=1*2=2
x=110/10=11
}while(110!=0);
2nd iteration
do
{
z=11%10=1
y=0+1*2=2
i=2*2=4
x=11/10=1
}while(11!=0);
3rd iteration
do
{
z=1%10=1
y=2+1*4=6(decimal form)
i=4*2=8
x=1/10=0
}while(1!=0);
4th iteration
Loop terminates.
Q4. C Program to Check the Armstrong Number using Do While Loop.
Solution:
/*************************************************************************
FILE NAME: dowhile4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to check the Armstrong number using do
while loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,reminder,sum=0,y;
printf(“Input the integer number to check Armstrong number:”);
scanf(“%d”,&x);
y=x;
do
{
reminder=x%10;
sum=sum+(reminder*reminder*reminder);
x=x/10;
}
186 Concepts and Techniques of Programming in C
while(x!=0);
if(sum==y)
printf(“Inputted number %d is Armstrong number”,y);
else
printf(“Inputted number %d is not an Armstrong number”,y);
}
Output:
Input the integer number to check Armstrong number: 135
Input number 135 is not an Armstrong number
Assignment: Try to convert the above while loop programs into do while programs.
EXPLANATION:
The above declaration consists of three parts, i.e., initialization, condition and increment/
decrement. In the initialization part, values are assigned to the variables and in the
condition part, if the condition is true then statement block of the loop will be executed
otherwise it will terminate. When the statement block of the loop is executed at first
iteration, at the that time program control moves to the increment part of the for loop.
In the second iteration, the variable’s value increases and again tests the condition, if it
again becomes true then statement block of the loop is executed and it continues until
the condition become true.
Looping 187
Variable initialization
Update statement
Jump to next
statements out the
for loop
for(x=1;x<4;x++)
{
Output:
Input the number of loop: 4
x is:1 y is:1 total is:2
x is:1 y is:2 total is:3
x is:1 y is:3 total is:4
x is:2 y is:1 total is:3
x is:2 y is:2 total is:4
x is:2 y is:3 total is:5
x is:3 y is:1 total is:4
x is:3 y is:2 total is:5
x is:3 y is:3 total is:6
Looping 189
EXPLANATION:
Here the outer loop is x and inner loop is y. The number of loop is 4. For each outer
loop of x, the inner loop y executes 3 times, i.e., for 3 outer loops, 3 inner loop executes,
i.e., 9 statements are executed.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
2)#include<stdio.h>
void main()
{
int x;
for(x=1;x<=15;)
{
printf(“%d\t”,x);
x=x+1;
}
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
3)#include<stdio.h>
void main(void)
{
int x=1;
for(;x<=15;x=x+1)
printf(“%d\t”,x);
}
190 Concepts and Techniques of Programming in C
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
4)#include<stdio.h>
void main(void)
{
int x=1;
for(;x<=15;)
{
printf(“%d\t”,x);
x=x+1;
}
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
5)#include<stdio.h>
void main(void)
{
int x;
for(x=0;x++<15;)
printf(“%d\t”,x);
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Q2. C Program of Sum of Nth Natural Numbers using for Loop.
Solution:
/*************************************************************************
FILE NAME: for2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program of sum of nth natural numbers using for loop
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0,n,x;
printf(“Input the nth natural numbers:”);
scanf(“%d”,&n);
for(x=1;x<=n;x++)
{
sum=sum+x;
}
Looping 191
Output:
Input the nth natural numbers:4
The summation of nth natural number is:10
Q3. C Program to Find Prime Numbers between 1 to 100 using for Loop.
Solution:
/*************************************************************************
FILE NAME: for3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find prime numbers between 1 to 100 using
for loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,j,count;
printf(“The prime numbers [1-100]are:\n”);
for(x=1;x<=100;x++)
{
count=0;
for(j=2;j<=x/2;j++)
{
if(x%j==0)
{
count++;
break;
}
}
if(count==0&&x!=1)
printf(“%d\t”,x);
}
}
Output:
The prime numbers [1-100] are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
EXPLANATION:
Logic of prime number:
A number which has two divisors, i.e., 1 and itself is called prime number. Example 3,
their divisor are 1 and 3. We will have two loops. The outer loop is the number from 1
192 Concepts and Techniques of Programming in C
to 100 and outer loop will divide the number taking from 2 to number/2. If the number
is not divisible by any of the number then we will print the prime numbers which are
displayed in the output.
Q4. C Program of Sum of Digits of an Integer Number using for Loop.
Solution:
/*************************************************************************
FILE NAME: for4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of sum of digits of an integer number using
for loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,sum=0,r;
printf(“Input the integer number:”);
scanf(“%d”,&x);
for(;x!=0;x=x/10)
{
r=x%10;
sum=sum+r;
}
printf(“Summation of digits of an inputted integer number is:%d”,sum);
}
Output:
Enter the number: 123
Summation of digits of an input integer number is: 6
Q5. C Programs of Reverse a Number using for Loop.
Solution:
/*************************************************************************
FILE NAME: for5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program of reverse a number using for loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,reminder,rev=0;
printf(“Input the integer number:”);
scanf(“%d”,&x);
Looping 193
for(;x!=0;x=x/10)
{
reminder=x%10;
rev=rev*10+reminder;
}
printf(“Reverse of inputted integer number is:%d”,rev);
}
Output:
Input the integer number: 789
Reverse of input integer number is: 987
Q6. C Program to Count the Number of Digits of an Integer Number using for Loop.
Solution:
/*************************************************************************
FILE NAME: for6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to count the number of digits of an integer
number using for loop.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,count=0;
printf(“Input the integer number:”);
scanf(“%d”,&x);
for(;x!=0;x=x/10)
{
count++;
}
printf(“Number of digits of an inputted integer number is:%d”,count);
}
Output:
Input the integer number: 1234
Number of digits of an input integer number is: 4
Q7. C Program to Find the Factorial of an Integer Number using for Loop.
Solution:
/*************************************************************************
FILE NAME: for7.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find the factorial of a integer number
using for loop
*************************************************************************/
194 Concepts and Techniques of Programming in C
#include<stdio.h>
void main(void)
{
int x,i,fact=1;
printf(“Input the integer number to find the factorial:”);
scanf(“%d”,&x);
for(i=x;i>0;i--)
{
fact=fact*i;
}
printf(“Factorial of integer number %d is :%d\n”,x,fact);
}
Output:
Input the integer number to find the factorial: 5
Factorial of integer number 5 is: 120
Q8. C Program to Generate the Pyramid by Entering the Number of Lines by User.
Or
C Program to Print Floyd’s Triangle
1
11
111
1111
Solution:
/*************************************************************************
FILE NAME: for8.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to generate the pyramid by entering the
number of lines by user.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y,n;
printf(“Input the number of lines:”);
scanf(“%d”,&n);
printf(“The generated pyramid is:\n”);
for(x=1;x<=n;x++)
{
for(y=1;y<=x;y++)
{
printf(“1”);
}
Looping 195
printf(“\n”);
}
}
Output:
Input the number of lines:4
The generated pyramid is:
1
11
111
1111
Q9. C Program to Print Pyramid of 1.
Or
C Program to Print Patterns of Numbers and 1.
1
111
11111
Solution:
/*************************************************************************
FILE NAME: for9.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to print pyramid of 1.
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x,y,n,z;
printf(“Input the number of rows in pyramid of one: “);
scanf(“%d”,&n);
printf(“The generated pyramid is:\n”);
z= n;
for(x=1;x<=n;x++ )
{
for(y =1;y<z;y++ )
printf(“ “);
z--;
for (y= 1;y<=2*x-1;y++ )
printf(“1”);
printf(“\n”);
}
}
196 Concepts and Techniques of Programming in C
Output:
Input the number of rows in pyramid of one:3
The generated pyramid is:
1
111
11111
Q10. C Program to Print Half Pyramid using Numbers.
1
12
123
1234
Solution:
/*************************************************************************
FILE NAME: for10.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to print half pyramid using numbers
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x,y,n;
printf(“Input the number of rows:”);
scanf(“%d”,&n);
printf(“The generated half pyramid is:\n”);
for(x=1;x<=n;++x)
{
for(y=1;y<=x;++y)
{
printf(“%d “,y);
}
printf(“\n”);
}
}
Output:
Input the number of rows: 4
The generated half pyramid is:
1
12
123
1234
Looping 197
Q11. C Program to Find Out the Sum of Series 1^2 + 2^2 + …. + N^2.
Solution:
/*************************************************************************
FILE NAME: for11.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: c program to find out the sum of series 1^2 + 2^2
+ .... + n^2
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x,m,s=0;
clrscr();
printf(“Input the maximum number of series :”);
scanf(“%d”,&x);
s=(x*(x+1)*(2*x+1))/6;
printf(“Sum of the inputted series “);
for(m=1;m<=x;m++)
{
if (m!= x)
printf(“%d^2+”,m);
else
printf(“%d^2 is:%d”,m,s);
}
getch();
}
Output:
Input the maximum number of series: 4
Sum of the input series 1^2+2^2+3^2+4^2 is:30
Q12. C Program to Find Sum of Series 1 + 2 + 3 +......+ N=N*(N+1)/2.
Solution:
/*************************************************************************
FILE NAME: for12.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to find sum of series 1 + 2 + 3 +......+
n=n*(n+1)/2.
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
198 Concepts and Techniques of Programming in C
int i,x,s=0;
clrscr();
printf(“1+2+3+......+n”);
printf(“\nInput the value of n:”);
scanf(“%d”,&x);
for(i=1;i<=x;++i)
{
s=s+i;
}
printf(“Sum of values of %d is:%d”,x,s);
getch();
}
Output:
1+2+3……+n
Input the values of n: 4
Sum is: 10
Q13. C Program to Find Even Number between 1 to 100 using for Loop.
Solution:
/*************************************************************************
FILE NAME: for13.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to find even number between 1 to 100 using
for loop.
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void main(void)
{
int x;
clrscr();
printf(“EVEN NUMBER BETWEEN [1 to 100]”);
printf(“\n”);
for(x=1;x<=100;x++)
{
if(x%2==0)
printf(“%d “,x);
}
getch();
}
Output:
EVEN NUMBER BETWEEN [1 to 100]
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62
64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
Looping 199
Output:
Input the integer number: 3
Sum of odd numbers between [1 to 3] is: 4
Q15. C Program to Generate and Print Fibonacci Series.
Solution:
/*************************************************************************
FILE NAME: for15.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 4/8/2015
NAME OF THE PROGRAM: C program to generate and print Fibonacci series
*************************************************************************/
#include<stdio.h>
void main(void)
{
int n,j,x=0,y=1,z=0;
printf(“Input the Nth term of Fibonacci series:”);
scanf(“%d”,&n);
printf(“%d %d”,x,y);
for(j=2;j<n;j++)
{
z=x+y;
x=y;
y=z;
200 Concepts and Techniques of Programming in C
printf(“ %d “,z);
}
printf(“\n”);
}
Output:
Input the nth term of Fibonacci series: 5
0 1 1 2 3
Summary
1. Loops are used when a part of the program is executed several times.
2. In while loop the condition is tested before entering the loop. When the condition
becomes false at the starting stage then the loop statements are not executed. It
is called entry-controlled loop.
3. In do while loop the condition is tested at the end of the loop. When the condition
becomes false the statements are executed at least once. It is called exit-controlled
loop.
4. The for loop consists of initialization, test condition and increment/decrement in
a single statement. So it is more preferable than while and do while loops.
Short Questions
1. What is looping in C? And what are the different types of the loop.
2. What is while loop?
3. What is do while loop?
4. What is for loop?
5. What is the difference between while, do while and for loops.
Long Questions
printf(“%d”,++x);
printf(“\n”);
}
Output:
Infinite loop
3. What will be the output?
#include<stdio.h>
void main(void)
{
unsigned int x = 65536;
while(x!= 0)
printf(“%d”,++x);
printf(“\n”);
}
Output:
No output
4. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
while(x<2)
{
x++;
}
printf(“INDIA\n”);
}
Output:
INDIA
5. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
while(++x)
{
printf(“INDIA”);
}
}
Output:
Infinite loop
Looping 203
Output:
I LOVE MY COUNTRY
I LOVE MY COUNTRY
I LOVE MY COUNTRY
I LOVE MY COUNTRY
10. What will be the output?
#include <stdio.h>
void main(void)
{
int x=4;
do
{
printf(“JAI HIND”);
}
while(x<4);
}
Output:
JAI HIND
11. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
while(++x)
{
printf(“INDIA”);
}
}
Output:
INDIA will print infinite times
12. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0;
do
{
printf(“INDIA”);
}
while (x!=0);
}
Output:
INDIA
Looping 205
Output:
INDIA
ODISHA
17. What will be the output?
#include <stdio.h>
void main(void)
{
for(int x=0;x<2;x++)
printf(“INDIA\n”);
}
Output:
INDIA
INDIA
18. What will be the output?
#include<stdio.h>
void main(void)
{
int y=1,z=1;
for(;z;printf(“%d %d\n”,y,z))
{
z=y++<=6;
}
printf(“\n”);
}
Output:
21
31
41
51
61
71
80
19. What will be the output?
#include<stdio.h>
void main(void)
{
short int y=0;
for(y<=5&&y>=-1; ++y; y>0)
printf(“%u”,y);
}
Output:
Infinite loop
Looping 207
9.1 INTRODUCTION
Unconditional statements are the statements used only when the program flows into
another part of the program without checking the test condition. These statements
interrupt the sequential execution of program. The examples of unconditional statements
are: break, goto, continue, exit (0).
TIPS TO REMEMBER
Solution: The break is used with if statement only when the if statement is written
inside the loop.
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 5/8/2015
NAME OF THE PROGRAM: c program to check the number is prime or not by
using the break statement.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,j;
printf(“Input the number:”);
scanf(“%d”,&x);
j=2;
while(j<=x-1)
{
if(x%j==0)
{
printf(“Inputted %d is not a prime”,x);
break;
}
j++;
}
if(j==x)
printf(“Inputted %d is a prime number”,x);
}
Output:
Input the number: 3
Input 3 is a prime number
EXPLANATION:
In the above program when break statement finds then it stops that loop or if statements.
If we remove the break statement then the above program will display both the
statements.
Example:
Input the number: 4
Input 4 is not a prime number
Input 4 is a prime number
The goto statements needs a label in order to search the location where the branching
is to be made. A label is a variable and it must be followed by a colon. The label can
be placed in any position in the program. Basically, it may be placed before the goto
label statement or after the goto label statements. When the label is placed before the
goto label statement then a loop will be generated and the set of statements will be
executed repeatedly. Such jump is called a backward jump. If the label is placed after
the goto label statement then some statements will be skipped and the jump is known
as forward jump.
In case of forward jump, the cursor directly comes to statement-1 after goto label
statement and skips the block of statements. In case of backward jump, statement-1
and block of statements will be executed repeatedly.
TIPS TO REMEMBER
Do not use goto statement in programming. It can be used if any program is difficult
to debug.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
EXPLANATION:
This program is a backward jump goto statement.
Q3. C Program to Find the Odd Number from 1 to 15 using Continue Statements.
Solution:
/*************************************************************************
File Name: Unc3.C
Author Details: Mr. X, 1St Sem, Comp.Sc& Engg., Abc College of Engg.
Date Of Program Execution: 5/8/2015
Name Of The Program: C Program To Find The Odd Number From 1 To 15 Using
continue statements
*************************************************************************/
#include<stdio.h>
void main(void)
{int x;
for(x=1;x<=15;x++)
{
if(x%2==0)
{
continue;
printf(“GCE,KEONJHAR”);
}
else
{
printf(“%d\t”,x);
}
}
}
Output:
1 3 5 7 9 11 13 15
EXPLANATION:
In the above program when 2%2==0 and condition is satisfied and the if condition
execution starts. Since there is no statement before the continue statement in that case
control goes to incremental part and test for next iteration. Here, the printf statement
will not print the message “GCE, KEONJHAR” because that statement is written below
the continue statement.
Q4. C Program of Continue Statement.
Solution:
/*************************************************************************
FILE NAME: unc4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 5/8/2015
NAME OF THE PROGRAM: c program of continue statements
*************************************************************************/
Unconditional Statements 213
#include<stdio.h>
void main(void)
{int x;
for(x=1;x<=15;x++)
{
if(x%2==0)
{
printf(“GCE,KEONJHAR\t”);
continue;
}
else
{
printf(“%d\t”,x);
}
}
}
Output:
1 GCE,KEONJHAR 3 GCEKEONJHAR 5 GCEKEONJHAR 7 GCEKEONJHAR
9 GCEKEONJHAR 11 GCEKEONJHAR 13 GCEKEONJHAR 15
Explanation:
From the above program when 2%2==0 condition is satisfied then execution starts.
Since before the continue statement printf statement is used. So when the reminder of
condition matched with 0 then GCE,KEONJHAR will print then continue statement
continue the loop and control moves to incremental part for next iteration.
Examples:
exit(0);
Q5. Examples of Exit Function.
Solution:
/*************************************************************************
FILE NAME: unc5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
214 Concepts and Techniques of Programming in C
Output:
I LOVE MY INDIA
I AM PROUD TO BE AN INDIAN
EXPLANATION:
In the above examples exit(0) function stops the program execution when it is placed.
So the other message “thanks” is not printed.
Q6. Examples of Exit Function using Function.
Solution:
/*************************************************************************
FILE NAME: unc6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 5/8/2015
NAME OF THE PROGRAM: examples of exit function using function.
*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
void x()
{
printf(“I am user-defined function”);
exit(0);
}
void main(void)
{
x();
printf(“I am main function”);
}
Output:
I am user-defined function
Unconditional Statements 215
SUMMARY
1. The continue statement is used to continue the loop. Those statements which
come after the continue will not execute and those statements which come before
continue will execute.
2. The goto is an unconditional statement which transfers the flow of control to
another part of the program.
3. The break statement is used to terminate the switch statement or loop and
transfers the control to the next statements immediately following that loop or
switch statements.
4. The exit(0) function is used to quit the program.
SHORT QUESTIONS
LONG QUESTIONS
Output:
Compile time error
EXPLANATION:
Continue statement is applied in only loops. Therefore, compilation error
happened.
2. What will be the output?
#include <stdio.h>
void main(void)
{
int x=1;
do
{
x++;
if(x==4)
{
printf(“INDIA”);
continue;
}
}while (x<4);
}
Output:
India
3. What will be the output?
#include <stdio.h>
void main(void)
{
int x=0,y=0;
for(;x<2;x++)
{
for(;y<3;y++)
{
printf(“*\n”);
break;
}
printf(“**\n”);
}
printf(“INDIA\n”);
}
Output:
*
**
*
**
INDIA
Unconditional Statements 217
Output:
Compile time error
7. What will be the output?
#include <stdio.h>
void main(void)
{
printf(“%d “,1);
goto x1;
printf(“%d “,2);
x1:goto x2;
printf(“%d “,3);
x2:printf(“%d “,4);
}
Output:
14
8. What will be the output?
#include<stdio.h>
void main()
{
printf(“%d “,1);
x1:x2:
printf(“%d “,2);
printf(“%d”,3);
}
Output:
123
9. What will be the output?
#include <stdio.h>
void main()
{
printf(“%d “,1);
goto x1;
printf(“%d “,2);
}
void fun()
{
x1 :printf(“3 “, 3);
}
Output:
Compile time error
10. What will be the output?
#include <stdio.h>
int main()
{
Unconditional Statements 219
int x=0,y=0;
while (x < 2)
{
m1 :x++;
while (y<3)
{
printf(“INDIA\n”);
goto m1;
}
}
}
Output:
Infinite loop
11. What will be the output?
#include <stdio.h>
void main()
{
int x=0,y=0;
while(m1:x<2)
{
x++;
while(y<3)
{
printf(“INDIA\n”);
goto m1;
}
}
}
Output:
Compilation error
12. What will be the output?
#include <stdio.h>
void main()
{
int x=1,y=1;
m1:while(x<3)
{
x++;
while(y<4)
{
printf(“INDIA\n”);
goto m1;
}
}
}
Output:
India
India
10
Function
10.1 INTRODUCTION
When a person faces a complex problem then to solve that problem is not an easy task
immediately. It takes some time to solve it. Then one of the easiest methods to solve
that problem is the divide and conquer principle. This principle divides the logic of
the problem into smaller problems and later solves the logic of the smaller problems
individually and then adds all these solutions of smaller problems to get the final
solution. Like that in programming concept, a complex program is divided into different
sub-programs and then each sub-programs is executed separate and sends the result to
the calling function. Such separate parts of sub-programs is called subroutine or function
or user-defined function or module. Thus, a function contains block of statements that
does a particular work/task. A function is also called black box because all the inner
operations inside the user-defined function are invisible to the rest of the program
and return the value to the calling function placed inside the main function. From the
above statements we can differentiate between monolithic programming with modular
programming.
codes without affecting the whole programming code. One module can communicate
with other module of a program in a well defined manner.
Advantages are:
1. It is easy to write a programming code and run.
2. The programming code can further be reused.
3. It reduces programming code.
4. Detecting error in each module is easy then searching error in whole program.
Let us write a C program to display the different laboratories in your college. Then
someone will take time to think. If he writes different laboratories of each dept separately
called module wise, then it will solve within a few seconds.
Suppose college name is: gcekjr and different depts. are: CSE, Electrical, Mechanical,
Civil, Mineral, Mett and Mining. The CSE dept has C programming lab, C++ lab, DBMS
lab, data structure lab, etc., Electrical dept has basic electrical lab, etc., Mechanical
dept has workshop lab, etc., Mineral has mineral processing lab, etc., Mett has metal
processing lab, Civil dept has survey lab then we can write the C program using above
data is
Test Program 1
/*Monolithic Program Execution of Displaying different Laboratories in each Dept
of a College*/
#include<stdio.h>
void main()
{
printf(“This is the example of displaying different labs in each dept of
a college without using function\n”);
printf(“CSE DEPT LABS\n”);
printf(“Data Structure lab\n”);
printf(“C++ programming lab\n”);
printf(“DBMS lab\n\n”);
printf(“MECHINACAL ENGG DEPT LABS\n”);
printf(“workshop lab\n\n”);
printf(“ELECTRICAL ENGG LABS\n”);
printf(“basic electrical lab\n\n”);
printf(“CIVIL ENGG LABS\n”);
printf(“survey lab\n\n”);
printf(“MINERAL ENGG LABS\n”);
printf(“mineral processing lab\n\n”);
printf(“coal preparation lab”);
printf(“particle technology”);
printf(“METT ENGG LABS\n”);
printf(“Metal processing lab\n”);
222 Concepts and Techniques of Programming in C
Test Program 2:
/*Example of C Program Execution of Displaying Different Laboratories in each Dept
of a College using User Defined Function (Module)*/
#include<stdio.h>
void cse(); /*CSE function declaration*/
void mechanical(); /*mechanical function declaration*/
void electrical(); /*electrical function declaration*/
void civil(); /*civil function declaration*/
void mineral(); /*mineral function declaration*/
void mett(); /*mett function declaration*/
void mining(); /*mining function declaration*/
void main() /*Entry point*/
{
printf(“This is the example of displaying different labs in each dept of
a college using function\n”);
cse(); /*calling function*/
mechanical(); /*calling function*/
electrical(); /*calling function*/
civil(); /*calling function*/
mineral(); /*calling function*/
mett(); /*calling function*/
mining(); /*calling function*/
printf(“This is the end of the function”);
}
void cse() /* CSE function definition*/
{
printf(“CSE DEPT LABS\n”);
printf(“c programming lab\n\n”);
printf(“Data Structure lab\n”);
printf(“C++ programming lab\n”);
printf(“DBMS lab\n\n”);
}
void mechanical() /* mechanical function definition*/
{
printf(“MECHINACAL ENGG DEPT LABS\n”);
printf(“workshop lab\n\n”);
}
void electrical() /* electrical function definition*/
{
Function 223
Output:
Different labs in each dept of a college using function
CSE DEPT LABS
C programming lab
Data structure lab
C++ programming lab
DBMS lab
MECHANICAL ENGG DEPT LABS
Workshop
ELECTRICAL ENGG LABS
Basic electrical lab
MINERAL ENGG LABS
Mineral processing lab
METT ENGG LABS
Metal processing lab
MINING ENGG LABS
224 Concepts and Techniques of Programming in C
EXPLANATION:
In the above two program displays the different labs of different depts in a college. Then
if anyone asks why the second program is preferable? The answer is that we put the
different labs individually inside each dept function. And each dept function calculates
individually and sends the value to the main function. By using the user defined
function if any error is found while writing the program then it is easy to detect it
because instead of focusing each line of program the programmer focuses function-wise.
Diagrammatic representation of the above user defined function is:
main()
mining()
cse() mett()
electrical() mineral()
mechanical()
civil()
}
void y() /*function definition*/
{
Function 225
Output:
I AM DHABAL PRASAD SETHI
I COMPLETED MY BTECH CSE FROM BIET, BHADRAK IN 2006
I COMPLETED MY MTECH CSE FROM UTKAL UNIVERSITY IN 2011
Output:
Input the number to find square root: 16.00
226 Concepts and Techniques of Programming in C
EXPLANATION:
Here sqrt() function is a library function used to measure the square root of the input
number.
/*C Program to Find Power of an Integer Number using Library Function*/
#include<stdio.h>
#include<math.h>
void main(void)
{
int x,y,z;
printf(“ C program execution to find power of an integer number using library
function\n”);
printf(“Input the base and exponent:”);
scanf(“%d%d”,&x,&y);
z=pow(x,y);
printf(“The power of integer(base) is:%d”,z);
printf(“\nThis is the end of the program”);
}
Output:
Input the base and exponent: 2 3
The power of integer (base) is: 8
This is the end of the program.
EXPLANATION:
Here pow() function is a library function which measures the power of an integer
number.
TIPS TO REMEMBER
C program has at least one function, which is main () function. There are three basic
functions required to write a simple c program: 1) main(),2) printf();,3) scanf();
three are important to write when the programmer wants to write a modular program
(user-defined function).
TIPS TO REMEMBER
The main() function is called user-defined function because the prototype declaration
of main() function is predefined by compilers in C library and it is defined as the
entry point of the C program.
EXPLANATION:
From the above syntax choose return_type as void or int then write the function name of
your choice then give parentheses and inside parentheses place the number of arguments
you want to use. Each argument consists of again first data type then argument name.
Always remember that the function declaration should end with semicolon and should
be placed above the void main function.
Let’s see an example:
int mul(int x,int y); /* valid function declaration*/
TIPS TO REMEMBER
In function declaration the names of the argument are optional, i.e., you may give
or may not.
EXPLANATION:
Here the above declaration consists of function_name and argument list. Do not write
the data type inside the parentheses of calling function. Write only arguments inside
calling function of the program. The function call should be placed inside the main
function. Therefore, the arguments used in calling function consist of only variables and
not the combination of data-type and variables. Let’s see the example:
void main (void)
{
int x,y,m;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
m=mul(x,y); /*function call*/
printf(“The multiplication of inputted two integer numbers is:%d”,m);
}
Example:
/*User-defined Function mul()*/
int mul (int x,int y) ___________________Function Header
{ ___________________________function body starts
int z; ___________________local variable
z=x*y; __________________ functional statement
return z; _______________________ return statement
} _________________________________function body close
Output:
Input the two integer numbers: 2 3
The multiplication of input two integer numbers is: 6
This the end of the program
Let’s see the above program diagrammatically
EXPLANATION:
In the above diagram the integer values suppose 2,3 is passed through the calling
function mul(2,3); to the called function/user-defined function int mul(2,3)and after
operation done at called function the return function return the value 6 through variable
z to the calling function and that calling function stores that value in variable m. Then
printf function prints the value 6.
Output:
Input the two integer numbers: 10 10
The multiplication of input two integer numbers is: 1000
This is the end of the program
int x,y,m;
int mul(int x,int y); /*function prototype*/
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
m=mul(x,y); /*function call*/
printf(“The multiplication of inputted two integer numbers is:%d”,m);
printf(“\nThis is the end of the program”);
}
/*user-defined function mul */
int mul(int x,int y)
{
int z;
z=x*y;
return z;
}
Output:
Input the two integer numbers: 10 10
The multiplication of these two integer numbers is: 1000
This is the end of the program.
int x,y;
printf(“Input the two integer numbers:”);
scanf(“%d %d”,&x,&y);
x=x+50;
y=y+100;
printf(“After updating the inputted two integer number are:%d %d\n”,x,y);
printf(“This is the end of the program”);
}
Output:
This is the example of function with no argument and no return a value to the calling
function
Input the two integer numbers: 10 20
After updating the inputted two integer numbers are: 60 120
This is the end of the program
Output:
This is the example of function with arguments and no return a value to calling function
Input the two integer numbers: 5 10
234 Concepts and Techniques of Programming in C
Output:
This is an example of function with arguments and returns a single value to the calling
function.
Input the two numbers: 10 4
The subtraction of input two numbers is : 6
This is the end of the program.
int main(void)
{
int x1;
printf(“This the example of function with no arguments and return a value
to calling function\n”);
x1=x(); /*function call*/
printf(“Sum of two numbers is :%d\n”,x1);
printf(“This is the end of the program”);
return 0;
}
int x() /*function definition*/
{
int y,z,m;
printf(“Input two integer numbers:”);
scanf(“%d%d”,&y,&z);
m=y+z;
return(m);
}
Output:
This is an example of function with no argument and returns a value to the calling
function
Input two integer numbers:2 3
Sum of two numbers is: 5
This is the end of the program.
TIPS TO REMEMBER
When the programmer writes a program using user defined function, he should
ensure the number of parameters in the calling function/actual parameter should
match with formal parameters/called function. If the actual arguments are more
than formal parameter then extra arguments in actual arguments are removed.
If the actual arguments are less than formal arguments, then unmatched formal
arguments are initialized to garbage value. Any mismatch in data type may also
result in passing of garbage values.
Q1. C Program to Swap Two Numbers using the Third Variable by Function.
Solution:
/*************************************************************************
FILE NAME: swap.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to swap two numbers using the third variable
by function
*************************************************************************/
#include<stdio.h>
void swap_intnum(int x,int y); /*function prototype*/
void main(void)
{
int x,y,z;
printf(“This is the c program to swap two integer numbers using third
variable by function\n”);
printf(“Input the two numbers :”);
scanf(“%d%d”,&x,&y);
printf(“Before swapping the inputted two numbers is:%d %d\n”,x,y);
swap_intnum(x,y); /*function call*/
printf(“\nThis is the end of the program”);
}
void swap_intnum(int x,int y) /*function definition*/
{
int z;
z=x;
x=y;
y=z;
printf(“After swapping the inputted two numbers is:%d %d”,x,y);
}
Output:
This is a C program to swap two integer numbers using third variable by function
Input the two numbers which is swapped: 2 3
Before swapping the input two numbers is: 2 3
After swapping the input two numbers is: 3 2
This is the end of the program
EXPLANATION:
In the above program the two integer numbers (2, 3) are input through the scanf
function. Then the two numbers are passed through the function swap_intnum
(2, 3).Then two numbers are passed to the called functions. In the called function declared
the third variable as z. First the x value( 2 )is assigned to the third variable z, i.e., memory
of x variable becomes blank then value of y (3) is assigned to x, i.e., x becomes 3 and
then y memory becomes blank. Then z values (2) is assigned to y variable e.g. y becomes
2. Finally x becomes 3 and y becomes 2.
Function 237
Output:
This is a C program to swap two integer numbers without third variable by function
Input the two integer numbers which are to swapped: 2 3
Before swapping the input two integer numbers is: 2 3
After swapping the input two integer numbers is: 3 2
This is the end of the program.
EXPLANATION:
In the above program two values 2 and 3 are input through scanf function and it passes
through the function swap, i.e., swap (2, 3).In the called function we did not use the
third variable. So the logic is x=2+3=5 and the value of y=5-3=2 and then x=5-2=3.so we
get after swapping without third variable x=3 and y=2.
238 Concepts and Techniques of Programming in C
Output:
This is a C program to count the number of digits of an integer number using function
Input the integer number: 123
Number of digits of input integer number is: 3
This is the end of the program.
EXPLANATION:
In the above program of user defined function countdigit(), declare the variable x
and count with initialize it to zero (e.g. count=0). Enter the number 123 through
scanf function. Then apply the logic as while (123>0) then x=123/10=12 and counter
variable increments one, i.e., counter=1. Then in the second iteration while (12>0) then
x=12/10=1 and counter variable increments on e.g. counter =2. In the third iteration
Function 239
while (1>0) then x=1/10=0 and counter=3 then next iteration the while loop condition
does not satisfied and the loop terminates.
Q4. C Program of Sum of Digits of a Number using Function.
Solution:
/*************************************************************************
FILE NAME: sumdigit.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program of sum of digits of a number using function
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void sumdigit(); /*function prototyping*/
void main(void)
{
clrscr();
printf(“This is the c program of sum of digits of a number using function\n”);
sumdigit(); /*function call*/
printf(“\nThis is the end of the program”);
getch();
}
void sumdigit() /*function definition*/
{
int x,sum=0,reminder;
printf(“Input the integer number:”);
scanf(“%d”,&x);
while(x>0)
{
reminder=x%10;
sum=sum+reminder;
x=x/10;
}
printf(“Sum of digits of inputted integer number is:%d”,sum);
}
Output:
This is a C program of sum of digits of a number using function
Input the number: 123
Sum of digits of input integer number is: 6
This is the end of the program.
EXPLANATION:
In the above user-defined function is sumdigit() and inside body is supposed to read
the number 123.
240 Concepts and Techniques of Programming in C
1st Iteration
while(123>0)
Then it goes to the body part of the while loop. Reminder=123%10=3, then
sum=0+3=3, then x=123/10=12
2nd Iteration
while (12>0)
{
reminder=12%10=2
sum=3+2=5;
x=12/10=1
}
3rd Iteration
while(1>0)
{
reminder=1%10=1
sum=5+1=6;
x=1/10=0
}
4th Iteration
Loop terminates
Q5. C Program of Multiplication of Digits of a Number using Function.
Solution:
/*************************************************************************
FILE NAME: multdigit.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program of multiplication of digits of a number
using function
*************************************************************************/
#include<stdio.h>
#include<conio.h>
void muldigit(); /*function prototyping*/
void main(void)
{
clrscr();
printf(“This is the c program of multiplication of digits of an integer
number using function\n”);
muldigit(); /*function call*/
printf(“\nThis is the end of the program”);
getch();
}
void muldigit() /*function definition*/
{
Function 241
int x,mul=1,reminder;
printf(“Input the integer number:”);
scanf(“%d”,&x);
while(x>0)
{
reminder=x%10;
mul=mul*reminder;
x=x/10;
}
printf(“Multiplication of digits of inputted integer number is:%d”, mul);
}
Output
This is a C program of multiplication of digits of an integer number using function
Input the integer number: 234
Multiplication of digits of input integer number is: 24
This is the end of the program.
EXPLANATION:
Follow the above program.
Q6. C Program to Check either Prime Number or Armstrong Number Depending on
the Data Entered by User.
Solution:
/*************************************************************************
FILE NAME: check.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to check either prime number or Armstrong
number depending upon the data entered by user
*************************************************************************/
#include <stdio.h>
#include<conio.h>
int prime(int n); /*function declaration*/
int armstrong(int x); /*function declaration*/
void main(void)
{
char m;
clrscr();
int n,x=0;
printf(“This is the c program to check the number is either prime or
Armstrong \n”);
printf(“Input an integer number: “);
scanf(“%d”,&n);
printf(“[Input X(or x) to check prime]or[ Y(or y) to check Armstrong
number]:”);
242 Concepts and Techniques of Programming in C
m=getche();
if(m==’x’||m==’X’)
{
x=prime(n); /*calling function*/
if(x==1)
printf(“\n The inputted %d is a prime number.”, n);
else
printf(“\nThe inputted %d is not a prime number.”, n);
}
if(m==’Y’||m==’y’)
{
x=armstrong(n); /*calling function*/
if(x==1)
printf(“\nThe inputted %d is an Armstrong number”, n);
else
printf(“\nThe inputted %d is not an Armstrong number”, n);
printf(“\nThis is the end of the program”);
getch();
}
}
int prime(int n) /*prime user-defined function*/
{
int j,c=1;
for(j=2;j<=n/2;++j)
{
if(n%j==0)
{
c=0;
break;
}
}
return(c);
}
int armstrong(int x) /*Armstrong user-defined function*/
{
int s=0,t,r,c=0;
t=x;
while(x!=0)
{
r=x%10;
s=s+(r*r*r);
x=x/10;
}
if(s==t)
c=1;
return(c);
}
Function 243
Output:
This is a C program to check the number is either prime or Armstrong
Input a positive integer number: 2
Input X (or x) to check prime or Y (or y) to check Armstrong number: x
The input 2 is a prime number
This is the end of the program
Q7. C Program to Check Prime Number using Function.
Solution
/*************************************************************************
FILE NAME: checkprime.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to check prime number using function
*************************************************************************/
#include<stdio.h>
int prime(int); /*function declaration*/
void main(void)
{
int x,y;
printf(“This is the c program to check the number is prime or not\n”);
printf(“Input a positive integer number:”);
scanf(“%d”,&x);
y=prime(x); /*function call*/
if(y==1)
printf(“%d is a prime number”,x);
else
printf(“%d is not a prime number”,x);
printf(“\nThis is the end of the program”);
}
int prime(int x) /*function definition*/
{
int i=2;
while(i<=x/2)
{
if(x%i==0)
return 0;
else
i++;
}
return 1;
}
Output:
This is a C program to check the number is prime or not
Input an integer to check prime number: 2
244 Concepts and Techniques of Programming in C
2 is a prime number
This is the end of the program.
Q8. C Program to Check the Prime Number between the Ranges entered by User.
Solution
/*************************************************************************
FILE NAME: checkprime.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to check the prime number between the ranges
entered by user
*************************************************************************/
#include<stdio.h>
int prime(int num); /*function prototype/declaration*/
void main(void)
{
int x,y,i,z;
printf(“This is the c program to check the prime number and the ranges is
entered by user\n”);
printf(“Input two integer numbers(suppose[1-100]): “);
scanf(“%d %d”,&x, &y);
printf(“Prime numbers between inputted [%d and %d] are: “,x,y);
for(i=x+1;i<y;++i)
{
z=prime(i); /*function call*/
if(z==0)
printf(“%d “,i);
}
printf(“\nThis is the end of the program”);
}
int prime(int num) /* User-defined function to check prime number*/
{
int i,z=0;
for(i=2;i<=num/2;++i)
{
if(num%i==0)
{
z=1;
break;
}
}
return(z);
}
Output:
This is a C program to check the prime number and the range is entered by user
Input two integer numbers (suppose [1-100]): 1 30
Function 245
Output:
This is a C program to find HCF and LCM using function
Input two integer numbers: 3 4
246 Concepts and Techniques of Programming in C
Output:
This is a C program to find factorial of a number using function
Input the number to calculate factorial: 5
The factorial of input 5 is: 120
This is the end of the program
TIPS TO REMEMBER
If the programmer does not write the function prototyping then it will run successful
by placing function definition part before main function.
Function 247
Output
Input the two integer numbers: 10 20
After modification the input numbers: a=40, b=40
This is the end of the program.
EXPLANATION:
In the above program, calling function takes variables x and y as arguments are called
actual parameter and in function header variable a and b are called formal parameter.
The actual parameter variable and formal parameter variable may be same or different
but their data type should be same. The input 10 and 20 are passed from calling function
alter(10,20) to called function void alter(10,20) function then 30 is added with 10 and 20
is added with 20 and then updated results are printed through printf function.
TIPS TO REMEMBER
The actual parameter and formal parameter names may be same or different.
The data type, order and number of actual and formal parameter list must be always
same.
248 Concepts and Techniques of Programming in C
Output:
This is the example of pass by value
Input the two integer numbers which are to be swapped: 7 8
Before swapping the input numbers are: 7 8
After swapping the input numbers are: 7 8
This is the end of the program.
Function 249
EXPLANATION:
In the above program the two numbers are not swapped because this is an example of
pass by value. Because x, y are taken as parameters of the calling function swap(x,y);
and the called function parameter x, y, e.g., void swap(int x,int y) are stored in different
memory locations. So there is no connection. But this is possible only in pass by reference.
EXPLANATION:
In the above program we saw swap happened because in pass by reference (pointer) the
calling function parameter and called function parameter are stored in the same memory
location. First stored the value 6 7 and in two variables and after swapping the variables
value changes, i.e., 7 6. So pass by reference is the best for swapping two numbers.
TIPS TO REMEMBER
There are major differences between the pass by value and pass by reference value.
In pass by value, it takes more memory and more time to consume because values
are copied. In pass by reference, it takes less memory and less time because no values
are copied, instead address is passing.
Output:
Sum of x=5 and y=10 are: 15
This is the end of the program.
Function 251
Output:
This is an example of global variable
Sum of x: 12 and y: 8 are: 20
This is the end of the program.
TIPS TO REMEMBER
The benefit of global variable is once the variable is declared never again declared.
But local variable are local to each function.
10.10 RECURSION
Recursion is the process, where a function calls itself, that is, the same function statement
is within function, which calls itself until it terminates. To terminate the recursive
function there should be a base condition. If the base condition is wrong then recursive
function will never end and that function leads to stack overflow error. Therefore,
recursion works on the principle of stack. Stack is the collection of elements where
insertion and deletion are done at a single end. The top is the pointer variable through
which push and pop operations are done. The examples of recursion are evaluations of
factorial of a number, Fibonacci series, GCD of two numbers and many more.
The factorial of a number is calculated as
fact (n)=n*(n-1)*(n-2)-----------1
For example
Factorial of 5=5*4*3*2*1=120
From programming concept of recursion is
fact=n*factorial(n-1);
If n=5 e.g fact=5*factorial(4); will be evaluated.
252 Concepts and Techniques of Programming in C
int factorial(int x)
{
if(x==0)
return(1);
else
return(x*factorial(x-1));
}
EXPLANATION:
Form the above program if x=4
Then inside the function factorial (int x); there is a same function marked in bold letters
again which calls itself, i.e., factorial (3) calls itself until it terminates. As a result the
factorial of 4 is 4*3*2*1=24.The base condition is 0 for termination.
Output:
Input the integer number: 5
Function 253
EXPLANATION:
Here in the program the user enters the number 5 then the value 5 goes to the parameter
of calling function, i.e., factorial (5).Then that value is passed to the function definition,
i.e., in the parameter of called function. In the called function, since 5 is not equal to 0
then it goes to the else part. In the else part the function calculated is as 5*factorial (4);
since this program is using recursion. Then next parameter value of function header is
4 and continue the next step until it reaches the termination condition, i.e., 0. Thus, the
result of factorial of 5 is 5*4*3*2*1=120.
Q2. C Program to Find the Fibonacci Series using Recursive Function.
Solution:
/*************************************************************************
FILE NAME: recursion.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTE: 7/8/2015
NAME OF THE PROGRAM: C program to find the Fibonacci series using recursive
function
*************************************************************************/
#include<stdio.h>
int fibonacci(int x); /*function declaration*/
void main(void)
{
int x,y;
printf(“This is the c program to find the Fibonacci series using recursive
function\n”);
printf(“Input the number of terms:”);
scanf(“%d”,&x);
printf(“The Fibonacci series are:”);
for(int m=0;m<x;m++)
{
y=fibonacci(m); /*function call*/
printf(“%d\t”,y);
}
printf(“\nThis is the end of the program”);
}
int fibonacci(int x)/*function definition*/
{
if(x==0)
return(0);
if(x==1)
return(1);
else
return(fibonacci(x-1)+fibonacci(x-2));
}
254 Concepts and Techniques of Programming in C
Output:
Input the number of terms: 5
The Fibonacci series are: 0 1 1 2 3
This is the end of the program.
Q3. C Program to Find Gcd of Two Numbers using Recursive Function.
Solution:
/*************************************************************************
FILE NAME: gcd.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to find GCD of two numbers using recursive
function
*************************************************************************/
#include<stdio.h>
int gcd_integer(int x,int y); /*function prototype*/
void main(void)
{
int x,y,z;
printf(“This is the c program to find GCD of two numbers using recursion\n”);
printf(“Input the two integer numbers whose GCD is to find:”);
scanf(“%d%d”,&x,&y);
z=gcd_integer(x,y);/*function call*/
printf(“The GCD of inputted two integer numbers is:%d”,z);
printf(“\nThis is the end of the program”);
}
int gcd_integer(int x,int y) /*function definition*/
{
int z;
if(x%y==0)
return(y);
else
z=gcd_integer(y,(x%y));
return(z);
}
Output:
Input the two integer numbers whose GCD is to find: 3 4
The GCD of input two integer numbers is: 1
This is the end of the program.
EXPLANATION:
Here this program finds the greatest common divisor of two integer numbers using
recursion. Here the user inputs the two integer number 3 and 5. Then it goes to the
parameter of the calling function, i.e., gcd(5,6); then that values goes to the parameter
of function header.
Function 255
TIPS TO REMEMBER
z=gcd(y,(x%y));
return z;
Instead of the above two lines we can write return(gcd(y,x%y));
Output:
Input a sentence/string: dhabal
labahd
This is the end of the program.
256 Concepts and Techniques of Programming in C
Q5. C Program to Find Sum of the First nth Natural Number E.G. 1+2+3----N=N(N+1)/2
using Recursion.
Solution:
/*************************************************************************
FILE NAME: rev.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to find sum of first nth natural number e.g.
1+2+3----n=n(n+1)/2 using recursion
*************************************************************************/
#include<stdio.h>
int sum(int x); /*function declaration*/
void main(void)
{
int x,y;
printf(“This is the c program to find sum of first nth natural number[1+2+3-
----n=n(n+1)/2]\n”);
printf(“Input the nth term:”);
scanf(“%d”,&x);
y=sum(x); /*function call*/
printf(“The sum of inputted 1 to nth term is:%d”,y);
printf(“\nThis is the end of the program”);
}
int sum(int x) /*function definition*/
{
if(x==0)
return x;
else
return x+sum(x-1);
}
Output:
Input the nth term: 5
The sum of input 1 to nth term is: 15
This is the end of the program.
Q6. C Program of Sum of Digits of a Integer Number using Recursion.
Solution:
/*************************************************************************
FILE NAME: sumdig.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program of sum of digits of a integer number using
recursion
*************************************************************************/
Function 257
#include<stdio.h>
int sum_integer_digit(int x); /*function declaration*/
void main(void)
{
int x,y;
printf(“This is the c program of sum of digits of an integer number using
recursion\n”);
printf(“Input an integer number:”);
scanf(“%d”,&x);
y=sum_integer_digit(x); /*function call*/
printf(“Sum of digits of inputted integer number is:%d”,y);
printf(“\nThis is the end of the program”);
}
int sum_integer_digit(int x) /*function definition*/
{
if(x==0)
return(0);
else
return(x%10)+sum_integer_digit(x/10);
}
Output:
This is a C program of sum of digits of an integer number using recursion
Input a number: 123
Sum of digits of input integer numbers is: 6
This is the end of the program.
Q7. C Program to Count the Total Number of Digits of an Integer Number using
Recursion.
Solution:
/*************************************************************************
FILE NAME: countdig.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM:C program to count the total number of digits of an
integer using recursion
*************************************************************************/
#include<stdio.h>
int countdigits_intnum(int x); /*function prototype*/
void main(void)
{
int n,m;
printf(“This is the c program to count the total number of digits of an
integer number using recursion\n”);
printf(“Input an integer number:”);
scanf(“%d”,&n);
m=countdigits_intnum(n); /*function call*/
258 Concepts and Techniques of Programming in C
Output:
This is a C program to count the total number of digits of an integer number using
recursion.
Input an integer number: 123
Total number of digits of input integer number is: 3
This is the end of the program.
Q8. C Program to Find Factorial of two Integer Numbers Simultaneously using
Recursive Function.
Solution:
/*************************************************************************
FILE NAME: fact1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM:C program to find factorial of two integer numbers
simultaneously using recursive function.
*************************************************************************/
#include<stdio.h>
int factorial(int b); /*function prototype*/
void main(void)
{
int x,y,f1,f2;
printf(“This is the c program to find factorial of two integer numbers
simultaneously using recusion\n”);
printf(“Input two integer numbers:”);
scanf(“%d %d”,&x,&y);
f1=factorial(x); /*function call*/
f2=factorial(y); /*function call*/
printf(“The factorials of inputted two integer numbers simultaneously are:%d
%d”,f1,f2);
printf(“\nThis is the end of the program”);
}
Function 259
Output:
Input the two integer numbers: 3 4
The factorials of input two integer numbers simultaneously are: 6 24
This is the end of the program.
Q9. C Program to Convert Decimal to Binary Equivalent using Recursion.
Solution:
/*************************************************************************
FILE NAME: bin.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to convert decimal to binary equivalent
using recursion
*************************************************************************/
#include<stdio.h>
long binary(int);/*prototype declaration*/
void main(void)
{
long m;
int x;
printf(“This is the c program to convert decimal to binary using recursion\n”);
printf(“Input the decimal number: “);
scanf(“%d”,&x);
m=binary(x); /*calling function*/
printf(“Binary representation of inputted decimal number is: %ld”,m);
printf(“\nThis is the end of the program”);
}
long binary(int y)/*function definition*/
{
static long m,remainder,f= 1;
if(y!= 0)
{
remainder =y% 2;
m= m+ remainder * f;
f= f*10;
binary(y/ 2);
}
return m;
}
260 Concepts and Techniques of Programming in C
Output:
Input the decimal number: 12
Binary representation of input decimal number is: 1100
This is the end of the program.
Q10. C Program to Check a Number is Prime Number or not by Recursion.
Solution:
/*************************************************************************
FILE NAME: prime.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: C program to check a number is prime number or not
by recursion
*************************************************************************/
#include<stdio.h>
int prime(int,int);/*prototype declaration*/
void main(void)
{
int x,y;
printf(“This is the c program to check a number is prime or not using
recursion\n”);
printf(“Input a positive integer number: “);
scanf(“%d”,&x);
y= prime(x,x/2);/*function call*/
if(y==1)
printf(“The inputted %d is a prime number”,x);
else
printf(“The inputted %d is not a prime number”,x);
printf(“\nThis is the end of the program”);
}
int prime(int num,int i)/*function definition*/
{
if(i==1)
{
return 1;
}
else if(num%i==0)
return 0;
else
prime(num,i-1);
}
Output:
Input a positive integer number: 3
The input 3 is a prime number
This is the end of the program.
Function 261
TIPS TO REMEMBER
In a function, the return statement returns only one value to the calling function at
a time.
Output:
Input the two integer numbers: 3 4
GCD of input 3 and 4 is: 1
LCM of input 3 and 4 is: 12
This is the end of the program.
262 Concepts and Techniques of Programming in C
Output:
Input the number of disks: 2
The sequence of disk moves in the Tower of Hanoi is:
Move disk1 from[ S to T]
Move disk2 from[ S to D]
Move disk1 from[ T to D]
This is the end of the program.
EXPLANATION:
Tower of Hanoi is a mathematical puzzle where there should have three rods and
n disks. The objective of the puzzle is to move the entire stack to another rod, by
following the simple rules:
1. Only one disk can be moved at a time.
Function 263
2. Each move consists of taking the upper disk from one of the stacks and placing it
onto the top of another stack, i.e., a disk can only be moved if it is the uppermost
disk on a stack.
3. No disk may be placed on top of a smaller disk.
In the above program num is the number of disks on source rod s. We can solve
it for n=1 and n=2.
So here we presented S is the source rod, T is the temporary rod and D is the destination
rod.
When n=1
The disk is place:
S------>D
When n=2
The disk is placed:
S----->T
S----->D
T----->D
When n=3
The disk is placed:
S--->D
S---->T
D----->T
S------>D
T------->S
T------->D
S------->D
Output:
This is an example of auto variable
The values of x are: 0 0 0
This is the end of the program.
EXPLANATION:
The input of the first, second and third iterations is 0 because auto variable is initialized
each time.
void main(void)
{
int x;
printf(“This is the example of static variable\n”);
printf(“The values of x are:”);
for(x=1;x<4;x++)
{
z();
}
printf(“\nThis is the end of the program”);
}
void z()
{
static int x=0;
printf(“ %d “,x);
x=x+1;
}
Output:
This is an example of static variable
The values of x are: 0 1 2
This is the end of the program.
EXPLANATION:
During the first call x=0, second call x=1, third call x=2. Because if once the static variable
is initialized it is never initialized again. The next will be incremented until termination.
Output:
This is an example of register variable
The values of x are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
This is the end of the program.
Output:
This is an example of external variable
20 10
This is the end of the program.
/*Another Examples of External Variables*/
#include <stdio.h>
extern int x,y;
extern int z;
extern float f;
void main (void)
{
int x,y;
int z;
float f;
x= 10;
y= 20;
z= x+ y;
printf(“value of z is: %d \n”,z);
f = 40/2.0;
printf(“value of f is : %f”,f);
printf(“\nThis is the end of the program”);
}
Function 267
Output:
Value of z is: 30
Value of f is: 20.00
This is the end of the program.
Comparison between four variables.
SUMMARY
SHORT QUESTIONS
Important QUESTIONS
LONG Questions
1. Explain the formal parameters and actual parameters with suitable example.
2. Define different types of user-defined functions with suitable examples.
3. What is parameter passing technique? Explain pass by value and pass by reference
with suitable examples.
4. What is the scope of a variable? Explain local variable and global variable with
suitable examples.
5. What is recursion? Write a C program to find factorial of a number.
6. Write a C program to find GCD and LCM of two numbers using recursive
function.
7. Write a C program to find Fibonacci series using recursion.
8. Write a C program to swap two numbers using third variable by function.
9. Write a C program to swap two numbers without a third variable.
10. Write a C program to count the number of digits of a number using function.
11. Write a C program of sum of digits of a number by function.
12. Write a C program of multiplication of digits of a number by sung function.
13. Write a C program to check either Palindrome or Armstrong number depending
on the data entered by user.
14. Write a C program to check the prime number between the ranges entered by the
user.
15. Write a C program to find HCF and LCM by using function.
16. Write a C program to reverse a string using recursion.
17. Write a C program to find the sum of nth natural numbers using recursion.
18. Write a C program of sum of digits of a number using recursion.
19. Write a C program to count the total number of digits using recursion.
20. Write a C program to find factorial of two integer numbers simultaneously using
recursion.
21. Write a C program to convert decimal to binary using recursion.
22. Write a C program to check a number is prime or not using recursion.
23. Write a C program to find HCF and LCM using recursion.
int x;
x=z(30);
printf(“%d”,x);
}
Output:
Compilation error
EXPLANATION:
The program gives compilation error because return statement is used in
conditional expression. Therefore, whenever writing a C program avoid return
statement in conditional expression.
2. Point out the error in the program
m(int x, int y)
{
int x;
x = 10;
return x;
}
Output:
Compilation error
3. What will be the output?
#include<stdio.h>
void z();
void main(void)
{
int x=10;
z();
}
void z()
{
printf(“INDIA”);
}
Output:
India
4. What will be the output?
#include<stdio.h>
void main(void)
{
int z();
int x;
x=z();
printf(“%d”,x);
}
Function 271
int z()
{
int m=2000;
return(m);
}
Output:
2000
5. What will be the output?
#include<stdio.h>
void fun(int*x, int*y);
void main(void)
{
int x=10,y=20;
fun(&x,&y);
printf(“%d,%d”,x,y);
}
void fun(int *x,int *y)
{
*x = *x**y;
*y = *y**y;
}
Output:
200, 400
6. What will be the output?
#include<stdio.h>
int rev(int y);
void main(void)
{
int x=20;
rev(x);
}
int rev(int y)
{
if(y == 0)
return 0;
else
printf(“%d,”,y);
rev(--y);
}
Output:
20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
7. What will be the output?
#include<stdio.h>
int sumdig(int);
272 Concepts and Techniques of Programming in C
void main(void)
{
int a,b;
a=sumdig(123);
b=sumdig(120);
printf(“%d, %d\n”,a,b);
}
int sumdig(int x)
{
int s,d;
if(x!=0)
{
d=x%10;
x=x/10;
s=d+sumdig(x);
}
else
return 0;
return s;
}
Output:
6, 3
8. What will be the output?
#include<stdio.h>
void main(void)
{
int x=10,y=20,p,q;
p=add(x,y);
q=add(x,y);
printf(“%d %d”,p,q);
}
add(int a,int b)
{
a+=a;
b+=b;
return(a);
return(b);
}
Output:
Compilation error
9. What will be the output?
#include<stdio.h>
int fun(int n);
void main()
{
int x;
x=fun(5);
Function 273
printf(“%d”,x);
}
int fun(int n)
{
int x=1,k;
if(n==1)
return x;
for(k=1;k<n;++k)
x=x+fun(k)*fun(n-k);
return x;
}
Output:
51
MULTIPLE-Choice QUESTIONS
1. The keyword used to transfer control from an user defined function to the calling
function is
(a) switch (b) goto (c) go back (d) return
[Answer: d]
The keyword return is used in user-defined function to return back the values to
the calling function.
2. What is the notation for following functions?
1. int f(int a, float b)
{
}
2. int f(a, b)
int a; float b;
{
}
(a) KR Notation
ANSI Notation
(b) Pre ANSI C Notation
KR Notation
(c) ANSI Notation
KR Notation
(d) ANSI Notation
Pre ANSI Notation
[Answer: c]
KR Notation means Kernighan and Ritchie Notation.
274 Concepts and Techniques of Programming in C
11.1 INTRODUCTION
Using fundamental data types (int, char, float, double), a single variable of these types
can store only one value at a given time. When many times a single variable is assigned
the different values then what values the variable will hold? Let’s see the example
below and see the output.
#include<stdio.h>
void main(void)
{
int z;
z=10;
z=20;
z=30;
printf(“Value of z is:%d”,z);
}
Output:
Value of z is: 30
EXPLANATION:
From the above example the question arises how the value of z becomes 30? When
same variable is assigned many values, i.e., first 10 is assigned to variable z then 20 is
assigned to z and then 30 is assigned to z then one can get confused that what will be
the output? The solution of the above example is first 10 is assigned to variable z, so
10 is stored in variable z and then when 20 is assigned to the same variable z at that
time old value of z is lost and new value 20 is stored in variable z and last when 30
is assigned to variable z at that time again old value is lost. This is because a single
variable can store only one value at a time. Finally, 30 becomes value of variable z.
276 Concepts and Techniques of Programming in C
Then a if programmer wants to store the above three values and display them then
he can use three different variables.
Let’s see the example
#include<stdio.h>
void main(void)
{
int x,y,z;
x=10;
y=20;
z=30;
printf(“Value of x is:%d\n”,x);
printf(“Value of y is:%d\n”,y);
printf(“Value of z is:%d”,z);
}
Output:
Value of x is:10
Value of y is:20
Value of z is: 30
EXPLANATION:
In the above example three values are assigned to individual variables and then print
its values by using printf() function. By following the above concepts and techniques,
if a programmer wants to store 1000 values and display them he will create 1000
variables to store the values. So it creates problem for the programmer. To solve the
problem array can be used.
In arrays, instead of creating 1000 variables of same type to store 1000 values, the
programmer will create only one variable and it will store 1000 or more values. How
can it be possible for a beginner? To get the solution follow the Q1 in some useful
programming examples of one-dimensional array. Thus, array is the fixed-size series
of variables of same data type.
TIPS TO REMEMBER
• The derived data type array can also be called subscripted variables.
• The definition of array is: it is the fixed series of variables of same data type and
size by giving a name.
• Another definition, an array is the collection of elements of same type and size
and by using it we can create a common variable and that variable holds many
values called array.
• The array elements are generally stored in contiguous memory location.
Array 277
Explanation:
In the above syntax data type determines the type of elements/values that the array
will store. It may be integer type, float type, char type or double type. The variable_
name is the name of the array and last size specifies the maximum number of elements
that the array can store.
Example 1:
int marks[50];
EXPLANATION:
This declaration specifies that marks variable stores 50 student’s marks of a particular
subject. The individual element/value of marks is called array elements, e.g., marks[0]
will store one values and marks[1] stores another values till marks[49].
Here int specifies data type of the array, marks is the name of the array, [50] represents
the size of the array is 50. The symbol square bracket [] used in array is called array
indices or subscript.
278 Concepts and Techniques of Programming in C
TIPS TO REMEMBER
When the array is declared the elements of the array contain garbage values at that
time.
Size used in array may be a numeric constant or a symbolic constant.
Example 2:
int marks[4]={40,45,50,55};
EXPLANATION:
This declaration tells that the variable marks as an array of size 4 and thus the values 40,
45, 50, 55 are stored in each variable or an array element. Let’s see how the initialized
values are stored in consecutive memory location of array marks. Suppose the base
address of array is100 then each location will take 2 bytes of memory. Because array
name marks is int type whose size is 2 bytes. So the memory addresses are 100, 102,
104, 106.
Example 3:
int marks[4]={40,45};
EXPLANATION:
In the above example marks variable creates 4 memory locations. But two values
are initialized. So the first elements are stored in the first memory locations and the
second element is stored in the second memory locations and the remaining values
are stored in other memory locations. Third memory and fourth memory locations
will automatically store the value zero. Let us see the above example in tabular form.
Array 279
TIPS TO REMEMBER
Sets of values are stored in a single variable name given by the programmer using a
single data type from fundamental data types is called as an array. Thus, array can
store large number of elements by same type.
The individual value in the array is called array element.
The position of each array element in the array is called the array index/subscript.
In one-dimensional array, the array index starts with the value zero and last maximum
size minus one.
TIPS TO REMEMBER
When an array is declared without initialization the total array contains the garbage
value. But suppose when the array size is 4 but one element is initialized then rest
of memory locations default assigned to zero.
Output:
The marks of student [0] is: 30
The marks of student [1] is: 35
The marks of student [2] is: 40
The marks of student [3] is: 45
EXPLANATION:
The above program is initialization of one-dimensional array. Here 30, 35, 40, 45
are assigned to array named marks, e.g., marks[0]=30,marks[1]=35,marks[2]=40,
marks[3]=45. The for loop is used to display each initialized value.
TIPS TO REMEMBER
A good programmer should try to define symbolic constant as the size of the array.
Q2. C Program to Insert the Elements into the Array and Display It.
Solution:
/*************************************************************************
FILE NAME: array2.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program to insert the elements into the array and
display it
*************************************************************************/
#include<stdio.h>
#define M 3
void main(void)
{
int x[M],y;
for(y=0;y<M;y++)
{
printf(“Input the elements of the array x[%d]:”,y);
scanf(“%d”,&x[y]);
}
for(y=0;y<M;y++)
{
printf(“The inputted elements of the array x[%d] is:%d\n”,y,x[y]);
}
}
Output:
Input the elements of the array x[0]:5
Input the elements of the array x[1]:6
Input the elements of the array x[2]:7
Array 281
EXPLANATION:
Here in the above program, instead of fixing the size of the array we have used symbolic
constant, M, i.e., size of the array is 3. We cannot store more than 3 elements in the above
array. Then we have input the elements through scanf() function by using for loop.
Then using for loop and printf() function we have displayed the elements of the array.
Instead of using the symbolic constant we can alternatively write the same program.
Let’s see the same program.
#include<stdio.h>
void main(void)
{
int x[100],y,n;
printf(“Input the size of the array:”);
scanf(“%d”,&n);
for(y=0;y<n;y++)
{
printf(“Input the elements of the array x[%d]:”,y);
scanf(“%d”,&x[y]);
}
for(y=0;y<n;y++)
{
printf(“The inputted elements of the array x[%d] is:%d\n”,y,x[y]);
}
}
Output:
Input the size of the array: 3
Input the elements of the array: 3 4 5
The sum of elements of the array is:12
The average of input array elements is: 4.000000
EXPLANATION:
Here, suppose the user input the size of the array, i.e., 3. Then the user input the
elements of the array by using scanf function and for loop. Then using the for loop
we have stored each individual element into the variable sum till j<3. When j value
becomes 3 the loop terminates and then divide the sum with the size of the array and
store the results in the variable avg and the printf statement prints that average value.
Q4. C Program to Find the Largest Number Among N Numbers.
Solution:
/*************************************************************************
FILE NAME:array4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: C program to find largest number among N numbers
*************************************************************************/
#include <stdio.h>
void main(void)
{
int x[10],j,y,n;
printf(“Input the size of the array:”);
scanf(“%d”,&n);
printf(“Input the elements of the array:\n”);
for (j=0;j<n;j++)
{
scanf(“%d”,&x[j]);
}
Array 283
y=x[0];
for(j=1;j<n;j++)
{
if (x[j]>y)
y=x[j];
}
printf(“\The largest element among inputted array elements is:%d”,y);
}
Output:
Input the size of the array: 4
Input the elements of the array
2 7 1 14
The largest element among input array elements is: 14
EXPLANATION:
Here the objective of the program is to find the largest element among the array. Here,
the user enters the size of the array, suppose 4 then he will input the elements of the
array through scanf() function and for loop. Then suppose x[0] value is assigned to the
larger variable. To find the largest among the array elements, the next step is to initialize
the variable j= 1 in for loop and check the condition 1<4. Since it satisfies execute the
loop and inside the for loop we have used the if condition to measure between x[1]
and larger, if(x[1]>larger) e.g. 7>1 then larger=7. Next loop increments to 2 and inside
the loop again test the condition as if(x[3]>larger) e.g. 14>7 yes condition satisfied,
therefore larger=14 and next loop increments to 4. As the maximum size of loop is 4,
therefore loop terminates.
Q5. C Program to Find Smallest Elements in One-Dimensional Array.
Solution:
/*************************************************************************
FILE NAME: array5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program to find smallest elements in one dimensional
array.
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main(void)
{
int x[100],y,n,i,loc=1;
clrscr();
284 Concepts and Techniques of Programming in C
Output:
Input the size of the array: 3
Input 3 elements of the array: 3 8 1
Smallest elements is present at location [3] and the value is: 1
EXPLANATION:
Adopt the largest number among three using array explanation.
Q6. C Program to Generate the Fibonacci Series of N Numbers using Array.
Solution:
/*************************************************************************
FILE NAME: array6.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program to generate the Fibonacci series of n
numbers using array
*************************************************************************/
#include<stdio.h>
#define M 5
void main(void)
{
int fib[M];
int x;
fib[0]=0;
fib[1]=1;
for(x=2;x<M;x++)
{
Array 285
fib[x]=fib[x-1]+fib[x-2];
}
printf(“The Fibonacci series are:”);
for(x=0;x<M;x++)
{
printf(“%d\t”,fib[x]);
}
}
Output:
The Fibonacci series are: 0 1 1 2 3
EXPLANATION:
Here we have mentioned the symbolic constant #define M 5. It means instead of 5 we
have given named it M. So M is the substitute name of 5. In that program first two
values are initialized as 0 and 1 and are stored in two array elements. The size of fib
array is 5. Then for loop starts with index 2 and it increments till 4 because it is less
than 5. When x=2 and 2<5 the fib[2]=fib[2-1]+fib[2-2], i.e., fib[2]=fib[1]+fib[0] and the
for loop works till condition is satisfied. When the loop terminates for loop is again
used to display the Fibonacci series.
Q7. C Programs of Reverse the Array.
Solution:
/*************************************************************************
FILE NAME: array7.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: C program of reverse the array
*************************************************************************/
#include <stdio.h>
#include<conio.h>
void main(void)
{
int x[100],y[100],n,i,j;
clrscr();
printf(“Input the size of the array:”);
scanf(“%d”,&n);
printf(“Input the elements of the array:”);
for (i=0;i<n;i++)
scanf(“%d”,&x[i]);
for (i=n-1,j=0;i>=0;i--,j++)
{
y[j]=x[i];
}
for(i=0;i<n;i++)
{
286 Concepts and Techniques of Programming in C
x[i]=y[i];
}
printf(“The Reverse of inputted array elements are:”);
for(i=0;i<n;i++)
{
printf(“ %d “,x[i]);
}
getch();
}
Output:
Input the size of the array: 4
Input the elements of the array: 2 3 4 5
The reverse of input array elements are: 5 4 3 2
Output:
The array elements are: 20, 31, 42
Array 287
Explanation:
Here in the above program the individual element x[0],x[1],x[2] are passed from the
calling function display(); to the called function void display(int a,int b,intc){ }.
Output:
The array elements are: 20,31,42
Explanation:
Here three elements x[0],x[1] and x[2] are passed from the calling function by using the
address operator with each element to the called function and in the called function
three pointer variables are declared which hold the address of each element and in the
end last using dereferencing operator we can print the each individual element.
Output:
The sum of the array elements is 550
Explanation:
Here in the above program the array name is passed for the entire array instead of
individual array element.
Q11. C Program to Find the Greatest Number Among Array Elements using Function.
Solution:
/*************************************************************************
FILE NAME: hcf.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 7/8/2015
NAME OF THE PROGRAM: c program to find greatest number among array elements
using function.
*************************************************************************/
#include <stdio.h>
int max_num(int z[],int n); /* function prototype */
void main()
{
int z[100],i,x,m;
printf(“Input the size of the array:”);
scanf(“%d”,&m);
printf(“Input the elements of the array:”);
for(i=0;i<m;++i )
Array 289
scanf(“%d”,&z[i]);
x=max_num(z,m); /*function call*/
printf(“Greatest number among the array is:%d\n”,x);
}
int max_num(int z[],int m) /*function definition*/
{
int big,i;
big=z[0];
for(i=1;i<m;++i )
if(z[i]>big)
big=z[i];
return(big);
}
Output:
Input the size of the array: 3
Input the elements of the array: 3 2 10
Greatest number among the array is: 10
Explanation:
Here in the above program all the array elements are passed by using pass by value
method so array name z and size m is passed inside the calling function max_num(); to
called function then inside called function we declare the variable big which holds the
first element by assigning z[0] to big variable and using for loop we compare the second
element of the array to size-1 element with first element. and if the array element is
greater than big variable value then find the greater number else big variable assigning
first element is the greatest.
Output:
Value of x[0] is:10
Value of x[1] is:20
Value of x[2] is:30
Value of x[3] is:40
Value of x[4] is:50
Example:
int marks[3][3];
EXPLANATION:
In the above example the first index stores the row and the second index stores the
column, i.e., marks variable holds 3 rows and 3 columns.
Let us first see the two-dimensional representation of marks variables.
Example:
int marks[3][3]={30,35,40,45,50,55,60,65,70};
Or
int marks[3][3]={{30,35,40},{45,50,55},{60,65,70}};
Or
int marks[3][3]={
{30,35,40}
{45,50,55}
{60,65,70}
};
30 35 40
45 50 55
60 65 70
pass(x[0]);
}
void pass(int x[])
{
int m;
for(m=0;m<3;m++)
printf(“%d “,x[m]*15);
}
Output:
15 30 45
Output:
123456789
#include<stdio.h>
void main(void)
{
int x[20][20],y[20][20],z[20][20],i,j,k,l;
printf(“Input the number of rows and columns of the two matrices:”);
scanf(“%d%d”,&k,&l);
printf(“Input the elements of the first matrix:\n”);
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
scanf(“%d”,&x[i][j]);
}
}
printf(“Input the elements of the second matrix:\n”);
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
scanf(“%d”,&y[i][j]);
}
}
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
z[i][j]=x[i][j]+y[i][j];
}
}
printf(“The addition of inputted two matrices is:\n”);
for(i=0;i<k;i++)
{
for(j=0;j<l;j++)
{
printf(“%d\t”,z[i][j]);
}
printf(“\n”);
}
}
Output:
Input the number of rows and columns of the two matrices: 2 2
Input the elements of the first matrix:
3 4
2 3
Input the elements of the second matrix:
5 6
1 2
294 Concepts and Techniques of Programming in C
printf(“\n”);
}
}
Output:
Input the number of rows and columns of the two matrices: 2 2
Input the elements of the first matrix:
23
23
Input the elements of the second matrix:
23
23
Subtraction of two input matrices is:
0 0
0 0
Q3. C Program of Multiplication of Two Matrices.
Solution:
/*************************************************************************
FILE NAME: twoarray3.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program of multiplication of two matrices
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x[10][10],y[10][10],z[10][10],i,j,k,row1,row2,col1,col2;
printf(“Ensure that number of columns of the first matrix should match number
of rows in the second matrix\n”);
printf(“Input the number of rows and columns of the first matrix:”);
scanf(“%d%d”,&row1,&col1);
printf(“Input the number of rows and columns of the second matrix:”);
scanf(“%d%d”,&row2,&col2);
if(col1!=row2)
printf(“Multiplication is not possible”);
printf(“Input the elements of the first matrix:\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&x[i][j]);
}
}
printf(“Input the elements of the second matrix:”);
for(i=0;i<row2;i++)
296 Concepts and Techniques of Programming in C
{
for(j=0;j<col2;j++)
{
scanf(“%d”,&y[i][j]);
}
}
/*multiplication done*/
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
z[i][j]=0;
for(k=0;k<row2;k++)
{
z[i][j]=z[i][j]+x[i][k]*y[k][j];
}
}
}
printf(“The multiplication of two inputted matrices is:\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col2;j++)
{
printf(“\t%d”,z[i][j]);
}
printf(“\n\n”);
}
}
Output:
Ensure the number of columns of the first matrix should match the number of rows of
the second matrix.
Input the number of rows and columns of the first matrix: 2 2
Input the number of rows and columns of the second matrix: 2 2
Input the elements of the first matrix:
23
24
Input the elements of the second matrix:
25
37
The multiplication of two input matrices is:
13 31
16 38
Array 297
Output:
Input the number of rows and columns of the matrx: 2 3
Input the elements of the matrix:
1 3 4
4 5 6
298 Concepts and Techniques of Programming in C
TIPS TO REMEMBER
1. The transpose of the matrix is defined as the matrix that is obtained by
interchanging the rows of a matrix to columns. If the matrix is of the order m*n
then transpose of the matrix will be n*m.
2. In matrix multiplication, the number of columns in the first matrix should be
equal to the number of rows in the second matrix. Each row of the first matrix is
multiplied with the columns of the second matrix then added to get the element
of the result.
sum=sum+x[i][j];
}
}
}
printf(“Sum of diagonal of inputted matrix is:%d”,sum);
}
Output:
Input the number of rows and columns of a matrix: 2 2
Input the elements of the matrix:
2 3
2 3
Sum of diagonal of input matrix is: 5
Q6. C Program to Find Determinants of the N*N Matrix.
Solution
/*************************************************************************
FILE NAME: twoarray5.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 8/8/2015
NAME OF THE PROGRAM: c program to find determinants of the n*n matrix
*************************************************************************/
#include <stdio.h>
void main(void)
{
int m[3][3],x,y=0,i,j;
printf(“Input the order of the matrix(2*2/3*3):”);
scanf(“%d”,&x);
if (x<2||x>3)
{
printf(“You have inputted invalid value\n”);
}
printf(“Input the elements of the matrix\n”);
for (i=0;i<x;i++)
for (j=0;j<x;j++)
scanf(“%d”,&m[i][j]);
if (x==2)
{
y=(m[0][0]*m[1][1])-(m[0][1]*m[1][0]); /* calculatation of determinant of
the 2 x 2 matrix */
}
else if(x==3)
{
/* calculation of determinant of the 3 x 3 array */
y=(m[0][0]*m[1][1]*m[2][2])-(m[0][0]*m[2][1]*m[1][2])-(m[0][1]*m[1]
[0]*m[2][2])+
300 Concepts and Techniques of Programming in C
(m[0][1]*m[2][0]*m[1][2])+(m[0][2]*m[1][0]*m[2][1]) -(m[0][2]*m[1][1]*m[2]
[0]);
}
printf(“The Determinant of the inputted matrix is:%d”,y);
}
Output:
Input the order of the two-dimensional array (2*2/3*3):2
Input the elements of two-dimensional array
3 4
2 8
The determinant of the input matrix is: 16
This syntax described that the first subscript of the array contains number of tables
and second number of rows and third number of column.
Example:
int a[3][2][2];
EXPLANATION:
Here int specified that it is the data type, a is the name of the array, inside the first
subscript 3 is the number of tables, second 2 is the number of rows, third 2 is the number
of columns. This array contains 12 elements and the number of elements is calculated
by multiplying size inside each subscript. Therefore, size of array a is: 3*2*2=12.
EXPLANATION:
This is explained that a is the name of the 3-D array where 3 specifies the number of
array which is a 2*2 array.
Example 2:
int b[3][3][2]={
{
{1,2},
{3,4},
{5,6}
},
{
{7,8},
{9,10},
{11,12},
},
{
{13,14};
{15,16},
{17,18},
}
};
EXPLANATION:
This is explained that b is the 3-D array name where 3 is the number of tables each of
three rows and two columns each.
302 Concepts and Techniques of Programming in C
TIPS TO REMEMBER
2D array is the array of 1D array where 3D array is the array of array of array.
SUMMARY
SHORT Questions
1. What is an array?
2. Write the syntax of array declaration?
3. Write the syntax of array initialization?
4. What is a subscript?
5. If we do not initialize the array then the arrays contain what values?
6. If the array size is 10 then the array index start with what?
7. Assume”s” as an integer array with the following initialization values:
int s[3][3]={5,10,15,20,25,30,35,40,45,50};
Write a single c statement to print 35 from the list.
Solution:
#include<stdio.h>
void main()
{
int s[3][3]={5,10,15,20,25,30,35,40,45};
printf(“%d”,s[2][0]);
}
Output:
35
LONG Questions
1. What will be the output of the program if the array begins at 65472 and each
integer occupies 2 bytes? [internet]
#include<stdio.h>
void main()
{
int a[3][4] = {10,20,30,40,40,30,20,10,70,80,90, 0};
printf(“%u, %u\n”, a+1, &a+1);
}
Output:
65480, 65496
2. What will be the output of the following program?
#include<stdio.h>
void main()
{
int x[5],i=0;
while(i<5)
x[i]=++i;
for(i=0;i<5;i++)
printf(“%d “, x[i]);
}
Output:
garbase value,1,2,3,4
3. What will be the output of the program?
#include<stdio.h>
void main()
{
int a[2]={100};
printf(“%d\n”,0[a]);
}
Output:
100
304 Concepts and Techniques of Programming in C
Multiple-Choice questions
12.1 INTRODUCTION
The process of storing set of integer values in an integer array. Similarly, set of characters
can also be stored in a character array. Therefore, character arrays are called strings.
Thus, the definition of a string is, it a finite sequence of characters that is treated as a
single data item.
Example:
char x[20];
If the declaration of string size is large but less numbers are initialized then rest of
the memory locations are assigned NULL values. Example
char x[10]={‘C’,’U’,’T’,’T’,’A,’C’,’K’,’\0’};
C U T T A C K \0 \0 \0
Output:
DHABAL PRASAD SETHI
Q1. /*Program to Display Printing of a String named BBSR*/
#include<stdio.h>
void main(void)
{
char x[]=”BBSR”;
int j=0;
while(j<=4)
{
printf(“%c”,x[j]);
j++;
}
}
Output:
BBSR
Or
#include<stdio.h>
void main(void)
{
char x[]=”BBSR”;
int j=0;
while(x[j]!=’\0’)
{
printf(“%c”,x[j]);
j++;
}
}
Output:
BBSR
Or
#include<stdio.h>
void main(void)
{
308 Concepts and Techniques of Programming in C
char x[]=”BBSR”;
char *p;
p=x;
while(*p!=’\0’)
{
printf(“%c”,*p);
p++;
}
}
Output:
BBSR
TIPS TO REMEMBER
To read the character array do not use address operator (&) with the variable of scanf
function. The example is shown in above.
Output:
Input the string: DHABAL
DHABAL
Output:
DHABAL
TIPS TO REMEMBER
If the length of the string is six then declare the array whose size is seven because the
string should end with’\0’ e.g. ‘\0’ occupy one extra memory location in addition
to string size.
Output:
Input your name: DHABAL
My name is: DHABAL
Q3. /* Program to Input/Output Strings using gets() and puts() */
#include <stdio.h>
void main(void)
{
char x[20];
puts(“Input your name: “);
gets(x);
puts(“My name is: “);
puts(x);
}
Output:
Input your name: JUGAL
My name is: JUGAL
Output:
Input the string: DHABAL
The number of characters in the input string is 6
TIPS TO REMEMBER
If the character array/string size is 10 then you have to initialize the 9 character
because ‘\0’ (null character) occupies one memory location.
Output:
Input the source string: NUTAN
The destination string is: NUTAN
EXPLANATION:
Here y is the source string and x is the destination string.
void main(void)
{
char x[30],y[30];
printf(“Input the first name:”);
scanf(“%s”,x);
printf(“Input the second name:”);
scanf(“%s”,y);
if(strcmp(x,y)==0)
printf(“The two names are same”);
else
printf(“The two names are not same”);
}
Output:
Input the first name: DHABAL
Input the second name: DHABAL
The two names are same.
Q7. /* Program to Compare Two Strings without using strcmp() */
#include<stdio.h>
void main(void)
{
char x[30],y[30];
int j,c=0;
printf(“Input the first name:”);
gets(x);
printf(“Input the second name:”);
gets(y);
for(j=0;x[j]!=’\0’;j++)
{
if(x[j]==y[j])
c=1;
else
c=0;
}
if(c==1)
printf(“Both names are same.”);
else
printf(“Both names are not same.”);
}
Output:
Input the first name: DHABAL
Input the second name: DHABAL
Both names are same.
Q8. /* Program to Find whether a String is Palindrome or Not */
#include <stdio.h>
#include <string.h>
String 313
void main(void)
{
char x[20],y[20];
int z;
printf(“Input the string: “);
gets(x);
strcpy(y,x);
strrev(y);
z=strcmp(x,y);
if(z==0)
printf(“The inputted string is a palindrome string”);
else
printf(“The inputted string is not a palindrome string”);
}
Output:
1st run
Input the string: DHABAL
The input string is not a palindrome
2nd run
Input the string: EEE
The input string is a palindrome string
Output:
Input the first name: DHABAL
Input the last name: SETHI
The first name becomes: DHABALSETHI
Q10. /* Program to Concatenate Two Strings without using strcat() */
#include <stdio.h>
#include <conio.h>
#include <string.h>
void main(void)
{
char x[30],y[30];
int j,c=0,t;
printf(“Input the first name:”);
gets(x);
printf(“Input the last name:”);
gets(y);
for(j=0;x[j]!=’\0’;j++)
c++;
t=c;
for(j=0;y[j]!=’\0’;j++)
{
x[t]=y[j];
t++;
}
x[t] = ‘\0’;
printf(“After concatenation the first name is:”);
puts(x);
}
Output:
Input the first name: DHABAL
Input the last name: SETHI
After concatenation the first name is: DHABALSETHI
Output:
Input the string: dhabal
Reverse of input string is: labahd
TIPS TO REMEMBER
If the scanf() function reads the string as input then do not give “&” (address
operator)in that address variable.
Output:
Input the string to be reversed: UTKAL
The reversed string is: LAKTU
TIPS TO REMEMBER
The last character is always’\0’ and that ‘\0’is called null character.
The ASCII value of ‘\0’ is 0.
The ASCII value of ‘0’is 48
The printf() function does not print the ‘\0’
In c, the end of a string is marked by a null character.
The ‘\0’ is not two characters but it is actually one character. The\ indicates what
follows, it is something special.
The elements of the character array are stored in contiguous memory locations.
The ‘\0’ is not a string, but a collection of characters.
The %s used in printf() function is a format specifier for printing a string.
316 Concepts and Techniques of Programming in C
Output:
Input the string: DHABAL
Length of string is: 6
Q14. /* Program to Find whether a String is Palindrome or Not without using String
Functions */
#include <stdio.h>
#include <string.h>
void main(void)
{
char x[20];
int i,j,l=0,c=0;
printf(“Input the string to check palindrome:”);
gets(x);
for (i=0;x[i]!=’\0’;i++)
l++;
i=0;
j=l-1;
while(i<l)
{
if(x[i]!=x[j])
{
c=1;
break;
}
i++;
j--;
}
if(c==0)
printf(“The string is a palindrome”);
else
printf(“The string is not palindrome”);
}
String 317
Output:
Input the string to check palindrome: AAA
The string is a palindrome
Q15. /*C program to Find the Number of Vowels, Consonants, Digits and White
Spaces Character in a Sentence*/
#include<stdio.h>
void main(void)
{
char x[150];
int j,count1,count2,count3,count4;
count1=count2=count3=count4=0;
printf(“Input an English sentence:”);
gets(x);
for(j=0;x[j]!=’\0’;++j)
{
if(x[j]==’a’||x[j]==’e’||x[j]==’i’||x[j]==’o’||x[j]==’u’||x[j]==’A’||x[j]=
=’E’||x[j]==’I’||x[j]==’O’||x[j]==’U’)
count1++;
else if((x[j]>=’a’&&x[j]<=’z’)||(x[j]>=’A’&&x[j]<=’Z’))
count2++;
else if(x[j]>=’0’&&count2<=’9’)
count3++;
else if (x[j]==’ ‘)
count4++;
}
printf(“Vowels in the sentence:%d\n”,count1);
printf(“Consonants in the sentence:%d\n”,count2);
printf(“Digits in the sentence:%d\n”,count3);
printf(“White spaces in the sentence:%d\n”,count4);
}
Output:
Input an English sentence: I AM DHABAL
Vowels in the sentence: 4
Consonants in the sentence: 5
Digits in the sentence: 0
White spaces in the sentence: 2
SUMMARY
SHORT QUESTIONS
LONG QUESTIONS
Output:
A
3. What will be the output?
#include<stdio.h>
#include<string.h>
void main(void)
{
printf(“%d\n”,strlen(“123”));
}
Output:
3
4. What will be the output?
#include<stdio.h>
void main(void)
{
printf(2+”I LOVE MY COUNTRY”);
}
Output:
LOVE MY COUNTRY
5. What will be the output?
#include<stdio.h>
#include<string.h>
void main()
{
char x[]=”INDIA\0\ODISHA\0”;
printf(“%s\n”,x);
}
Output:
INDIA
6. What will be the output?
#include<stdio.h>
void x();
void main()
{
printf(“Input the character:”);
x();
printf(“\n”);
}
void x()
{
char d;
if((d=getchar())!=’\n’)
x();
printf(“%c”,d);
}
320 Concepts and Techniques of Programming in C
Output:
Input the character: a
a
7. What will be the output?
#include<stdio.h>
void main()
{
printf(“INDIA”,”ODISHA\n”);
}
Output:
INDIA
8. What will be the output?
#include<stdio.h>
void main()
{
char x[8]=”INDIAODISHA”;
printf(“%s\n”,x);
}
Output:
Compilation error
9. What will be the output?
#include<stdio.h>
void main()
{
char *x[]={“DHABAL”,”JUGAL”,”GUDU”,”NUTAN”,”RAKESH”};
int i;
char *t;
t=x[3];
x[3]=x[4];
x[4]=t;
for(i=0;i<=4;i++)
printf(“%s,”,x[i]);
}
Output:
DHABAL,JUGAL,GUDU,RAKESH,NUTAN,
10. What will be the output?
#include<stdio.h>
#include<string.h>
void main()
{
char x[]=”ODISHA\0\INDIA\0”;
printf(“%d\n”,strlen(x));
}
String 321
Output:
6
11. What will be the output?
#include<stdio.h>
#include<string.h>
void main()
{
static char x[]=”sethi”;
static char y[20];
static char z[]=”dhabal”;
int i;
i=strcmp(strcat(z,strcpy(y,x)),”dhabalsethi”);
printf(“%d\n”, i);
}
Output:
1
12. What will be the output?
#include<stdio.h>
#include<string.h>
void main()
{
static char x[]=”INDIA!”;
printf(“%d\n”,*(x+strlen(x)));
}
Output:
0
13. What will be the output?
#include<stdio.h>
void main(void)
{
static char x[25]=”MY INDIA”;
int i=0;
char d;
d=x[++i];
printf(“%c”,d);
d=x[i++];
printf(“%c”,d);
d=i++[x];
printf(“%c”,d);
d=++i[x];
printf(“%c”,d);
}
Output:
YY J
322 Concepts and Techniques of Programming in C
13.1 INTRODUCTION
In chapter 4 we studied that a variable is a memory location which is used to store
a value. To access that memory address of a variable we can use the & (ampersand)
operator.
Let’s see the programming example
#include <stdio.h>
void main(void)
{
int x;
printf(“Address of variable x is:%u”, &x);
}
Output:
Address of variable x: 1000
EXPLANaTION:
From the above discussion we learned about the memory address. Let’s see the concept
of a pointer. The definition: it is a derived data type which is built from one of the
fundamental data types, e.g., int, char, float, double. It holds memory addresses as their
values. It can be used to access and manipulate data stored in the computer memory.
Therefore, pointer is the most powerful and exciting features of C language.
EXPLANATION:
In the above declaration data type determines what type of data value of the pointer
variable will hold by using fundamental data type (e.g., int, char, float, double) and
then *in front of variable_name identified that variable_name is a pointer variable.
TIPS TO REMEMBER
The pointer variable declaration works when it gives the information/report to
the C compiler about three basic things about pointer variable. First thing is that,
asterisk (*) placed in front of variable identify that it is a pointer variable. Second
thing pointer variable requires is a memory location where it will contain address
of another variable and the third thing pointer variable should point to a variable
of same data type.
Let’s see the examples of pointer variable declarations with their respective data
types.
EXPLANATION OF EXAMPLE 1 TO 4
1. int *x;
Pointer 327
This statement declares that the variable x is a pointer variable that points to an
integer type value, e.g., pointer variable x may hold the value which may be a
garbage value because in that above syntax initialization of values is not done or
if initialized it holds the initialized value.
2. float *x;
This statement declares that the variable x is a pointer variable that points to a
float type value. It may hold garbage value or initialized value.
3. char *x;
This statement declares that the variable x is a pointer variable that points to char
type value. It may hold garbage value or initialized value.
4. double *x;
This statement declares that the variable x is a pointer variable that points to
double type value. It may hold garbage value or initialized value.
TIPS TO REMEMBER
Pointer is used to access and input data which is stored in computer memory.
Q. When we declare the pointer variable, e.g., int *x; or pointer variable x with
other data types (char, float, double), then what value x will contain?
The answer is that when we declare the pointer variable x .Then it will point to the
unknown locations because it searches some data values to store. These data values
are called garbage values and are automatically generated by the system.
x pointer variable
TIPS TO REMEMBER
int *x;
In the above declaration x is a pointer variable but *x is not called a pointer
variable. But *in front of x identifies that x is a pointer variable.
328 Concepts and Techniques of Programming in C
TIPS TO REMEMBER
A pointer is a variable and it contains only address, e.g., it contains address of
another variable.
There are two important operators used in pointer concept. They are:
(a) * and (b) &
(a) * is called as indirection operator or value at address operator or dereferencing
operator.
(b) & is called address operator and is used to find the address of a variable.
All three pointer variable declarations are correct declarations but the first one
marked as bold is preferred by programmers to the other two.
p=&x;
printf(“address of variable x stored in p is:%u”,p);
}
Output:
Compilation error
(b) When int pointer variable is pointing to char type values.
#include<stdio.h>
void main()
{
char x=’a’;
int *p;
p=&x;
printf(“address of variable x stored in p is:%u”,p);
}
Output:
Compilation error
(c) When int pointer variable is pointing to double type value.
#include<stdio.h>
void main()
{
double x=20.0;
int *p;
p=&x;
printf(“address of variable x stored in p is:%u”,p);
}
Output:
Compilation error
TIPS TO REMEMBER
The pointer variable of data type int can point to int data type values only but not
to float, double, char data type value.
Solution:
/*************************************************************************
FILE NAME: pointer1.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: Example of correct pointer variable initialization
which hold an address of another variable of same data type.
*************************************************************************/
330 Concepts and Techniques of Programming in C
#include <stdio.h>
void main (void)
{
int x=10; /* variable declaration */
int *y; /* pointer variable declaration */
y= &x; /* address of x is stored in pointer variable p*/
printf(“Address of variable x is: %x\n”,&x ); /*printing address of variable
x by using address operator*/
printf(“Address stored in pointer variable y is:%x\n”,y); /*printing
address of variable x by using pointer variable */
}
Output:
Address of variable x is: 2226
Address stored in pointer variable y is: 2226
x=10
y=1000
In the above diagram let’s see how the pointer variable y holds the address 1000 of
another variable x.
{
int *y=NULL;
printf(“value of pointer variable y is:%u”,y);
}
Output:
Value of pointer variable y is:0
Output:
Value of x is: 5
Value of x is: 5
Value of x is: 5
Value of x is: 5
EXPLANATION:
From the above four printf statements in the program that prints the value of x in
different ways. First is printing the value of variable x then second, third, fourth printf
statements are the same for printing the value of x through pointer concept.
332 Concepts and Techniques of Programming in C
Output:
4
D
10.7000000
Explanation:
In the above program the first printf function prints the output 4 and in the printf
statement *(int *)y is used because y is void type and our objective is to print the value
of x which is int type therefore we type caste void data type to int data type by the
syntax (int *) and other printf statements are followed by the first syntax.
(contains one asterisk). Again that another pointer variable (containing one asterisk)
holds the address of a variable. The whole process is called multiple indirections.
Double asterisks are used to declare the pointer-to-pointer variable. The above
declaration tells that x is a pointer to a pointer of int data type.
TIPS TO REMEMBER
int **x;
In the above line x is not a pointer to an integer type but a pointer to an integer
pointer.
We can access the variable’s value indirectly through the concept pointer to pointer,
e.g., using the indirection operator (*) two times. Let’s see the example.
Q5. Example of Pointer to Pointer.
Solution:
/*************************************************************************
FILE NAME: pointer4.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: Example of dereferencing pointer.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=20,*y,**z;
y=&x;
z=&y;
printf(“value of pointer variable z is:%d”,**z);
}
Output:
Value of pointer variable z is: 20
Explanation:
From the above program we saw that z is displaying the value of x by using the
operator** called pointer to pointer, e.g., z holds the value of y which again holds the
value of x.
334 Concepts and Techniques of Programming in C
z=2000
Address=3000
y=1000
Address=2000
x=20
Address=1000
Fig. 13.3 Pointer-to-pointer mechanism
Here in the figure pointer variable z holds the address of another pointer variable y
and again that pointer variable y holds the address of variable x.
Q6. /*Example of Size of Character Pointer Variable*/
#include<stdio.h>
void main(void)
{
char *x;
printf(“Size of character pointer variable is:%d”,sizeof(x));
}
Output:
Size of character pointer variable is:4
Q7. /*Example of Size of Indirection Character Pointer Variable*/
#include<stdio.h>
void main(void)
{
char *x;
printf(“Size of indirection character pointer variable is:%d”,sizeof(*x));
}
Output:
Size of indirection character pointer variable is:1
Q8. /*Example of Size of Integer Pointer Variable*/
#include<stdio.h>
void main(void)
{
Pointer 335
int *x;
printf(“Size of character pointer variable is:%d”,sizeof(x));
}
Output:
Size of integer pointer variable is: 4
Q9. /*Example of Size of Indirection Integer Pointer Variable*/
#include<stdio.h>
void main(void)
{
int *x;
printf(“Size of indirection integer pointer variable is:%d”,sizeof(*x));
}
Output:
Size of indirection integer pointer variable is: 2
Q10. /*Example of Size of Floating Type Pointer Variable*/
#include<stdio.h>
void main(void)
{
float *x;
printf(“Size of floating type pointer variable is:%d”,sizeof(x));
}
Output:
Size of floating type pointer variable is: 4
Q11. /*Example of Size of Indirection Floating Type Pointer Variable*/
#include<stdio.h>
void main(void)
{
float *x;
printf(“Size of indirection float type pointer variable is:%d”,sizeof(*x));
}
Output:
Size of indirection float type pointer variable is: 4
Q12. /*Example of Size of Double Type Pointer Variable*/
#include<stdio.h>
void main(void)
{
double *x;
printf(“Size of double type pointer variable is:%d”,sizeof(x));
}
336 Concepts and Techniques of Programming in C
Output:
Size of double type pointer variable is: 4
Q13. /*Example of Size of Indirection Double Type Pointer Variable*/
#include<stdio.h>
void main(void)
{
double *x;
printf(“Size of double type indirection pointer variable is:%d”,sizeof(*x));
}
Output:
Size of double type indirection pointer variable is: 8
TIPS TO REMEMBER
In the above program we find that the size of pointer variable of types, e.g., int,
char, float, double type is 4. This program tested in 32-bit compiler and editor
Turbo C 4.5. If you run the above program in 16-bit compiler and Turbo C then
its output will be 2. So it is compiler dependent. But if we measure the size of
fundamental data types and indirection pointer variable, e.g., int, char, float,
double then its size is different. Generally, size of fundamental data types are: int
is 2,char=1,float=4 and double=8.
Output:
Input the two integer numbers: 2 3
Sum of input two integer numbers is: 5
Explanation:
Here in the above program pointer variable a and b hold the address of input variable
x and y. Then using dereferencing operator add these pointer variables and the result
is stored in another variable c and last prints that values.
Q15. Swap Two Integer Numbers using Pointer Concept.
Solution:
/*************************************************************************
FILE NAME: pointer15.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: swap two integer numbers using pointer concept.
**************************************************************************
*******/
#include <stdio.h>
void main(void)
{
int x,y,*m,*n,t;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
printf(“Before Swapping the inputted values are:\nx:%d\ny=%d\n”,x,y);
m=&x;
n=&y;
t=*m;
*m=*n;
*n=t;
printf(“After Swapping the inputted values are:\nx:%d\ny:%d\n”,x,y);
}
Output:
Input the two integer numbers: 3 4
Before swapping the input values are:
x:3
y:4
After swapping the input values are:
x:4
y:3
receiving the addresses should be pointers. The process of passing the address of a
variable from the calling function to called function is called call by reference. In call by
reference the values of variable used in function call are changed. The example shown
below is passing by reference.
Q16. Examples of Pointer as Function Arguments.
Solution:
/*************************************************************************
FILE NAME: pointer16.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: examples of pointer as function arguments.
*************************************************************************/
#include<stdio.h>
void num_update(int *m,int *n); /*function declaration*/
void main(void)
{
int x,y;
printf(“Input the two integer numbers:”);
scanf(“%d%d”,&x,&y);
num_update(&x,&y); /*calling function*/
printf(“After updating the two inputted numbers are:%d %d”,x,y);
}
void num_update(int *m,int *n)
{
*m=*m*10;
*n=*n*5;
}
Output:
Input the two integer numbers: 10 20
After updating the two input numbers are: 100 100
See the program of swapping the two integer numbers using call by reference in the
chapter function is another examples of pointer as function arguments.
TIPS TO REMEMBER
The parameter used in user-defined functions/function header is declared as
pointers.
The dereferencing pointers are used in body section of user-defined function.
When the function is called from calling function, the addresses of parameter are
passed in function call.
Pointer 339
Pointer arithmetic is different from general arithmetic. In pointer arithmetic all the
operations are done on the base address of the corresponding data type.
Suppose p is an integer data type which holds the address 100 then if we write p++
;or p=p+1; then it will display the value 102 instead of 101. Because its corresponding
data type size is 2bytes when one increment is done then the result becomes 100+2=102 .
Q17. C Program of Addition of Two Dereferencing Pointer Variable.
Solution:
/*************************************************************************
FILE NAME: pointer17.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: c program of addition of two dereferencing pointer
variable.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x=10,y=20,z;
int *p1,*p2;
p1=&x;
p2=&y;
z=*p1+*p2;
printf(“%d”,z);
}
340 Concepts and Techniques of Programming in C
Output:
30
TIPS TO REMEMBER
In pointer concept the dereferencing pointer variable addition, subtraction,
multiplication and division is possible but except subtraction of one pointer variable
from other pointer variable others pointer operation, e.g., addition, division,
multiplication is not possible.
Output:
1
Explanation:
Suppose the pointer variable y1 holding address of x is 1000 and another pointer
variable y2 holding the address of variable y is 999 and after difference the variable z
holds the value 1.
Q19. /*C Program of Add an Integer Number with Pointer Variable*/
#include<stdio.h>
void main(void)
{
int x=10,y;
int *p1;
p1=&x;
p1=p1+4;
printf(“%d”,p1);
}
Output:
8680
Pointer 341
EXPLANATION:
Because if the pointer variable p1 will hold the address 8672 then with the addition of
integer number 4 it will have 8680, e.g., 8672+4*size of int data type=8672+4*2=8680.
Q20. /*C Program of Subtraction of a Integer Number from Pointer Variable*/
#include<stdio.h>
void main(void)
{
int x=10,y;
int *p1;
p1=&x;
p1=p1-4;
printf(“%d”,p1);
}
Output:
8664
EXPLANATION:
Because if pointer variable p1 holds the address 8672 then on subtracting the number
4 it will have 8664.The formula is base address-integer number*size of data type,
e.g., 8672-4*2=8664.
The name of the array y is called constant pointer that points to the first elements
y[0]. Therefore, the first element 10 stored in memory y[0] whose base address is 2000.
If we declare a pointer variable p and it points to the array y then it can be represented
as
p=y;
We can access the address of each elements of the array by using pointer concept is
p+0=&y[0]=2000
p+1=&y[1]=2002
p+2=&y[2]=2004
p+3=&y[3]=2006
342 Concepts and Techniques of Programming in C
TIPS TO REMEMBER
From the above discussion we find the formula to access the address of array
elements using pointer concept in one-dimensional array is: p+i or y+i or
&y[i]
We can access the array elements using pointer concept in one-dimensional array is
*(p+0)=y[0]=10
*(p+1)=y[1]=12
*(p+2)=y[2]=14
*(P+3)=y[3]=16
TIPS TO REMEMBER
So the formula of accessing array elements using pointer concept is:
*(p+i) or *(y+i) or y[i]
TIPS TO REMEMBER
The name of the array is called constant pointer that points to the first element of
the array.
Q21. Examples of Accessing the Array Elements and its Address using Pointer
Concept.
Solution:
/*************************************************************************
FILE NAME: pointer20.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTE: 10/8/2015
NAME OF THE PROGRAM: Examples of accessing the array elements and its
address using pointer concept.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int y[4]={10,12,14,16};
int *p;
p=&y[0];
for(int j=0;j<4;j++)
{
printf(“Value of y[%d] is:%d”,j,y[j]);
printf(“Address of y[%d] is:%u\n”,j,&y[j]);
printf(“Value of y[%d] is:%d”,j,*(y+j));
printf(“Address of y[%d] is:%u\n”,j,y+j);
Pointer 343
Output:
Value of y[0] is:10 Address of y[0] is:8806
Value of y[0] is:10 Address of y[0] is:8806
Value of y[0] is:10 Address of y[0] is:8806
Value of y[1] is:12 Address of y[1] is:8808
Value of y[1] is:12 Address of y[1] is:8808
Value of y[1] is:12 Address of y[1] is:8808
Value of y[2] is:14 Address of y[2] is:8810
Value of y[2] is:14 Address of y[2] is:8810
Value of y[2] is:14 Address of y[2] is:8810
Value of y[3] is:16 Address of y[3] is:8812
Value of y[3] is:16 Address of y[3] is:8812
Value of y[3] is:16 Address of y[3] is:8812
Output:
Input the size of the array: 4
Input [4] integer elements: 3 1 6 8
Smallest element found at location [2] and its value is 1
Example:
int (*x)[20];
EXPLANATION:
This declares that x is a pointer to an array of twenty integers and size represents the
number of columns. The pointer to the array must be dereferences to access the value of
each element. If we do not mention the parenthesis in the above declaration of pointer
variable named x then we would call them it array of pointer. Therefore, we should
use the parenthesis when declaring pointer variable.
Q23. Example of Pointer to One-Dimensional Array.
Solution:
/*************************************************************************
FILE NAME: pointer22.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
Pointer 345
Output:
10 20 30 40 50
Q24. Example of Pointer to Two-Dimensional Arrays.
Solution:
/*************************************************************************
FILE NAME: pointer23.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: examples of pointer to two dimensional arrays.
*************************************************************************/
#include<stdio.h>
void main(void)
{
int x,y;
int m[2][2]={{10,20},{30,40}};
int (*p)[2]=m;
for(x=0;x<2;x++)
{
for(y=0;y<2;y++)
printf(“%d\t”,(*(p+x))[y]);
}
}
Output:
10 20 30 40
Q25. Write a Function using Pointers to Add Two Matrices and Return the Resultant
Matrix to the Calling Function.
346 Concepts and Techniques of Programming in C
Solution:
/*************************************************************************
FILE NAME: pointer24.c
AUTHOR DETAILS: Mr. x, 1ST SEM, COMP.SC& ENGG., ABC COLLEGE OF ENGG.
DATE OF PROGRAM EXECUTION: 10/8/2015
NAME OF THE PROGRAM: write a function using pointers to add two matrices
and return the resultant matrix to the calling function.
*************************************************************************/
#include<stdio.h>
#include<conio.h>
int x[5][5],y[5][5],row,col;
void add(int(*)[5]);
void main(void)
{
int z[5][5],m,n;
clrscr();
printf(“Input the row : “);
scanf(“%d”,&row);
printf(“Input the column : “);
scanf(“%d”,&col);
printf(“Input the matrix X :\n”);
for(m=0;m<row;m++)
{
for(n=0;n<col;n++)
{
scanf(“%d”,&x[m][n]);
}
}
printf(“Input the matrix Y :\n”);
for(m=0;m<row;m++)
{
for(n=0;n<col;n++)
{
scanf(“%d”,&y[m][n]);
}
}
add(z);
printf(“Addition of two matrices:\n”);
for(m=0;m<row;m++)
{
for(n=0;n<col;n++)
{
printf(“%d\t”,z[m][n]);
}
printf(“\n”);
}
getch();
}
Pointer 347
Output:
Input the row: 2
Input the column: 2
Input the matrix X:
2 3
2 4
Input the matrix Y:
2 4
4 5
Addition of two matrices:
4 7
6 11
Example:
int *x[20];
This declares and allocates an array of pointers to int type. Each element must be
dereferences individually.
348 Concepts and Techniques of Programming in C
Output:
Value of x[0]are:1
Value of x[0]are:2
Value of x[0]are:3
Value of x[0]are:4
The C programming language consists of set of local variable, global variable and
program instruction. Among the three generally local variables are stored in stack
region. Program instruction and global variable are stored in computers permanent
storage region. Heap region is the dynamic memory allocation. The size of the heap
changing when program is executed due to creation and deleted.
Here size specified means the number of bytes to be allocated, p is a pointer of type
data-type, malloc returns a pointer of data type to an area of memory with specified
size.
Example:
int *p;
p=(int *)malloc(20);
This function creates 20 bytes of memory whose base address is stored in pointer
variable p. Since p is integer pointer it creates 10 memory location whose size is 2 bytes.
Another form of declaration is
p=(data_ type*)malloc(number of space*sizeof(data _type));
Example:
int *p;
p=(int *)malloc(10*sizeof(int));
This declaration allocates 5 memory blocks each of size 2 bytes and starting address/
base address is stored in pointer variable p which is int type.
TIPS TO REMEMBER
malloc() function allocates the size of bytes and returns a pointer to the first bytes
of the allocated memory.
calloc() function allocates the memory for array elements, initializes them to zero
and returns a pointer to the memory.
realloc() function modifies the existing memory.
free() function removes the allocated memory.
Pointer 351
In the above declaration argv[0] hold the name of the program and argv[1] is pointer
to the first command line argument supplied and *argv[n] is the last argument. If no
arguments are supplied, argc will be one, otherwise and if you pass one argument then
argc is set at 2.
Summary
1. A pointer is a derived data type which is built from fundamental data type, e.g.,
int, char, float, double.
352 Concepts and Techniques of Programming in C
SHORT QUESTIONS
1. What is a pointer?
2. What value the pointer variable will hold without initialization?
3. What do you mean by NULL pointer?
4. What do you mean by pointer to pointer?
5. What do you mean by dereferencing pointer?
6. Give examples of pointer as function arguments?
7. Can we add two-pointer variables?
8. Write the formula to access array elements using pointer?
9. Write the formula to access array address using pointer?
10. What do you understand by pointer to array?
Pointer 353
LONG QUESTIONS
Output:
200
7. What will be the output?
#include<stdio.h>
void main()
{
printf(“%c\n”,6[“INDIA-ODISHA”]);
}
Output:
O
8. What will be the output?
#include<stdio.h>
void main()
{
char s[] = “INDIA”;
char *s1 =s;
printf(“%s\n”, s1++ +2);
}
Output:
DIA
9. What will be the output?
#include<stdio.h>
void main()
{
char *x;
x=”INDIA”;
printf(“%s\n”, *&*&x);
}
Output:
INDIA
10. What will be the output, assuming that the array begins at location 1002?
#include<stdio.h>
void main()
{
int x[2][3][4] = { {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 100,
200},
{20, 10, 40, 70, 60, 70, 80, 90, 0, 0, 0, 0} };
printf(“%u, %u, %u, %d\n”,x,*x,**x,***x);
}
11. What will be the output, if address of ‘a’ is 1000?
#include<stdio.h>
int power(int**);
356 Concepts and Techniques of Programming in C
void main()
{
int x=5,*y;
y= &x;
x= power(&y);
printf(“%d\n”,x);
}
int power(int **m)
{
int n;
n=**m***m;
return(n);
}
Output:
25
12. What will be the output?
#include <stdio.h>
void main(void)
{
int x=30;
int *p =&x;
printf(“%d\n”,*p++);
}
Output:
30
13. What will be the output?
#include <stdio.h>
void main(void)
{
int x=10;
int *p=&x;
int *m=p++;
int n=p-m;
printf(“%d”,n);
}
Output:
1
14. What will be the output?
#include<stdio.h>
void main(void)
{
int x[]={1,2,3,4,5,6};
int *p=x+2;
printf(“%d”,*--p);
}
Pointer 357
Output:
2
15. What will be the output?
#include<stdio.h>
void main()
{
char *x;
x=”DHABAL”;
printf(“%s”,x);
}
Output:
DHABAL
16. What will be the output?
#include<stdio.h>
void main()
{
double a[2],*p,*q;
p=a;
q=p+1;
printf(“%d\n”,q-p);
}
Output:
1
MULTIPLE-Choice QUESTIONS
14.1 INTRODUCTION
In chapter 4 we saw that a variable can store only one value at a time. Then we
learnt in chapter 14 that an array is a substitute for storing multiple values by using
a single variable of same type. Now we are going to learn a new topic “structure and
it is another substitute how different types of variables called members are store in a
single package” called structure. The structure is the mechanism for storing members of
different data types into one package. Example, suppose the entity named as student
has the following characteristics or properties, e.g., name, regdno, branch, etc. If one
can ask write a C program to display the information of two students using structure
then the program is written as:
/* C Program to Display 2 Students Information, e.g., name, regdno, branch using
Structure */
#include<stdio.h>
void main()
{
struct student
{
char name[20];
int regdno;
char branch[20];
};
struct student s1,s2;
printf(“Input the name,regdno and branch\n”);
scanf(“%s%d%s”,s1.name,&s1.regdno,s1.branch);
scanf(“%s%d%s”,s2.name,&s2.regdno,s2.branch);
printf(“The inputted data are\n”);
printf(“%s\t%d\t%s\n”,s1.name,s1.regdno,s1.branch);
printf(“%s\t%d\t%s”,s2.name,s2.regdno,s2.branch);
}
360 Concepts and Techniques of Programming in C
Output:
Input the name, regdno and branch
Dhabal 15 Comp.sc
Jugal 09 ETC
The input data are
Dhabal 15 comp.sc
Jugal 09 ETC
Explanation:
Here in this program the structure is defined inside the main function along with
structure variables s1 and s2. Each structure variable can have access permission of each
member. Always note that whenever the user writes code of taking the input of group
of characters then the access specifier %s is used. You may or may not place address
operator before the character member and when input is int type then the place address
operator before int type member.
EXPLANATION:
From the above definition we know that struct is a data type which holds the different
variables of different types than struct_name is the name of the structure and it also
called structure tag. The variables declared inside the curly braces are called structure
elements or structure members. These are not called structure variables. Each member
belongs to different data type. At the end of the structure definition semicolon is given
to terminate it. Let’s see the example:
struct student
{
char name[30];
int regdno;
char branch[30];
};
Structure, Union, Type Definition, Bit Field 361
EXPLANATION:
Here the keyword struct is the structure data type which holds three data fields of
different types, e.g., name, regdno, branch. The student is called name of structure or
structure tag. The three different fields (name, regdno and branch) are called structure
elements or structure members and last semicolon is used to terminate the structure.
TIPS TO REMEMBER
While writing a program using structure, the declaration of structure may be done
above the main()function or inside the main()function.
Example:
struct student s1,s2,s3; /*s1,s2,s3 are structure variables*/
Then the complete declaration of structure and variable is
struct student
{
char name[10];
int regdno;
char branch[10];
};
struct student s1,s2; /*s1 and s2 are structure variables*/
TIPS TO REMEMBER
The members of structure are not structure variables. They are structure members.
They do not occupy any memory until they are associated with the structure
variables such are s1, s2.
of a structure the dot (.) is used which is called dot operator or period operator or
member operator. This operator makes or establishes a connection between members
of the structure with the structure variables. Let’s see the example below as:
s1.name;
Here s1 is the structure variable and name is the structure member. So the dot
operator maintains the relationship between s1 and name to access the name which is
initialized.
/*Example of Accessing Structure Members*/
#include<stdio.h>
void main()
{
struct student
{
char name[30];
int regdno;
char branch[30];
};
struct student s1;
printf(“INPUT THE NAME,REGD,BRANCH:”);
scanf(“%s %d %s”,s1.name,&s1.regdno,s1.branch);
printf(“THE INPUTTED NAME,REGD AND BRANCH IS:%s %d %s”,s1.name,s1.regdno,s1.
branch);
}
Output:
INPUT THE NAME, REGD, BRANCH: DHABAL 15 CSE
THE INPUTTED NAME, REGD AND BRANCH IS: DHABAL 15 CSE
Output:
NAME REGDNO BRANCH
Ram 100 Civil
Explanation:
Here name ‘ram’ assign to s1.name,100 assign to s1.regdno,’civil’ assign to
s1.branch.There is a one-to-one mapping between the members and their
initializing values.
2. Multiple structure variable initializations inside the main function
#include<stdio.h>
void main()
{
struct student
{
char name[30];
int regdno;
char branch[30];
}
s1={“Ram”,100,”Civil”}; /*structure variable s1 initialization*/
struct student s2={“Hari”,101,”Elect”}; /*structure variable s2
initialization*/
printf(“NAME\t REGDNO\tBRANCH\n”);
printf(“%s\t%d\t%s\n”,s1.name,s1.regdno,s1.branch);
printf(“%s\t%d\t%s”,s2.name,s2.regdno,s2.branch);
}
Output:
NAME REGDNO BRANCH
Ram 100 Civil
Hari 101 Elect
Explanation:
Here structure named student consists of three members name, regdno, branch
is declared along with two structure variable s1 and s2 are initialized.
3. One structure variable initialization outside the main function and another one
initialization inside the main function
#include<stdio.h>
struct student
{
364 Concepts and Techniques of Programming in C
char name[30];
int regdno;
char branch[30];
}s1={“Ram”,100,”Civil”};/*structure variable s1 initialization*/
void main()
{
struct student s2={“Hari”,101,”Elect”};/*structure variable s2
initialization*/
printf(“NAME\t REGDNO\tBRANCH\n”);
printf(“%s\t%d\t%s\n”,s1.name,s1.regdno,s1.branch);
printf(“%s\t%d\t%s”,s2.name,s2.regdno,s2.branch);
}
Output:
NAME REGDNO BRANCH
Ram 100 Civil
Hari 101 Elect
Explanation:
Here structure student is declared outside the main function, i.e., it is placed
above the main function and the structure variable is declared and initialized
inside the main function.
TIPS TO REMEMBER
1. The structure members inside the curly braces are not initialized individually.
2. When initializing the structure variables, the order of values should match the
order of the structure members. The uninitialized members are assigned to zero
for integer and floating numbers and ‘\0’ for character and strings.
if(z.img>=0)
printf(“Addition of two complex numbers is:%d + %di\n”, z.real, z.img);
else
printf(“Addition of two complex numbers is:%d %di\n”, z.real, z.img);
}
Output:
Input x and y [where x+iy is the first complex number]:2 3
Input m and n [where m+in is the second complex number]:4 5
Addition of two complex numbers is:6+8i
Output:
Student Id is: 100
Student Name is: Rajiv Sharma
Percentage of marks is: 80.000000
College Id is: 104
College Name is: GCE, KEONJHAR
366 Concepts and Techniques of Programming in C
Explanation:
In the above program the structure student has three data fields’, i.e., id, name, and
percentage. To access the student id, name, percentage of marks we can use structure
variable s.memeber name, e.g., s.id, s.name, s.percentage. To access college id and
college name we can use s.c.colle_id, s.c.colle_name. We cannot directly access the
college members because college members are declared inside another structure.
Therefore, college structure variable c is essential with student structure variable s to
access the college members.
/*Examples of Structure within Structure of Structure Pointer Variable*/
#include <stdio.h>
#include <string.h>
struct college
{
int colle_id;
char colle_name[30];
};
struct student
{
int id;
char name[30];
float percentage;
struct college c; /*structure within structure*/
}s,*s1;
void main()
{
struct student s ={100,”Rajiv sharma”,80.00,104,”GCE,KEONJHAR”};
s1=&s;
printf(“ Student Regd_Id is: %d \n”,s1->id);
printf(“ Student Name is: %s \n”,s1->name);
printf(“ Percentage of marks is: %f \n\n”,s1->percentage);
printf(“ College Regd_Id is: %d \n”,s1->c.colle_id);
printf(“ College Name is: %s \n”,s1->c.colle_name);
}
Output:
Student Regd_ Id is: 100
Student Name is: Rajiv Sharma
Percentage of marks is: 80.000000
Explanation:
Here s is the structure variable of student,*s1 is pointer variable of structure student.
So when pointer variable s1 is used to access the student members then arrow operator
Structure, Union, Type Definition, Bit Field 367
(->) is used by pointer variable of structure type, i.e., s1->id, s1->name, s1->percentage.
To access college members use s1->c.colle_id, s1->c.colle_name.
TIPS TO REMEMBER
Dot(.) operator is used to access structure members by simple variables and
->(arrow) operators is used to access the structure member by using pointer
variables which is declared inside the structure.
Output:
INPUT THE STDUENT NAME, REGDNO, BRANCH: DHABAL 100 CSE
INPUT THE STDUENT NAME, REGDNO, BRANCH: JUGAL 200 ETC
INPUT THE STDUENT NAME, REGDNO, BRANCH: RAJIB 300 MECHANICAL
INPUT THE STDUENT NAME, REGDNO, BRANCH: NUTAN 400 CIVIL
INPUT THE STDUENT NAME, REGDNO, BRANCH: PRAKASH 500 ELECT
YOU HAVE INPUTTED STDENT NAME, REGDNO, BRANCH
DHABAL 100 CSE
JUGAL 200 ETC
RAJIB 300 MECHANICAL
NUTAN 400 CIVIL
PRAKASH 500 ELECT
Explanation:
In the above program we declared the structure variable named s[5]; e.g., s is the
variable of which will hold 5 elements. Then using for loop we can input 5 elements
and will displaced on the computer screen.
Output:
Name Roll_No Marks
X 100 600.000000
Explanation:
Here user input the structure members individually as pass by value method, i.e., he
passes name, rollno and marks as an argument in function s. The function accepts the
members through calling function to called function and the called function displays
the output.
#include<stdio.h>
#include<conio.h>
struct student
{
char name[20];
int rollno;
float marks;
};
void s(struct student); /*function prototype*/
void main()
{
struct student s1 = {“DHABAL”,100,600};
s(s1); /*function call*/
getch();
}
void s(struct student s) /*function definition*/
{
printf(“Name\tRoll_No.\tMarks\n”);
printf(“%s\t%d\t\t%f”, s.name, s.rollno, s.marks);
}
Output:
Name Roll_No Marks
DHABAL 100 600.000000
Explanation:
Instead of sending the individual element of structure variable from calling function
to called function the user can send whole structure variable as an argument to called
function.
Output:
Name Roll_No Marks
DHABAL 100 600.000000
Explanation:
Here user passes the structure variable as an argument by using the address of variable
to called function. This method is called pass by reference method.
struct student
{
char name[30];
int regdno;
char branch[30];
} ;
struct student s1={“DHABAL”,100,”CSE”};
struct student *p;
p=&s1;
printf(“%s\t%d\t%s\t”,s1.name,s1.regdno,s1.branch);
printf(“\n%s\t%d\t%s\t”,p->name,p->regdno,p->branch);
}
Output:
DHABAL 100 CSE
DHABAL 100 CSE
EXPLANATION:
The first printf statement is simply displaying the initialized values of structure through
dot operator. The second printf statement displays the same initialized values by using
arrow operator because p is a pointer variable. If we want to access the structure
members through pointer variables we use the arrow (->) operator.
In the above program instead of ptr->name we can write (*p).name,(*p).regdno,(*p).
branch. Here parenthesis is required because (.) operator has highest precedence
then*operator.
We cannot use the p.name, p.regdno, p.branch because p is not a structure variable
but a pointer to structure. So instead of (.) dot operator provides an arrow (->) operator
to refer to the structure elements.
For example, a linked list is supposed to be a self-referential data structure. The next
node of a node is being pointed, which is of the same struct type. For example,
typedef struct node
{
void *data;
struct node *next;
} linked_list;
Structure, Union, Type Definition, Bit Field 373
In the above example, the node is a self-referential structure – because the *next is
of the type struct node.
14.11 UNION
Union is a derived data type like structure and it can contain members of different data
types. The syntax of union is same as structure, but the keyword union is used instead
of struct. The major difference between a structure and union is that, in structure each
member has its own/individual memory location; whereas in case of union all the
members have the same memory location, e.g., a union contains members of different
data types and it can handle one member at a time.
Example:
union student
{
char name;
int regdno;
flaot marks;
} u1;
EXPLANATION:
The above example the variable u1 is of type union student. The union contains three
members, i.e., char, int, float which is different type. However, the union works single
data type at time. This is the fact that one location is allocated for union variable in
respect to its size. The highest size of data type is floating, i.e., 4 bytes. So maximum
four memory locations, each of size1 byte is created and all of them use it.
When char whose size is 1 byte is used others are not used. Same int whose size is
2 bytes when used others are not.
374 Concepts and Techniques of Programming in C
Example:
typedef int result; / *result is the data type*/
result r1,r2; /*r1,r2 are variables of type result*/
EXPLANATION:
Here result is the user-defined data type. So here the result is alternative name of int
data type. We can use the data type named result in place of anywhere in and r1, r2
are variables of type result.
/*Example 1 of Type-definition*/
#include<stdio.h>
#include<conio.h>
typedef struct student
{
char name[24];
int age;
};
void main()
{
typedef struct student b; /*here b is the data type*/
b z={“DHABAL”,30}; /*here z is the structure variable*/
clrscr();
printf(“The name and age is:%s %d”,z.name,z.age);
}
Structure, Union, Type Definition, Bit Field 375
Output:
The name and age is: DHABAL, 30
/*Example 2 of Type-definition*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
typedef struct employee
{
char name[30];
int sal;
} emp;
void main( )
{
emp e1;
printf(“Input the Employee record\n”);
printf(“\Input the Employee name:”);
scanf(“%s”,e1.name);
printf(“Input Employee salary:”);
scanf(“%d”,&e1.sal);
printf(“Inputted Employee name is: %s”,e1.name);
printf(“\nInputted Employee salary is: %d”,e1.sal);
}
Output:
Input the Employee record
Input the Employee name: DHABAL
Input the Employee salary: 15600
Inputted Employee name is: DHABAL
Inputted Employee salary is: 15600
data_type varibaleN:bit_length;
};
TIPS TO REMEMBER
The data type of bit field can be int, unsigned int, signed int.
Output:
The values of v are: 3, 10,12,3
EXPLANATION:
Here the size of member “a” is 2-bit, i.e., the value may be 0 to 22-1=3 e.g. 0 or 1 or 2 or
3. Then size of member “b” is 5 bits, i.e., the value may be 0 to25-1=31, i.e., value may
be[0----31].The size of member “c “ is 4 bits, i.e., the value may be 0 to 2 4-1=15 [0----15].
The size of member “d” is 3-bit, i.e., the value may be 0 to 2 3-1=7[0----7].
SUMMARY
1. Structure is the mechanism for storing members of different data types into one
package.
2. The structure name is also called structure tag.
3. The variables inside the structure by using curly braces are called structure
elements or structure members but not called structure variables.
4. Suppose the structure name is student then the structure variable declaration is:
struct student s1;
5. When the structure members are associated with structure variable then it creates
memory space.
6. To access structure members the dot(.) operator is used to establish a connection
between structure members and structure variable.
Structure, Union, Type Definition, Bit Field 377
SHORT QUESTIONs
1. Define structure and its advantages?
2. Can we write a program written using an array in using structure? If yes give
example?
3. The members of structure are called structure variables? True or false. Give your
justification.
4. What is the declaration of structure variable?
5. Define structure.
6. How do we access the structure elements?
7. Define array of structure?
8. Define Nested structure with example.
9. Define pointer to structure?
10. What is union?
11. Differentiate between union and structure?
LONG QUESTIONS
1. Write a program to store 100 records in one structure with the help of an array.
2. Write a C program to create data for 50 students (roll, name, mark 1, mark 2,
mark 3, termmark) using structure and then find the total marks for each student
and average marks of all students.
3. What do you mean by self-referential structure? Give an example of it.
struct student
{
int age;
char x;
};
printf(“%d”,sizeof(student));
}
Output:
3
2. What will be the output?
#include<stdio.h>
void main()
{
struct student
{
int age;
char x[20];
};
printf(“%d”,sizeof(student));
}
Output:
22
3. What will be the output?
#include<stdio.h>
void main()
{
union student
{
int age;
char x;
};
printf(“%d”,sizeof(student));
}
Output:
2
4. What will be the output?
#include<stdio.h>
void main()
{
union student
{
int age;
char x[20];
};
printf(“%d”,sizeof(student));
}
Output:
20
15
File
15.1 Introduction
In console oriented programming every time beginner is given the input value and it
display the output on the computer screen because when the power is turned off or
when the program is closed its data is lost. In real-time storing of large amount of data,
it is difficult to handle/maintain using console oriented programming. To solve that
situation we can use the concept file. A file is a place on the computer hard drive where
the set of related data is stored. The advantage of file is that loss data is not possible.
Generally, in computer hard drive, all data is stored in binary file. Let’s see how data
is stored in computer hard drive.
C Program
C Library Functions
Operating System
Binary files are the collection of bytes. Programs are converted into binary files and
stored in computer hard disk. The binary files are the combinations of binary digit 0
and 1. Examples of binary files are program.exe or music stored in wave files or pictures
stored in graphic files.
EXPLANATION:
In the above two lines, the first line: FILE *x; specifies that x is the pointer variable of
data type FILE. Note that FILE is the structures that are defined in the I/O library file.
The second line: x=fopen(“filename”,”mode”); the fopen() function consists of two
parameters. The first parameter ”filename” is the specified path where the data stored
and it is represented in the form of strings. The second parameter “mode” means to
place the mode, i.e., read, write or append, etc. The fopen() function assigns the value
to the file pointer x and it searches the location on the computer hard disk where it
will store the data and to be opened. Then it loads the data from the specified location
in to temporary memory place called buffer. Then it points the first character of buffer.
6) Closing a File
If the file reading from hard drive is finished then we need to close it. This can be done
by using the function fclose().
File 381
TIPS TO REMEMBER
In file concept, the header file is: #include <stdio.h>
(B) “w “(write)mode
The “w”(write) mode used for to open the file for writing purposes. In this mode
when the file does not exist then the file with a name will be created. If the file exists
previously then data of the file is lost and new data is written in that file.
file does not exist then new file is created and if exists new data is appended with
existing data.
This declaration read a character from the file whose file pointer is p. The getc()
function returns an end-of-file(EOF),when end of the file has been reached. Therefore,
when EOF is reached then reading the file is terminated.
1. /*** Program to Read a Character from a File ***/
#include <stdio.h>
void main(void)
{
FILE *p;
char x;
p=fopen(“c:\\new\\a.txt”, “r”);
x=getc(p);
printf(“\nRead character is:%c”,x);
}
Output:
Read Character is: I
EXPLANATION:
Here before executing the program the programmer should create a folder in any hard
drive, i.e., C, D, E, etc. Here I have created in C drive and open a new notepad and
type the character, i.e., I and save it by giving a name with extension txt. Then copy
the path of notepad and paste in place of file name that are enclosed in double quotes
then give comma and again give second double quote and inside it place r for read
mode in the program. Then after writing the complete program run that program and
get the output I.
This declaration writes a character contained in the character variable x to the file
pointer p.
2. /*** Program to Write a Character to a File ***/
#include <stdio.h>
void main(void)
{
FILE *p;
char x;
printf(“Input the character:”);
scanf(“%c”,&x);
p=fopen(“c:\\new\\a.txt”, “w”);
putc(x,p);
fclose(p);
}
Output:
Input the character: r (press enter and close and see a.txt file)
EXPLANATION:
Again I told that before run the above program first creates a folder named new in
any drive, i.e., C or other and inside the folder create a new notepad and save it with
extension txt inside the folder new. Then type the above program in editor and inside
the fopen() function copy the path of the notepad and paste it and then give comma
and again inside the double quotes write w for write purpose. After writing the
complete program run that program. When the message comes, input the character
in that position type the character suppose r and press the enter key then it activates
automatically and internally r stored in a.txt inside new folder. Then open the folder
new and again open a.txt and see the result.
TIPS TO REMEMBER
EOF means end of file.
3. /*C Program of Copying the File from One Location to other Locations*/
#include <stdio.h>
void main(void)
{
FILE *x,*y;
char z;
x=fopen(“d:\\dhabal\\source.txt”, “r”);
y=fopen(“d:\\dhabal\\destin.txt”, “w”);
while((z=getc(x))!=EOF)
putc(z,y);
fclose(x);
fclose(y);
}
384 Concepts and Techniques of Programming in C
Output:
Type the program and run it and see destin.txt
EXPLANATION:
Here in the above program two file pointer variables are declared, i.e., x and y. x
pointer variable holds data, i.e., reading the data from one file and y is another pointer
variable and is used to hold the data that is copied from another pointer variable x.
Before writing the above code first create the folder named dhabal and inside the folder
open two notepads and save as source.txt and other as destin.txt. In source.txt type the
text and save it then copy the path of source.txt and paste into the position of opening
file and assign to pointer variable x and in destin.txt file do not write any text and
copy the path and paste it into respective position of fopen() function and it assign
to pointer variable y . Lastly, type the above program turbo c4.5 editor or other editor
and run it .After run see the text stored in source.txt file are coped into destin.txt file.
4. /* Program to write the String to the File and then Read it*/
#include <stdio.h>
void main(void)
{
FILE *p;
char x[40],y[40];
printf(“\nInput the string: “);
gets(x);
p=fopen(“c:\\new\\a.txt”, “w”);
fputs(x,p);
fclose(p);
p=fopen(“c:\\new\\a.txt”, “r”);
fgets(y,40,p);
printf(“\nThe inputted string is:\n”);
puts(y);
}
Output:
Input the string: DHABAL
The inputted string is: DHABAL
EXPLANATION:
This program demonstrates that user input the strings that are stored in a.txt file and
then it will display on the computer screen. Here user input the string through gets
function and then fopen() function creates a file named as a.txt because we have used
w mode. The function w mode will store the input in file and old value of file will be
erased. The fputs()function will store the input into the created file a.txt. Again fopen()
function is used to read the input data from file and stores in to y variable through
fgets() function and last puts function display the input string.
File 385
Where p is a file pointer that has been opened for writing, the control string contains
the conversion specification character.
5. /*Program to write Data (roll number, name, marks) into a File using fprintf() */
#include <stdio.h>
void main(void)
{
FILE *x;
int roll_no;
char name[20];
float marks;
printf(“\nInput your roll number:”);
scanf(“%d”, &roll_no);
printf(“\nInput your name: “);
fflush(stdin);
gets(name);
printf(“\nInput your marks: “);
scanf(“%f”,&marks);
x=fopen(“c:\\new\\a.txt”, “w”);
fprintf(x,”%d %s %f”, roll_no, name, marks);
fclose(x);
}
386 Concepts and Techniques of Programming in C
Output:
Input:
Input your roll number: 110
Input your name: DHABAL
Input your marks: 80
EXPLANATION:
After running the program when the user types the above input and presses enter by
keyboard then in the background in a.txt, all data is stored in serial. i.e., in a.txt the
data are: 110 DHABAL 80
Output:
Roll_No: 110
Name: DHABAL
Marks: 80.00
EXPLANATION:
Here the output is 110, DHABAL, 80.00 because before running the above program
in a.txt file 110DHABAL89.00 is stored. The fscanf() function reads that and displays
using printf() function.
File 387
Output:
File is not present on hard drive
EXPLANATION:
To test the above program the programmer first create a folder named new in the c
drive then copy the path of the drive and paste it in the fopen() function with double
quotes and second quotes in r mode. You may create the folder in any name with any
drive to store. Since no data exists in a.txt file therefore NULL assigns to x and again x
is compared with NULL. As it matches the output is file does not present on hard drive.
EXPLANATION:
Here fp is a pointer to file, Offset is a number/variable of data-type long, Position is
the integer number.
The offset specifies the number positions/bytes to be moved from current location
to the specified location. The offset may be positive move or negative move. Positive
move means move forward and negative move means move backward.
Value Meaning
0 Starting of file
1 Current position
2 End of the file
fseek(x,0,SEEK_END);
len=ftell(x);
fclose(x);
printf(“Total size of file.txt = %d bytes\n”,len);
}
SUMMARY
1. A file is a place on the computer hard drive where the set of related data is stored.
2. A text file contains textual information where binary files are collection of bytes.
3. Different file operations are: creating a file, opening a file, reading a file, writing
a file and others.
4. The syntax of creating a file is
FILE *x;
5. The syntax of opening a file is
FILE *x;
X=fopen(“file name”,”mode”);
6. The file opening modes are: read mode, write mode, append mode, read and
write mode, write and read mode, append and read mode.
SHORT QUESTIONS
1. Write the general syntax for opening a file named as “sample.txt” stored in a hard
drive.
2. What is file?
3. What is the difference between text file and binary file.
4. What is fseek, ftell and rewind functions.
5. What is the difference between random acess and sequential access.
6. Write short notes on:
(a) getc() function
(b) putc()function
(c) getw() function
(d) putw() function
(e) fprintf() function
(f) fscanf() function.
390 Concepts and Techniques of Programming in C
LONG QUESTIONS
1. What kind of file accesses is possible with C programming? What are the different
modes that a file in C can be handled?
2. Write a program that reads the contents of a file and prints it on the screen.
3. Write a short note on error handling in file management.
MULTIPLE-CHOICE QUESTIONS
1. While opening a file if there is an error, the fopen() function will return____
(a) EOF (b) Nothing
(c) NULL (d) Depends on compiler
[Answer: c]
2. FILE is of ______ type?
(a) chart *type (b) int type (c) struct type (d) none
[Answer: c]
3. In the given syntax ‘a ‘stand for ___?
fp=fopen(“a.txt”,”a”);
(a) add (b) append (c) attach (d) apprehend
[Answer: b]
4. Which type of file cannot opened using fopen() function?
(a) .bin (b) .c (c) .txt (d) none
[Answer: d]
5. Which of the following causes an error?
(a) failure to allocate memory with the help of malloc.
(b) trying to read a file that does not exist.
(c) inability to write data in a file.
(d) all the above [Answer: d]
16
Preprocessor Directive
16.1 INTRODUCTION
The preprocessor directive instructs the compiler to preprocess the information before
the compilation starts. That is, C preprocessor modifies the programming code before
compilation by allowing the conditional compilation using #ifdef, defining the constant
value by using #define, including the header file by using #include directive. The
preprocessor directives are not statements therefore semicolon (;) is not required at the
end. The preprocessor directive is usually placed at the top of the source code with
starting character”#” followed by directive name and an optional white space before
and after it.
They are macro substation directives, Header file inclusion directive, conditional
compilation directive, and other directive.
There are different types of macro substitution directives, i.e., simple macro
substitution directive, argument macro substitution directive and nested macro
substitution directive.
The simple macro defines constant value and can be any of the basic fundamental
data types.
392 Concepts and Techniques of Programming in C
Example:
#define PI 3.14
SUMMARY
SHORT QUESTIONS
LONG QUESTION
MULTIPLE-CHOICE QUESTIONS
For successful run the C program in TURBO C Editor use the following key
1. For compilation press the key ALT and + F9.
2. For running the program press the key CTR and +F9
3. For displacing the output on computer screen press the key ALT and +F5
POINTS TO NOTE:
1. The header file #include<stdio.h> is called the preprocessor directive and its
purpose is to do input and output operation and inform to the c complier before
compilation.
2. The header file of printf(); function and scanf(); function is #include<stdio.h> .
3. The getch(); is a function used in the last portion of the program because when
any key is pressed it only displays the output. If we did not write in the program
then to display the output on the computer screen we can use the key: ALT
and +F5.
4. The header file of getch(); function is #include<conio.h>.
5. The keyword clrscr(); is used to clear the screen whose header file is #include<conio.
h>. After using it, when the programmer runs the program any number of times
then it does not show the previous output and it only displays the current output.
6. The most frequently used header files are:
#include<conio.h> or #include”conio.h” for clear screen and for
getch(); function.
#include<math.h> or #include”math.h” for mathematical operation.
#include<string.h> or #include”string.h” for group of character or
string related operation.
Bibliography
Storage unit 3 U
strcat() function 313 Union 373
String constant 68 V
String handling library functions 310 Variable, accessing a 331
writing a 309 W
displaying a 309 While loop, concepts of 161
Structure 360