USIT101 Imperative Programming
USIT101 Imperative Programming
(IT)
SEMESTER - I (CBCS)
IMPERATIVE PROGRAMMING
SUBJECT CODE : USIT101
© UNIVERSITY OF MUMBAI
Prof. Suhas Pednekar
Vice Chancellor
University of Mumbai, Mumbai.
Prof. Ravindra D. Kulkarni Prof. Prakash Mahanwar
Pro Vice-Chancellor, Director
University of Mumbai. IDOL, University of Mumbai.
Published by : Director
Institute of Distance and Open Learning ,
University of Mumbai,
Vidyanagari, Mumbai - 400 098.
ipin Enterprises
DTP Composed : Varda Offset
Tantiaand Typesetters
Jogani Industrial Estate, Unit No. 2,
Andheri (W), Mumbai - 400 053.Pace Computronics
Ground Floor, Sitaram Mill Compound,
"Samridhi" Paranjpe 'B' Scheme, Vile Parle (E), Mumbai - 57.
Printed by : J.R. Boricha Marg, Mumbai - 400 011
CONTENTS
Chapter No. Title Page No.
Unit I
Chapter 01 Introduction To Imperative Programming.........................................................01
Chapter 02 Programming And User Environments
Understanding Programming Environments......................................................21
Chapter 03 Fundamentals.................................................................................................28
Unit II
Chapter 04 Operators And Expressions - I & II.........................................................51&57
Chapter 05 Data Input And Output...................................................................................72
Unit III
Chapter 06 Conditional Statements...................................................................................88
Chapter 07 Loops..........................................................................................................100
Chapter 08 Functions......................................................................................................111
Unit IV
Chapter 09 Program Structure........................................................................................125
Chapter 10 Preprocessor................................................................................................133
Chapter 11 Array............................................................................................................143
Unit V
Chapter 12 Pointers........................................................................................................157
Chapter 13 Advanced Pointers.......................................................................................165
Chapter 14 Structures And Unions..................................................................................174
*****
Syllabus
B. Sc (Information Technology) Semester – I
Course Name: Imperative Programming Course Code: USIT101
Periods per week (1 Period is 50 minutes) 5
Credits 2
Hours Marks
Evaluation Theory 2½ 75
System Examination - 25
Syllabus
B. Sc (Information Technology) Semester – I
Course Name: Imperative Programming Course Code: USIT1P2
Practical
Periods per week (1 Period is 50 minutes) 3
Credits 2
Hours Marks
Evaluation System Practical Examination 2½ 50
Internal - -
1
INTRODUCTION TO IMPERATIVE
PROGRAMMING
Unit Structure
1.0 Objectives
1.1 Introduction
1.2 Applications of C Programming
1.3 Program Development Life Cycle
1.4 Using Pseudocode Statements And Flowchart Symbols
1.5 Algorithms and Flowchart
1.6 Unit End Questions
1.0 OBJECTIVES
1.1 INTRODUCTION
2
Object Oriented Programming are imperative in style, but added
features to support objects. C++ , JAVA, Perl, Rubey, visual c++ are
object oriented languages & Python languages
3
translated to machine language that represents the millions of on/off
circuits within the computer.
Your programming language statements are called source code, and
the translated machine language statements are object code.
Each programming language uses a piece of software, called a
compiler or an interpreter, to translate your source code into machine
language.
Machine language is also called binary language,and is represented as
a series of 0s and 1s.
The compiler or interpreter that translates your code tells you if any
programming language component has been used incorrectly. Syntax
errors are relatively easy to locate and correct because your compiler
or interpreter highlights them. If you write a computer program using a
language such as C++ but spell one of its words incorrectly or reverse
the proper order of two words, the software lets you know that it found
a mistake by displaying an error message as soon as you try to
translate the program.
After a program’s source code is successfully translated to machine
language, the computer can carry out the program instructions.
When instructions are carried out, a program runs, or executes. some
input will be accepted, some processing will occur, and results will be
the output.
Machine Language:
Assembly Language:
5
comparatively hard. stops. Hence debugging is
easy.
5. Errors are displayed after entire Errors are displayed for
program is checked and every instruction interpreted
Intermediate Object Code is (if any) No Intermediate
Generated Object Code is Generated
6 Programming language like C, Programming language like
C++ use compilers. Python, Ruby use
interpreters.
Features of C Language:
C is the widely used language. It provides many features that are given
below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. Structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1) Simple:
5) Rich Library:
6) Memory Management:
7) Speed:
8) Pointer:
9) Recursion|:
10) Extensible:
To write the first c program, open the C console and write the following
code:
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
int main() The main() function is the entry point of every program in c
language.
return 0 The return 0 statement, returns execution status to the OS. The 0
value is used for successful execution and 1 for unsuccessful execution.
By menu:
Now click on the compile menu then compile sub menu to compile the
c program.
Then click on the run menu then run sub menu to run the c program.
9
By shortcut
Or, press ctrl+f9 keys compile and run the program directly.
You will see the following output on user screen.
You can view the user screen any time by pressing the alt+f5 keys
Programmer for developing the program can not directly start any
program or project. Programmer has to understand whole program or
project, has to analyze the sequence and flow of the program
10
1. Understand the problem.
2. Plan the logic.
3. Code the program.
4. Use software (a compiler or interpreter) to translate the program into
machine language.
5. Test the program.
6. Put the program into production.
7. Maintain the program.
Suppose the manager needs a list of all employees who have been
here over five years, because we want to invite them to a special thank-
you dinner. On the surface, this seems like a simple request. An
experienced programmer, however, will know that the request is
incomplete. For example, you might not know the answers to the
following questions about which employees to include: Does the manager
want a list of full-time employees only, or a list of full and part-time
employees together?
Does she want to include people who have worked for the
company on a month-to month contractual basis over the past five years,
or only regular, permanent employees?
The programmer cannot make any of these decisions; the user must
address these questions to manager.
11
For example, no one knew they wanted to play Angry Birds or
leave messages on Facebook before those applications were developed.
Mobile app developers also must consider a wider variety of user skills
than programmers who develop applications that are used internally in a
corporation. Mobile app developers must make sure their programs work
with a range of screen sizes and hardware specifications because software
competition is intense and the hardware changes quickly.
After the logic is developed, only then can the programmer write
the source code for a Program in a respective programming language. The
logic developed to solve a programming problem can be executed using
any number of languages. Only after choosing a language must the
programmer be concerned with correct syntax.
13
mean simply running the program once, if it was written to satisfy a user‘s
request for a special list then we can finalize the program.
Writing Pseudocode:
Using pseudocode involves writing down all the steps you will use
in a program. Usually, programmers preface their pseudocode with a
beginning statement like start and end it with a terminating statement like
stop. The statements between start and stop look like English and are
indented slightly so that start and stop stand out. Most programmers do not
bother with punctuation such as period sat the end of pseudocode
statements, although it would not be wrong to use them if you prefer that
style. Similarly, there is no need to capitalize the first word in a sentence,
although you might choose to do so. This book follows the conventions of
14
using lowercase letters for verbs that begin pseudocode statements and
omitting periods at the end of statements. Pseudocode is fairly flexible
because it is a planning tool, and not the final product. Therefore, for
example, you might prefer any of the following:
• Instead of start and stop, some pseudocode developers would use the
terms begin and end.
• Instead of writing input myNumber, some developers would write
getmyNumber or read myNumber.
• Instead of writing set myAnswer = myNumber * 2, some developers
would write calculate myAnswer = myNumber times 2 or
computemyAnswer as myNumber doubled.
• Instead of writing output myAnswer, many pseudocode developers
would write display myAnswer, print myAnswer, or write myAnswer.
Algorithms:
1. A sequential solution of any program that written in human language,
called algorithm.
2. Algorithm is first step of the solution process, after the analysis of
problem, programmer write the algorithm of that problem.
3. Example of Algorithms:
Flowchart Symbols:
Here is a chart for some of the common symbols used in drawing
flowcharts.
Example Flowcharts:
Here is the flowchart for going to the market to purchase a pen.
17
If, for example, the input numbers are being entered at the
keyboard, the program will keep accepting numbers and outputting their
doubled values forever. Of course, the user could refuse to type any more
numbers. But the program cannot progress any further while it is waiting
for input; meanwhile, the program is occupying computer memory and
tying up operating system resources.
Any infinite loop in a program has a problem that you can input
values infinite time, processing will be done, result will be displayed.
Loop will be continued infinite times. Solution to stop is turn off your
computer, Solution is to somewhere Refuse input value or stop accepting
input value.
18
Flowchart with sentinel value equal to zero
One drawback to using 0 to stop a program, of course, is that it
won‘t work if the user does need to find the double of 0. In that case, some
other data-entry value that the user never will need, such as 999 or –1,
could be selected to signal that the program should end.
A preselected value that stops the execution of a program is often
called a dummy value because it does not represent real data, but just a
signal to stop. Sometimes, such a value is called a sentinel value because it
represents an entry or exit point, like a sentinel who guards a fortress.
For one thing, an input record might have hundreds of fields, and if
you store a dummy record in every file, you are wasting a large quantity of
storage on ‘‘non data.’’ Additionally, it is often difficult to choose sentinel
values for fields in a company’s data files.
Any balance Due, even a zero or negative number, can be a
legitimate value, and any customerName, even ‘‘ZZ’’, could be someone‘s
name. Fortunately, programming languages can recognize the end of data
in a file automatically, through a code that is stored at the end of the data.
Many programming languages use the terme of (for end of file) to refer to
this marker that automatically acts as a sentinel.
Here In this example, therefore, uses eof to indicate the end of data
whenever using a dummy value is impractical or inconvenient. In the
flowchart shown in Fig. 1.10, the eof question is shaded.
19
1.6 UNIT END QUESTIONS
1. What is Imperative Programming? What are its Types?
2. Write a Difference between Compiler and Interpreter.
3. Explain History of C Programming Language.
4. Enlist Features of C Programming. Explain any 4 in Brief.
5. Explain Program Development Life Cycle in Detail.
6. What is Flowchart ? What is the use of Flowchart?
*****
20
2
PROGRAMMING AND USER
ENVIRONMENTS UNDERSTANDING
PROGRAMMING ENVIRONMENTS
Unit Structure
2.0 Objectives
2.1 Introduction
2.2 Understanding the evolution of programming models:
2.3 Unit End Questions
2.0 OBJECTIVES
A text editor is a program that you use to create simple text files. It is
similar to a word processor, but without as many features.
21
You can use a text editor such as Notepad that is included with
Microsoft Windows. The C Developing Environment is a screen display
with windows and pull-down menus. The program listing, error messages
and other information are displayed in separate windows.
2.1 INTRODUCTION
A window will appear on the screen where the program may be typed.
22
Writing a Program in Turbo C:
When the Edit window is active, the program may be typed. Use
the certain key combinations to perform specific edit functions.
To save the program, select save command from the file menu.
This function can also be performed by pressing the [F2] button. A dialog
box will appear asking for the path and name of the file. Provide an
appropriate and unique file name. You can save the program after
compiling too but saving it before compilation is more appropriate
All the above steps can be done by using Run option from the menu bar or
using key combination
23
two ways to do this: you can select Make EXE from the compile menu, or
you can press the [F9] key
Correcting Errors in Turbo C:
If the compiler recognizes some error, it will let you know through
the Compiler window. You‘ll see that the number of errors is not listed as
0, and the word ―Error‖ appears instead of the word ―Success‖ at the
bottom of the window. The errors are to be removed by returning to the
edit window.
Usually these errors are a result of a typing mistake. The compiler
will not only tell you what you did wrong, they‘ll point you to the exact
place in your code where you made the mistake.
Executing a Programs in Turbo C:
If the program is compiled and linked without errors, the program
is executed by selecting Run from the Run Menu or by pressing the
[Ctrl+F9] key combination.
24
Software technology has a growth of a tree. Software evolution has
a layer of growth. Each layer representing an improvement over the
previous one.
25
For example, object-oriented programmers might design a payroll
application by thinking about employees and paychecks, and by describing
their attributes. Employees have names and Social
1. Integrity:
2. Clarity:
3. Simplicity:
4. Efficiency:
It is concerned with execution speed and efficient memory
utilization. Many complex programs require a tradeoff between these
characteristics. Hence experience and common sense are key factors are
used to increase efficiency of the program.
5. Modularity:
6. Generality:
*****
27
3
FUNDAMENTALS
Unit Structure
3.0 Objectives
3.1 Introduction
3.2 Program Structure
3.3 The C Character Set
3.4 Data Types In C Language
3.5 C Expressions
3.6 Symbolic Constants In C Language
3.7 Unit End Questions
3.0 OBJECTIVES
Structure of a C Program:
Every C program consists of one or more modules called
functions. One of the functions must be called main.
28
book. For now, the reader should be concerned only with an overview of
the basic features that characterize most C programs.
3.1 INTRODUCTION
The comments at the end of each line have been added in order to
emphasize the overall program organization.
29
4. The third line is a heading for the function main. The empty
parentheses following the name of the function indicate that this
function does not include any arguments.
5. The remaining five lines of the program are indented and enclosed
within a pair of braces. These five lines comprise the compound
statement within main.
6. The first indented line is a variable declaration. It establishes the
symbolic names radius and area as floating-point variables (more
about this in the next chapter).
7. The remaining four indented lines are expression statements. The
second indented line ( p r i n t f ) generates a request for information
(namely, a value for the radius). This value is entered into the
computer via the third indented line (scanf).
8. The fourth indented line is a particular type of expression statement
called an assignment statement. This statement causes the area to be
calculated from the given value of the radius. Within this statement the
asterisks (*) represent multiplication signs.
9. The last indented line ( p r i n t f ) causes the calculated value for the
area to be displayed. The numerical value will be preceded by a brief
label.
10. Notice that each expression statement within the compound statement
ends with a semicolon. This is required of all expression statements.
Radius = 7 3
Area = 28.274309
Let us look at a simple code that would print the words "Hello World":
#include intmain()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
Let us see how to save the source code in a file, and how to compile and
run it. Following are the simple steps:
1. Open a text editor and add the above-mentioned code.
2. Save the file as hello.c
3. Open a command prompt and go to the directory where you have
saved the file.
4. Type gcchello.c and press enter to compile your code.
5. If there are no errors in your code, the command prompt will take you
to the next line and would generate a.out executable file.
6. Now, type a.out to execute your program.
7. You will see the output "Hello World" printed on the screen.
$ gcchello.c
$ ./a.out
31
Hello, World!
Make sure the gcc compiler is in your path and that you are running it in
the directory containing the source file hello.c.
Most versions of the language also allow certain other characters, such as
@ and $, to be included within strings and comments.
TABLE
Keywords:
Data types specify how we enter data into our programs and what
type of data we enter. C language has some predefined set of data types to
handle various kinds of data that we use in our program. These data types
have different storage capacities.
33
The array types and structure types are referred collectively as the
aggregate types. The type of a function specifies the type of the function's
return value. We will see the basic types in the following section, where as
other types will be covered in the upcoming chapters.
Integer Types:
The following table provides the details of standard integer types
with their storage sizes and value ranges
Type Storage size Value range
Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to
2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 8 bytes -9223372036854775808 to
9223372036854775807
unsigned long 8 bytes 0 to 18446744073709551615
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
int main(intargc, char** argv) {
printf("CHAR_BIT : %d\n", CHAR_BIT);
printf("CHAR_MAX : %d\n", CHAR_MAX);
printf("CHAR_MIN : %d\n", CHAR_MIN);
printf("INT_MAX : %d\n", INT_MAX);
printf("INT_MIN : %d\n", INT_MIN);
printf("LONG_MAX : %ld\n", (long) LONG_MAX);
printf("LONG_MIN : %ld\n", (long) LONG_MIN);
printf("SCHAR_MAX : %d\n", SCHAR_MAX);
printf("SCHAR_MIN : %d\n", SCHAR_MIN);
printf("SHRT_MAX : %d\n", SHRT_MAX);
printf("SHRT_MIN : %d\n", SHRT_MIN);
printf("UCHAR_MAX : %d\n", UCHAR_MAX);
printf("UINT_MAX : %u\n", (unsigned int) UINT_MAX);
printf("ULONG_MAX : %lu\n", (unsigned long) ULONG_MAX);
printf("USHRT_MAX : %d\n", (unsigned short) USHRT_MAX);
return 0;
}
34
When you compile and execute the above program, it produces the
following result on Linux −
CHAR_BIT :8
CHAR_MAX : 127
CHAR_MIN : -128
INT_MAX : 2147483647
INT_MIN : -2147483648
LONG_MAX : 9223372036854775807
LONG_MIN : -9223372036854775808
SCHAR_MAX : 127
SCHAR_MIN : -128
SHRT_MAX : 32767
SHRT_MIN : -32768
UCHAR_MAX : 255
UINT_MAX : 4294967295
ULONG_MAX : 18446744073709551615
USHRT_MAX : 65535
Floating-Point Types:
The following table provide the details of standard floating-point types
with storage sizes and value ranges and their precision
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 6 decimal places
3.4E+38
double 8 byte 2.3E-308 to 15 decimal
1.7E+308 places
long double 10 byte 3.4E-4932 to 19 decimal
1.1E+4932 places
The header file float.h defines macros that allow you to use these
values and other details about the binary representation of real numbers in
your programs. The following example prints the storage space taken by a
float type and its range values
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
35
printf("DBL_MAX : %g\n", (double) DBL_MAX);
printf("DBL_MIN : %g\n", (double) DBL_MIN);
printf("-DBL_MAX : %g\n", (double) -DBL_MAX);
printf("Precision value: %d\n", FLT_DIG );
return 0;
}
When you compile and execute the above program, it produces the
following result on Linux −
Storage size for float : 4
FLT_MAX : 3.40282e+38
FLT_MIN : 1.17549e-38
-FLT_MAX : -3.40282e+38
-FLT_MIN : -1.17549e-38
DBL_MAX : 1.79769e+308
DBL_MIN : 2.22507e-308
-DBL_MAX : -1.79769e+308
Precision value: 6
The void type specifies that no value is available. It is used in three kinds
of situations
Sr.No. Types & Description
1 Function returns as void
There are various functions in C which do not return any
value or you can say they return void. A function with no
return value has the return type as void. For example, void
exit (int status);
2 Function arguments as void
There are various functions in C which do not accept any
parameter. A function with no parameter can accept a void.
For example, int rand(void);
3 Pointers to void
A pointer of type void * represents the address of an object,
but not its type. For example, a memory allocation function
void *malloc(size_t size ); returns a pointer to void which can
be casted to any data type.
36
Constants:
Constants are of fixed values that do not change during the
execution of a program. There are various types of constants. The types
are illustrated in the following figure.
Integer constants:
Real constants: Real constants are used to represent quantities that are
very continuously, such as distances, temperature etc. These quantities are
represented by numbers containing fractional parts.
Examples,
0.00832 -0.75 33.337
Single character constants: A single character constants contains a single
character enclosed within a pair of single quote marks.
Example, ‗5
‘X’ ‘:’
String constants : A string constant contains a string of characters
enclosed within a pair of double quote marks. Examples, ‘‘Hello !’’
‘‘1987’’
Variables:
Type Description
Char Typically a single octet (one byte). This is an
integer type.
int The most natural size of integer for the machine
float A single-precision floating point value.
double A double-precision floating point value
void Represents the absence of type. C
Variable Definition in C:
A variable definition tells the compiler where and how much
storage to create for the variable. A variable definition specifies a data
type and contains a list of one or more variables of that type as follows:
typevariable_list;
38
Here, type must be a valid C data type including char, w_char, int,
float, double, bool, or any user-defined object; and variable_list may
consist of one or more identifier names separated by commas. Some valid
declarations are shown here: Variable Definition in C :A variable
definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of
one or more variables of that type as follows:
inti, j, k;
char c, ch;
float f salary;
double d;
C –Arrays:
39
Declaring Arrays :
typearrayName [ arraySize ];
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double
numbers.
Initializing Arrays:
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write −
You will create exactly the same array as you did in the previous
example. Following is an example to assign a single element of the
array −
40
balance[4] = 50.0;
The above statement assigns the 5th element in the array with a
value of 50.0. All arrays have 0 as the index of their first element which is
also called the base index and the last index of an array will be total size of
the array minus 1. Shown below is the pictorial representation of the array
we discussed above –
The above statement will take the 10th element from the array and
assign the value to salary variable. The following example Shows how to
use all the three above mentioned concepts viz. declaration, assignment,
and accessing arrays –
#include <stdio.h>
int main () {
return 0;
}
41
When the above code is compiled and executed, it produces the
following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Arrays in Detail:
Arrays are important to C and should need a lot more attention.
The following important concepts related to array should be clear to a C
programmer
3.5 C EXPRESSIONS
Arithmetic expressions
Relational expressions
Logical expressions
42
Conditional expressions
For example:
1. x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after
the equal is an expression.
Arithmetic Expressions:
An arithmetic expression is an expression that consists of operands
and arithmetic operators. An arithmetic expression computes a value of
type int, float or double.
43
When both the operands are of type integer, then arithmetic will be
performed, and the result of the operation would be an integer value.
For example, 3/2 will yield 1 not 1.5 as the fractional part is ignored.
When both the operands are of type float, then arithmetic will be
performed, and the result of the operation would be a real value. For
example, 2.0/2.0 will yield 1.0, not 1.
If one operand is of type integer and another operand is of type real,
then the mixed arithmetic will be performed. In this case, the first
operand is converted into a real operand, and then arithmetic is
performed to produce the real value. For example, 6/2.0 will yield 3.0
as the first value of 6 is converted into 6.0 and then arithmetic is
performed to produce 3.0.
Relational Expressions:
A relational expression is an expression used to compare two
operands.
It is a condition which is used to decide whether the action should be
taken or not.
In relational expressions, a numeric value cannot be compared with the
string value.
The result of the relational expression can be either zero or non-zero
value. Here, the zero value is equivalent to a false and non-zero value
is equivalent to true.
Relational Description
Expression
x%2 = = 0 This condition is used to check whether the x is an
even number or not.
The relational expression results in value 1 if x is an
even number otherwise results in value 0.
a!=b It is used to check whether a is not equal to b.
44
This relational expression results in 1 if a is not equal
to b otherwise 0.
a+b = = x+y It is used to check whether the expression "a+b" is
equal to the expression "x+y".
a>=9 It is used to check whether the value of a is greater
than or equal to 9.
Let's see a simple example:
1. #include <stdio.h>
2. int main()
3. {
4.
5. int x=4;
6. if(x%2==0)
7. {
8. printf("The number x is even");
9. }
10. else
11. printf("The number x is not even");
12. return 0;
13. }
Output :
Logical Expressions:
A logical expression is an expression that computes either a zero or
non-zero value.
It is a complex test condition to take a decision.
Let's see some example of the logical expressions.
Logical Expressions Description
( x > 4 ) && ( x < 6 ) It is a test condition to check
45
whether the x is greater than 4 and
x is less than 6. The result of the
condition is true only when both the
conditions are true.
x > 10 || y <11 It is a test condition used to check
whether x is greater than 10 or y is
less than 11. The result of the test
condition is true if either of the
conditions holds true value.
! ( x > 10 ) && ( y = = 2 ) It is a test condition used to check
whether x is not greater than 10 and
y is equal to 2. The result of the
condition is true if both the
conditions are true.
Output
46
1. #include <stdio.h>
2. int main()
3. {
4. int x = 4;
5. int y = 9;
6. if ( (x <6) || (y>10))
7. {
8. printf("Condition is true");
9. }
10. else
11. printf("Condition is false");
12. return 0;
13. }
Output
Conditional Expressions:
A conditional expression is an expression that returns 1 if the
condition is true otherwise 0.
A conditional operator is also known as a ternary operator.
The Syntax of Conditional operator:
Output:
Statements:
48
The fourth expression statement causes the printf function to be
evaluated. This is a standard C library function that writes information out
of the computer (more about this in Sec. 3.6). In this case, the message
Area = will be displayed, followed by the current value of the variable
area. Thus, if area represents the value loo., the statement will generate the
message
Area = 100.
49
Here,FLAG and PI are symbolic constants.For better readability,it is
advisable to use uppercase character in the naming of symbolic
constants.see there is no semicolon ‘;’ at the end.
Program:
/* program illustrating use of declaration,assignment of value to
variables.also explains how to use symbolic constants.
#include<stdio.h>
#include<conio.h>
void main ()
}
OUTPUT :
AREA OF CIRCLE =78.537498
CIRCUMFERENCE OF CIRCLE =31.415001
*****
50
4I
OPERATORS AND EXPRESSIONS - I
Unit Structure
4I.0 Objectives
4I.1 Introduction
4I.2 Unary Operators
4I.3 Unit End Questions
4I.0 OBJECTIVES
4I.1 INTRODUCTION
ARITHMETIC OPERATORS:
There are five arithmetic operators in C. They are
Operator Purpose
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after integer division
EXAMPLE - Suppose that A and B are integer variables whose values are
10 and 3, respectively. Several arithmetic expressions involving these
variables - are shown below, together with their resulting values.
Expression Value
A+B 13
A–B 7
A*B 30
A/B 3
A%B 1
Also, notice the integer remainder resulting from the use of the
modulus operator in the last expression.
Note that the unary minus operation is distinctly different from the
arithmetic operator which denotes subtraction (-). The subtraction operator
requires two separate operands.
EXAMPLE 3.10 Here are several examples which illustrate the use of the
unary minus operation
These operators all fall within the same precedence group, which is
lower than the arithmetic and unary operators. The associativity of these
operators is left to right.
Operator Meaning
== equal to
!= not equal to
53
expressions will be of type integer, since true is represented by the integer
value 1 and false is represented by the value 0.
Operator Meaning
&& And
II Or
These operators are referred to as logical and and logical or, respectively.
The logical operators act upon operands that are themselves logical
expressions. The net effect is to combine the individual logical
expressions into more complex conditions that are either true or false. The
result of a logical and operation will be true only if both operands are true,
whereas the result of a logical or operation will be true if either operand is
true or if both operands are true. In other words, the result of a logical or
operation will be false only if both operands are false.
In this context it should be pointed out that any nonzero value, not just 1,
is interpreted as true.
The first expression is true because both operands are true. In the
second expression, both operands are again true; hence the overall
expression is true. The third expression is false because the second
54
operand is false. And finally, the fourth expression is true because the first
operand is true.
Assignment Operators :
EXAMPLE - Here are some typical assignment expressions that make use
of the = operator.
a=3
x=y
delta = 0.001
sum = a + b
55
When evaluating a conditional expression, expression 1 is
evaluated first. If expression 1 is true (i.e., if its value is nonzero), then
expression 2 is evaluated and this becomes the value of the conditional
expression. However, if expression 1 is false (i.e., if its value is zero), then
expression 3is evaluated and this becomes the value of the conditional
expression. Note that only one of the embedded expressions (either
expression 2 or expression 3) is evaluated when determining the value of a
conditional expression.
(f<g)?f :g
56
4II
OPERATORS AND EXPRESSIONS – II
Unit Structure
4II.0 Objectives
4II.1 Introduction
4II.2 Operators Precedence In C
4II.2 Unit End Questions
4II.0 OBJECTIVES
We will, in this chapter, look into the way each operator works.
4II.1 INTRODUCTION
Arithmetic Operators:
Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &|, and ^ is as follows
59
Operator Description Example
Here, operators with the highest precedence appear at the top of the
table, those with the lowest appear at the bottom. Within an expression,
higher precedence operators will be evaluated first.
Arithmetic Operator:
Example:
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf(“Value of c is %d\n”, c );
c = a - b;
printf(“Value of c is %d\n”, c );
c = a * b;
printf(“Value of c is %d\n”, c );
c = a / b;
printf(“Value of c is %d\n”, c );
c = a % b;
printf(“Value of c is %d\n”, c );
c = a++;
printf(“Value of c is %d\n”, c );
c = a—;
printf(“Value of c is %d\n”, c );
Result :
Value of c is 31
62
Value of c is 11
Value of c is 210
Value of c is 2
Value of c is 1
Value of c is 21
Value of c is 22
Relational Operator
Example:
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf(“a is equal to b\n” );
} else {
printf(“a is not equal to b\n” );
}
if ( a < b ) {
printf(“a is less than b\n” );
} else {
printf(“a is not less than b\n” );
}
if ( a > b ) {
printf(“a is greater than b\n” );
} else {
printf(“a is not greater than b\n” );
}
if ( a <= b ) {
printf(“a is either less than or equal to b\n” );
}
if ( b >= a ) {
printf(“b is either greater than or equal to b\n” );
}
}
63
Result:
a is not equal to b
a is not less than b
a is greater than b
a is either less than or equal to b
b is either greater than or equal to b
Logical Operator
Example :
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf(“Condition is true\n” );
}
if ( a || b ) {
printf(“Condition is true\n” );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b ) {
printf(“Condition is true\n” );
} else {
printf(“Condition is not true\n” );
}
if ( !(a && b) ) {
printf(“Condition is true\n” );
}
Result :
Condition is true
Condition is true
64
Bitwise Operator
Example:
#include <stdio.h>
main() {
c = a | b; /* 61 = 0011 1101 */
printf(“Value of c is %d\n”, c );
c = a ^ b; /* 49 = 0011 0001 */
printf(“Value of c is %d\n”, c );
Result:
Value of c is 12
Value of c is 61
Value of c is 49
Value of c is -61
Value of c is 240
Value of c is 15
Assignment Operator
Example:
#include <stdio.h>
main() {
int a = 21;
int c ;
c = a;
65
printf(“= Operator Example, Value of c = %d\n”, c );
c += a;
printf(“+= Operator Example, Value of c = %d\n”, c );
c -= a;
printf(“-= Operator Example, Value of c = %d\n”, c );
c *= a;
printf(“*= Operator Example, Value of c = %d\n”, c );
c /= a;
printf(“/= Operator Example, Value of c = %d\n”, c );
c = 200;
c %= a;
printf(“%= Operator Example, Value of c = %d\n”, c );
c <<= 2;
printf(“<<= Operator Example, Value of c = %d\n”, c );
c >>= 2;
printf(“>>= Operator Example, Value of c = %d\n”, c );
c &= 2;
printf(“&= Operator Example, Value of c = %d\n”, c );
c ^= 2;
printf(“^= Operator Example, Value of c = %d\n”, c );
c |= 2;
printf(“|= Operator Example, Value of c = %d\n”, c );
Result:
= Operator Example, Value of c = 21
+= Operator Example, Value of c = 42
-= Operator Example, Value of c = 21
*= Operator Example, Value of c = 441
/= Operator Example, Value of c = 21
%= Operator Example, Value of c = 11
<<= Operator Example, Value of c = 44
>>= Operator Example, Value of c = 11
&= Operator Example, Value of c = 2
^= Operator Example, Value of c = 0
|= Operator Example, Value of c = 2
66
Size of and ternary operator
Example:
#include <stdio.h>
main() {
int a = 4;
short b;
double c;
int* ptr;
Result:
Size of variable a=4
Size of variable b=2
Size of variable c= 8
value of a is 4
*ptr is 4.
Value of b is 30
Value of b is 20
Operators Precedence
Example:
#include <stdio.h>
main() { int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
67
e = (a + b) * c / d; // ( 30 * 15 ) / 5
printf(“Value of (a + b) * c / d is : %d\n”, e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
printf(“Value of ((a + b) * c) / d is : %d\n” , e );
e = (a + b) * (c / d); // (30) * (15/5)
printf(“Value of (a + b) * (c / d) is : %d\n”, e );
e = a + (b * c) / d; // 20 + (150/5)
printf(“Value of a + (b * c) / d is : %d\n” , e );
return 0;
}
Result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
C – Library functions:
Library functions in C language are inbuilt functions which are
grouped together and placed in a common place called library.
Each library function in C performs specific operation.
We can make use of these library functions to get the pre-defined
output instead of writing our own code to get those outputs.
These library functions are created by the persons who designed and
created C compilers.
All C standard library functions are declared in many header files
which are saved as file_name.h.
Actually, function declaration, definition for macros are given in all
header files.
We are including these header files in our C program using
“#include<file_name.h>” command to make use of the functions those
are declared in the header files.
When we include header files in our C program using
“#include<filename.h>” command, all C code of the header files are
included in C program. Then, this C program is compiled by compiler
and executed.
List Of Most Used Header Files In C Programming Language:
Check the below table to know all the C library functions and header
files in which they are declared.
Click on the each header file name below to know the list of inbuilt
functions declared inside them.
Header file Description
stdio.h This is standard input/output header file in which
Input/Output functions are declared
conio.h This is console input/output header file
68
string.h All string related functions are defined in this
header file
stdlib.h This header file contains general functions used
in C programs
math.h All maths related functions are defined in this
header file
time.h This header file contains time and clock related
functions
ctype.h All character handling functions are defined in
this header file
stdarg.h Variable argument functions are declared in this
header file
signal.h Signal handling functions are declared in this file
setjmp.h This file contains all jump functions
locale.h This file contains locale functions
errno.h Error handling functions are given in this file
assert.h This contains diagnostics functions
LIBRARY FUNCTIONS
The C language is accompanied by a number of library functions
that carry out various commonly used operations or calculations. These
library functions are not a part of the language per se, though all
implementations of the language include them. Some functions return a
data item to their access point; others indicate whether a condition is true
or false by returning a 1 or a 0, respectively; still others carry out specific
operations on data items but do not return anything. Features which tend
to be computer-dependent are generally written as library functions.
For example, there are library functions that carry out standard
input/output operations (e.g., read and write characters, read and write
numbers, open and close files, test for end of file, etc.), functions that
perform operations on characters (e.g., convert from lower- to uppercase,
test to see if a character is uppercase, etc.), functions that perform
operations on strings (e.g., copy a string, compare strings, concatenate
strings, etc.), and functions that carry out various mathematical
calculations (e.g., evaluate trigonometric, logarithmic and exponential
functions, compute absolute values, square roots, etc.). Other kinds of
library functions are also available.
Library functions that are functionally similar are usually grouped
together as (compiled) object programs in separate library files. These
library files are supplied as a part of each C compiler. All C compilers
contain similar groups of library functions, though they lack precise
standardization. Thus there may be some variation in the library functions
that are available in different versions of the language.
A typical set of library functions will include a fairly large number
of functions that are common to most C compilers, such as those shown in
Table 3-2 below. Within this table, the column labeled “type” refers to the
69
data type of the quantity that is returned by the function. The void entry
shown for function and indicates that nothing is returned by this function.
A library function is accessed simply by writing the function name,
followed by a list of arguments that represent information being passed to
the function. The arguments must be enclosed in parentheses and
separated by commas. The arguments can be constants, variable names, or
more complex expressions. The parentheses must be present, even if there
are no arguments.
A function that returns a data item can appear anywhere within an
expression, in place of a constant or an identifier (Le., in place of a
variable or an array element). A function that carries out operations on
data items but does not return anything can be accessed simply by writing
the function name, since this type of function reference constitutes an
expression statement.
Function Type Purpose
abs (i) Int Return the absolute value of i.
ceil (d) double Round up to the next integer
value (the smallest integer that is
greater than or equal to d).
cos (d) double Return the cosine of d.
cosh (d) double Return the hyperbolic cosine of d.
exp(d) double Raise e to the power d (e =
2.7182818 * is the base of the
natural (Naperian) system of
logarithms).
fabs (d) double Return the absolute value of d.
floor (d) double Round down to the next integer
value (the largest integer that
does not exceed d).
fmod (d1,d2) double Return the remainder (i.e., the
noninteger part of the quotient) of
d1 /d2, with same sign as d1 .
Getchar() Int Enter a character from the
standard input device.
log ( d ) double Return the natural logarithm of d.
pow(d1,d2) double Return dl raised to the d2 power.
printf( ...) Int Send data items to the standard
output device
putchar(c) Int Send a character to the standard
output device.
rand( ) Int Return a random positive integer.
sin (d) double Return the sine of d.
sqrt(d) double Return the square root of d
srand (u) Void Initialize the random number
generator
scanf( ...) Int Enter data items from the
standard input device
70
tan (d) double Return the tangent of d.
toascii(c) Int Convert value of argument to
ASCII.
tolower (c) Int Convert letter to lowercase
toupper(c) . Int Convert letter to uppercase
Note: Type refers to the data type of the quantity that is returned by the
function
c - denotes a character-type argument
i - denotes an integer argument
d - denotes a double-precision argument
u - denotes an unsigned integer argument
EXAMPLE - Lowercase to Uppercase Character Conversion Here is a
complete C program that reads in a lowercase character, converts it to
uppercase and then displays the uppercase equivalent.
/* read a lowercase character and display its uppercase equivalent */
#include <stdio.h>
#include <ctype.h>
main ( )
{
int lower, upper;
lower = getchar();
upper = toupper(lower);
putchar(upper);
}
This program contains three library functions: getchar, toupper and
putchar. The first two functions each return a single character (getchar
returns a character that is entered from the keyboard, and to upper returns
the uppercase equivalent of its argument). The last function (putchar)
causes the value of the argument to be displayed.
Notice that the last two functions each have one argument but the
first function does not have any arguments, as indicated by the empty
parentheses.
Also, notice the preprocessor statements #include <stdio. h> and
#include <ctype. h>, which appear at the start of the program. These
statements cause the contents of the files stdio. h and ctype .h to be
inserted into the program the compilation process begins. The information
contained in these files is essential for the proper functioning of the library
functions getchar, putchar and toupper.
4.II UNIT END QUESTIONS
1. What is the use of sizeof & ternary operator ?
2. Explain Operators Precedence in C .
3. Write a Program to Demonstrate Bitwise Operator
4. Write a Program to Demonstrate Logical Operator
5. What are the Library functions ? Explain with example.
*****
71
5
DATA INPUT AND OUTPUT
Unit Structure
5.0 Objectives
5.1 Introduction
5.2 Unit End Questions
5.0 OBJECTIVES
The names of those functions that return data items may appear
within expressions, as though each function reference were an ordinary
variable (e.g., c = getchar ( ) ;), or they may be referenced as separate
statements (e.g., scanf ( . . . ) ;). Some functions do not return any data
items. Such functions are referenced as though they were separate
statements (e.g., putchar ( . . . ) ;).
5.1 INTRODUCTION
72
#include <stdio.h>
main ( )
{
char c,d; /* declarations *I
float x,y;
int i , j ,0 k ;
void main()
{
73
// defining a variable
int i;
/*
*/
scanf("%d", &i);
/*
When you will compile the above code, it will ask you to enter a
value. When you will enter the value, it will display the value you have
entered on screen.
74
int i = printf("studytonight");
In this program printf("study tonight"); will return 12 as result, which will
be stored in the variable i, because studytonight has 12 characters.
void main( )
{
int c;
printf("Enter a character");
/*
*/
c = getchar();
/*
When you will compile the above code, it will ask you to enter a value.
When you will enter the value, it will display the value you have entered.
The gets and puts functions offer simple alternatives to the use of
scanf and printf for reading and displaying strings, as illustrated in the
following example.
This program utilizes gets and puts, rather than scanf and printf, to
transfer the line of text into and out of the computer.
The gets() function reads a line from stdin(standard input) into the
buffer pointed to by str pointer, until either a terminating newline or EOF
(end of file) occurs. The puts() function writes the string str and a trailing
newline to stdout.
str → This is the pointer to an array of chars where the C string is stored.
(Ignore if you are not able to understand this now.)
#include<stdio.h>
void main()
{
/* character array of length 100 */
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
When you will compile the above code, it will ask you to enter a
string. When you will enter the string, it will display the value you have
entered.
Difference between scanf() and gets():
The main difference between these two functions is that scanf()
stops reading characters when it encounters a space, but gets() reads space
as character too.
76
If you enter name as Study Tonight using scanf() it will only read
and store Study and will leave the part after space. But gets() function will
read it completely
77
#include<stdio.h>
int main()
char c;
c=getchar();
putchar(c);
return 0;
78
arguments in the scanf function actually represent the addresses of the data
items being entered.)
d decimal integer
e floating point value
f floating point value
h short integer
i decimal, hexadecimal or octal
integer
o hexadecimal
x integer octal integer
s string
u unsigned decimal integer
79
Example 1:
#include<stdio.h>
int main()
char a[20];
int i;
float b;
return 0;
In the above program, within the scanf function, the control string
is "%s %d %f". It denotes three-character groups or format specifiers. The
first format specifier %s denotes that the first argument a represents a
string (character array), the second format specifier %d denotes that the
second argument i is an integer and the third format specifier %f denotes
that the third argument b is a floating point number.
80
stop reading any more characters and will terminate the string. A null
character will then automatically be added to the end of the string.
Example:
#include<stdio.h>
int main()
char line[80];
printf("%s", line);
return 0;
then the entire data will be assigned to the array line. However, if the input
is:
Example:
scanf("[^n]", line);
81
conversion character. The input data may contain fewer characters than
the specified field width. Extra characters will be ignored.
Example: If a and b are two integer variables and the following statement
is being used to read their values:
Example 1: C Output:
#include <stdio.h>
int main()
{
Output:
C Programming
#include <stdio.h>
int main()
{
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;
}
#include <stdio.h>
int main()
{
int testInteger = 5;
82
printf("Number = %d", testInteger);
return 0;
}
Output
Number = 5
Example 3: float and double Output
#include <stdio.h>
int main()
{
return 0;
}
Output
number1 = 13.500000
number2 = 12.400000
Output
character = a
83
Output
Enter an integer: 4
Number = 4
#include <stdio.h>
int main()
{
float num1;
double num2;
return 0;
}
Output
Enter a number: 12.523
Enter another number: 10.2
num1 = 12.523000
num2 = 10.200000
char chr;
printf("Enter a character: ");
scanf("%c",&chr);
printf("You entered %c.", chr);
return 0;
Output
Enter a character: g
You entered g.
84
Example 8: ASCII Value:
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);
Output
Enter a character: g
You entered g.
ASCII value is 103.
Output
Enter integer and then a float: -3
3.4
You entered -3 and 3.400000
Here's a list of commonly used C data types and their format specifiers.
Data Type Format Specifier
int %d
char %c
float %f
85
double %lf
short int %hd
unsigned int %u
long int %li
long long int %lli
unsigned long int %lu
unsigned long long int %llu
signed char %c
unsigned char %c
long double %Lf
Notice that two statements are associated with each input data
item. The first is a printf statement, which generates a request for the item.
The second statement, a scanf function, causes the data item to be entered
from the standard input device (i.e., the keyboard).
After the student's name and all three exam scores have been
entered, an average exam score is calculated. The input data and the
calculated average are then displayed, as a result of the group of printf
statements at the end of the program.
*****
87
UNIT II
6
CONDITIONAL STATEMENTS
Unit Structure
6.0 Objectives
6.1 Introduction
6.2 Unit End Questions
6.0 OBJECTIVES
All of these operations can be carried out using the various control
statements included in C. We will see how this is accomplished in this
chapter. The use of these statements will open the door to programming
problems that are much broader and more interesting than those
considered earlier.
88
6.1 INTRODUCTION
Decision Making:
Decision making structures require that the programmer specifies
one or more conditions to be evaluated or tested by the program, along
with a statement or statements to be executed if the condition is
determined to be true, and optionally, other statements to be executed if
the condition is determined to be false.
The ? : Operator
We have covered conditional operator ? : in the previous chapter
which can be used to replace if...else statements. It has the following
general form –
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and
placement of the colon.
Decision making in C:
90
The if statement may be implemented in different forms depending
on the complexity of conditions to be tested. The different forms are,
1. Simple if statement
2. if....else statement
3. Nested if....else statement
4. Using else if statement
Relational Operators:
Example
#include <stdio.h>
main() {
int a = 19;
int b = 9;
int c ;
if( a == b ) {
printf("a is equal to b \n" );
} else {
printf("a is not equal to b \n" );
}
91
if ( a < b ) {
printf("a is less than b \n" );
} else {
printf("a is not less than b \n" );
}
if ( a > b ) {
printf("a is greater than b \n" );
} else {
printf("a is not greater than b \n" );
}
if ( a <= b ) {
printf("a is either less than or equal to b\n" );
}
if ( b >= a ) {
printf("b is either greater than or equal to b\n" );
}
}
Result:
a is not equal to b
a is not less than b
a is greater than b
a is either less than or equal to b
b is either greater than or equal to b
Logical Connectives:
EXAMPLE 6.2:
Here are some logical expressions that illustrate the use of the logical
connectives and the negation
operator.
(count <= 100) && (ch1 != ' * ')
(balance < 1000.0) || (status == 'R')
(answer < 0) || ((answer > 5.0) && (answer <= 10.0))
! ((pay >= 1000.0) && (status == 's'))
92
Note that ch1 and status are assumed to be char-type variables in
these examples. The remaining variables are assumed to be numeric
(either integer or floating-point). Since the relational and equality
operators have a higher precedence than the logical operators, some of the
parentheses are not needed in the above expressions. Thus, we could have
written these expressions as
count <= 100 && ch1 != '*'
balance < 1000.0 || status == 'R'
answer < 0 || answer > 5.0 && answer <= 10.0
! (pay >= 1000.0 && status == 's')
Example:
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf(“Condition is true\n" );
}
if ( a || b ) {
printf("Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
93
b = 10;
if ( a && b ) {
printf("Condition is true\n" );
} else {
printf("Condition is not true\n" );
}
if ( !(a && b) ) {
printf("Condition is true\n" );
}
}
Result:
Condition is true
Condition is true
Condition is not true
Condition is true
Simple if statement:
Syntax of if statement
if (condition)
statements;
... ... ...
Example 1 :
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}
94
OUTPUT:
x is greater than y
Flowchart:
Output
Enter a number:6
6 is less than 10
Square = 36
95
if block are executed, otherwise statements inside else block are executed.
Else block is optional and it may be absent in a program.
Output :
Enter a number:18
18 is even
Enter a number:33
33 is odd
97
{
statements;
... ... ...
}
98
In this program, a number is entered by user stored in variable n.
The if ... else if ... else statement tests two conditions:
1. n<0: If it is true, "Number is negative" is printed on the screen.
2. n>0: If it is true, "Number is positive" is printed on the screen.
If both of these conditions are false then the number is zero. So the
program will print "Number is zero".
Output
Enter a number:109
Number is positive
Enter a number:-56
Number is negative
Enter a number:0
Number is equal to zero
*****
99
7
LOOPS
Unit Structure
7.0 Objectives
7.1 Introduction
7.2 Unit End Questions
7.0 OBJECTIVES
C – while loop:
Syntax of while loop:
while (condition test)
{
//Statements to be executed repeatedly
// Increment (++) or Decrement (--) Operation
}
Flow Diagram of while loop
C while loop
Step1: The variable count is initialized with value 1 and then it has been
tested for the condition.
step2: If the condition returns true then the statements inside the body of
while loop are executed else control comes out of the loop.
100
step3: The value of count is incremented using ++ operator then it has
been tested again for the loop condition.
#include <stdio.h>
int main()
{
int var = 6;
while (var >=5)
{
printf("%d", var);
var++;
}
return 0;
}
Infinite loop: var will always have value >=5 so the loop would never
end.
do while loop in C:
The do while loop is a post tested loop. Using the do-while loop,
we can repeat the execution of several parts of the statements. The do-
while loop is mainly used in the case where we need to execute the loop at
least once. The do-while loop is mostly used in menu-driven programs
where the termination condition depends upon the end user.
char c;
int choice,dummy;
do{
printf("\n1. Print Hello\n2. Print demo program \n3. Exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Hello");
break;
case 2:
printf("demo program");
break;
case 3:
exit(0);
break;
default:
printf("please enter valid choice");
}
printf("do you want to enter more?");
scanf("%d",&dummy);
scanf("%c",&c);
}while(c=='y');
}
Output
Print Hello
Print Demo program
Exit
1
Hello
do you want to enter more?
y
Print Hello
Print demo program
Exit
2
Demo program
102
do you want to enter more?
N
Program :-
#include<stdio.h>
int main(){
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
do{
103
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
}
Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
for loop in C:
Syntax:
The syntax of a for loop in C programming language is −
for ( init; condition; increment )
{
statement(s);
}
104
Here is the flow of control in a 'for' loop −
The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required
to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and the
flow of control jumps to the next statement just after the 'for' loop.
After the body of the 'for' loop executes, the flow of control jumps
back up to the increment statement. This statement allows you to
update any loop control variables. This statement can be left blank, as
long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes
and the process repeats itself (body of loop, then increment step, and
then again condition). After the condition becomes false, the 'for' loop
terminates.
Flowchart :
Example
105
#include <stdio.h>
int main () {
int a;
/* for loop execution */
for( a = 10; a < 20; a = a + 1 ){
printf("value of a: %d\n", a);
}
return 0;
}
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
#include <stdio.h>
int main () {
for( ; ; ) {
printf("This loop will run forever.\n");
}
return 0;
}
106
nested loops in C:
C programming allows to use one loop inside another loop. The following
section shows a few examples to illustrate the concept.
Syntax
Example:
The following program uses a nested for loop to find the prime numbers
from 2 to 100 –
#include <stdio.h>
int main () {
Result :
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
107
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
You can do the same thing with the if...else..if ladder. However,
the syntax of the switch statement is much easier to read and write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
If we do not use break, all statements after the matching label are
executed. the default clause inside the switch statement is optional.
switch Statement Flowchart
equal to
case constant 3?
Example:
#include <stdio.h>
int main()
{
int i=2;
switch (i)
{
case 1:
printf("Case1 ");
109
break;
case 2:
printf("Case2 ");
break;
case 3:
printf("Case3 ");
break;
case 4:
printf("Case4 ");
break;
default:
printf("Default ");
}
return 0;
}
Output:
Case 2
*****
110
8
FUNCTIONS
Unit Structure
8.0 Objectives
8.1 Introduction
8.2 Unit End Questions
8.0 OBJECTIVES
You can divide up your code into separate functions. How you
divide up your code among different functions is up to you, but logically
the division usually is so each function performs a specific task.
Defining a Function:
Function Declarations:
112
Calling a Function:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( “Max value is : %d\n”, ret );
return 0;
}
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Here max() function along with main() function and compiled the
source code. While running final executable, it would produce the
following result:
Max value is : 200
Function Arguments:
If a function is to use arguments, it must declare variables that
accept the values of the arguments. These variables are called the formal
113
parameters of the function. The formal parameters behave like other local
variables inside the function and are created upon entry into the function
and destroyed upon exit.
While calling a function, there are two ways that arguments can be
passed to a function:
In general, this means that code within a function cannot alter the
arguments used to call the function. Consider the function swap()
definition as follows.
114
return 0;
}
Let us put above code in a single C file, compile and execute it, it
will produce the following
Result:
Which shows that there is no change in the values though they had
been changed inside the function.
115
{
/* local variable definition */
int a = 100;
int b = 200;
printf(“Before swap, value of a : %d\n”, a );
printf(“Before swap, value of b : %d\n”, b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf(“After swap, value of a : %d\n”, a );
printf(“After swap, value of b : %d\n”, b );
return 0;
}
Let us put above code in a single C file, compile and execute it, it
will produce the following
Result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values though they had
been changed inside the function.
int main(void) { . . . }
int main(int argc, char *argv[ ]) { . . . })
argc
The number of arguments in the command line that invoked the program.
The value of argc is nonnegative.
argv
Pointer to an array of character strings that contain the arguments, one per
string. The value argv[argc] is a null pointer.
116
If the value of argc is greater than zero, the array members argv[0]
through argv[argc - 1] inclusive contain pointers to strings, which are
given implementation-defined values by the host environment before
program startup. The intent is to supply the program with information
determined before program startup from elsewhere in the host
environment. If the host environment cannot supply strings with letters in
both uppercase and lowercase, the host environment ensures that the
strings are received in lowercase.
The parameters argc and argv, and the strings pointed to by the
argv array, can be modified by the program and keep their last-stored
values between program startup and program termination.
Function Prototype:
Old style:
Functions can be declared implicitly by their appearance in a call.
Arguments to functions undergo the default conversions before the
call.
The number and type of arguments are not checked.
Prototype style:
Functions are declared explicitly with a prototype before they are
called. Multiple declarations must be compatible; parameter types
must agree exactly.
117
Arguments to functions are converted to the declared types of the
parameters.
The number and type of arguments are checked against the prototype
and must agree with or be convertible to the declared types. Empty
parameter lists are designated using the void keyword.
Ellipses are used in the parameter list of a prototype to indicate that a
variable number of parameters are expected.
Prototype Syntax:
A function prototype has the following syntax:
function-prototype-declaration:
declaration-specifiers(opt) declarator;
118
Variable-length argument lists are specified in function prototypes
with ellipses. At least one parameter must precede the ellipses. For
example:
char function_name( int lower, ... );
Explanation:
It is now considered good form to use function prototypes for all
functions in your program. A prototype declares the function name, its
parameters, and its return type to the rest of the program prior to the
function’s actual declaration. To understand why function prototypes are
useful, enter the following code and run it:
#include <stdio.h>
void main()
{
printf(“%d\n”,add(3));
}
int add(int i, int j)
{
return i+j;
}
119
The prototype causes the compiler to flag an error on the printf
statement. Place one prototype for each function at the beginning of your
program. They can save you a great deal of debugging time, and they also
solve the problem you get when you compile with functions that you use
before they are declared. For example, the following code will not
compile:
#include <stdio.h>
void main()
{
printf(“%d\n”,add(3));
}
float add(int i, int j)
{
return i+j;
}
Why, you might ask, will it compile when add returns an int but
not when it returns a float? Because older C compilers default to an int
return value. Using a prototype will solve this problem. “Old style” (non-
ANSI) compilers allow prototypes, but the parameter list for the prototype
must be empty. Old style compilers do no error checking on parameter
lists.
C –Recursion:
Number Factorial:
#include <stdio.h>
unsigned long long int factorial(unsigned int i) {
120
if(i <= 1)
}
return 1;
}
return i * factorial(i - 1);
}
int main() {
int i = 12;
printf(“Factorial of %d is %d\n”, i, factorial(i));
return 0;
Result
Factorial of 12 is 479001600
Fibonacci Series:
#include <stdio.h>
int fibonacci(int i) {
if(i == 0) {
return 0;
}
if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main() {
int i;
for (i = 0; i < 10; i++) {
printf("%d\t\n", fibonacci(i));
}
return 0;
}
When the above code is compiled and executed, it produces the
following result −
0
1
1
2
3
5
121
8
13
21
34
For example,
If you want to use the printf() function, the header file <stdio.h> should be
included.
#include <stdio.h>
int main()
{
printf("Catch me if you can.");
}
If you try to use printf() without including the stdio.h header file, you will
get an error.
1. They work:
One of the most important reasons you should use library functions
is simply because they work. These functions have gone through multiple
rigorous testing and are easy to use.
122
4. The functions are portable:
#include <stdio.h>
#include <math.h>
int main()
{
Enter a number: 12
Square root of 12.00 = 3.46
123
Return Type of a C function:
*****
124
Unit III
9
PROGRAM STRUCTURE
Unit Structure
9.1 Storage classes, automatic variables, external variables, static variable
9.2 Multi-File Programs
9.3 More Library Functions
9.4 Unit End Questions
9.1.1 Introduction:
1. Auto: This is the default storage class for all variables declared inside a
function or a block. Hense, the keyword auto is rarely used while writing
programs in C language. Auto variables can be only accessed within the
block or function they have been declared and not outside them. These can
be accessed within nested blocks within the parent block or function in
which the auto variable was declared. They can be accessed outside their
scope as well using the concept of pointers given here by pointing to the
exact memory location where the variables resides. They are assigned a
garbage value by default whenever they are declared.
2. Extern: Extern storage class simply shows that the variable is defined
elsewhere and not within the same block where it is used. The value is
assigned to it in a different block and this can be overwritten or changed in
a different block as well. So an extern variable is a global variable
initialized with a legal value where it is declared in order to be used
elsewhere. It can be accessed within any function/block. A normal global
variable can be made extern as well by placing the ‗extern‘ keyword
before its declaration or definition in any function or block. This basically
signifies that we are not initializing a new variable but instead we are
using the global variable only. Then purpose of using extern variables is
that they can be accessed between two different files which are part of a
large program.
125
3. Static: This storage class is used to declare static variables which are
used while writing programs in C language. Static variables have a
property of preserving their value even after they are out of their scope.
Hense, static variables preserve their previous value in their previous
scope and are not initialized again in the new scope. we can say that they
are initialized only once and exist till the end of the program. Hence, no
new memory is allocated because they are not re-declared. Their scope is
local to the function to which they were defined. Global static variables
can be accessed anywhere in the program. By default, 0 value assigned to
them by the compiler.
4. Register: This storage class declares register variables which have the
same functionality as auto variables. Here, the only difference is that the
compiler tries to store these variables in the register of the microprocessor
if a free register is available. This makes the use of register variables to be
much faster than that of the variables stored in the memory during the
program runtime. If a free register is unavailable, these are then stored in
the memory only. Normally few variables which are to be accessed very
frequently in a program are declared with the register keyword which
improves the running time of the program. An important point to be noted
here is that we cannot obtain the address of a register variable using
pointers.
Syntax:
int a;
void autoStorageClass()
{
printf("--------------------------------");
}
void registerStorageClass()
{
printf("--------------------------------");
}
void externStorageClass()
{
127
printf("--------------------------------");
}
void staticStorageClass()
{
int i = 0;
printf("\nLoop started:\n");
for (i = 1; i < 5; i++) {
int main()
{
128
printf("A program to demonstrate"
" Storage Classes in C\n\n");
staticStorageClass();
// exiting
printf("\n\nStorage Classes demonstrated");
return 0;
}
Output:
A program to demonstrate Storage Classes in C
Demonstrating Value of the variable ‘as auto: 32
auto class ‘x’ declared
Demonstrating Value of the variable ‘as register: 71
register class ‘c’ declared
Demonstrating Value of the variable as extern:
extern class ‘x’ declared
Value of the variable as extern x‘ 0
‘x’ declared
Demonstrating
extern class
Modified value of the declared as 2
variable extern::
Demonstrating static class
Declaring ‘y’ as static inside the loop. But this declaration will occur only
once as ‘y’ is static.If not, then every time the value of ‘y’ will be the
declared value 5 as in the case of variable ‘p’
Loop started:
The value of ‘y’, declared as static, in 1 iteration is 6 The value of non
static variable ‘p’, in 1 iteration is 11
The value of ‘y’, declared as static, in 1 iteration is 6 The value of non
static variable ‘p’, in 1 iteration is 11
Loop ended:
129
9.2 MULTI-FILE PROGRAMS
/* main.c */
/*
Program to print factorials of all integers
between 0 and 20
*/
#include <stdio.h>
int main()
{
/* Print factorials of all integers between 0 and 10 */
for (j = 0; j <= 20; ++j)
{
factorial();
130
printf("j = %3d factorial(j) = %12.3e\n", j, fact);
}
return 0;
}
and
/* fact.c */
/*
Function to evaluate factorial (in floating point form)
of non-negative integer j. Result stored in variable fact.
*/
#include <stdio.h>
#include <stdlib.h>
void factorial()
{
int count;
/* Calculate factorial */
for (count = j, fact = 1.; count > 0; --count) fact *= (double) count;
return;
}
131
We are including these header files in our C program using
‘‘#include<file_name.h>’’ command to make use of the functions
those are declared in the header files.
When we include header files in our C program using
‘‘#include<filename.h>’’ command, all C code of the header files are
included in C program. Then, this C program is compiled by compiler
and executed.
List of most used header files in C programming language:
Check the below table to know all the C library functions and
header files in which they are declared.
132
10
PREPROCESSOR
Unit structure
10.1 Preprocessor
10.1.1 Introduction
10.2 Features
10.3 #define and #include
10.3.1#define
10.3.2 #include
10.4 Directives and Macros
10.5 Unit End Questions
10.1 PREPROCESSOR
10.1.1 Introduction:
10.2 FEATURES
Description:
Syntax:
The syntax for creating a constant using #define in the C language is:
#define CNAME value
OR
#define CNAME (expression)
CNAME
value
expression
Note:
Do NOT put a semicolon character at the end of #define statements.
This is a common mistake.
Example
Let's look at how to use #define directives with numbers, strings, and
expressions.
134
Number
The following is an example of how you use the #define directive to
define a numeric constant:
#define AGE 10
In this example, the constant named AGE would contain the value of 10.
String:
For example:
In this example, the constant called NAME would contain the value of
"TechOnTheNet.com".
{
printf("%s is over %d years old.\n", NAME, AGE);
return 0;
}
TechOnTheNet.com
Both user and system header files are included using the
preprocessing directive `#include'. It has three variants:
#include <file>
This variant is used for system header files. It searches for a file
named file in a list of directories specified by you, then in a standard list of
system directories. You specify directories to search for header files with
the command option `-I' (see section 1.9 Invoking the C Preprocessor).
The option `-nostdinc' inhibits searching the standard system directories;
in this case only the directories you specify are searched.
135
The parsing of this form of `#include' is slightly special because
comments are not recognized within the `<...>'. Thus, in `#include <x/*y>'
the `/*' does not start a comment and the directive specifies inclusion of a
system header file named `x/*y'.
#include "file"
This feature allows you to define a macro which controls the file
name to be used at a later point in the program. One application of this is
to allow a site-specific configuration file for your program to specify the
names of the system include files to be used. This can help in porting the
program to various operating systems in which the necessary system
header files are found in different places.
[
[
Preprocessors Examples:
#define MAX_ARRAY_LENGTH 20
#include <stdio.h>
#include "myheader.h"
These directives tell to get stdio.h from System Libraries and add
the text to the current source file. The next line tells to get myheader.h
from the local directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 45
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
Predefined Macros:
Sr.No.
Macro & Description
1 __DATE__
The current date as a character literal in "MMM DD YYYY" format.
2 __TIME__
The current time as a character literal in "HH:MM:SS" format.
3 __FILE__
This contains the current filename as a string literal.
4 __LINE__
This contains the current line number as a decimal constant.
5 __STDC__
Defined as 1 when the compiler complies with the ANSI standard.
Live Demo:
#include <stdio.h>
int main() {
138
When the above code in a file test.c is compiled and executed, it
produces the following result −
File :test.c
Date :July 5 2018
Time :03:45:25
Line :8
ANSI :1
Preprocessor Operators:
For example:
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
Live Demo
#include <stdio.h>
#define message_for(a, b) \
message_for(C, D);
return 0;
}
Live Demo:
#include <stdio.h>
When the above code is compiled and executed, it produces the following
result
Token35 = 50
Live Demo|:
#include <stdio.h>
140
#if !defined (MESSAGE)
#define MESSAGE "You are amazing!"
#endif
int main(void) {
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
Parameterized Macros:
int square(int y) {
return y * y;
}
Demo:
#include <stdio.h>
int main(void) {
printf("Max between 30 and 20 is %d\n", MAX(20, 30));
return 0;
}
141
When the above code is compiled and executed, it produces the following
result –
*****
142
143
11
ARRAY
Unit Structure
11.1 Arrays
11.1 Introduction
11.2 Definition, processing,
11.3 Passing arrays to functions,
11.4 Multidimensional arrays
11.5 Arrays and strings
11.6 Unit End Questions
11.1 ARRAYS
11.1.1 Introduction:
Initializing Arrays:
If you omit the size of the array, an array just big enough to hold the
initialization is created. Therefore, if you write −
You will create exactly the same array as you did in the previous
example. Following is an example to assign a single element of the
array −
balance[3] = 7.0;
The above statement assigns the 4th element in the array with a
value of 7.0. All arrays have 0 as the index of their first element which is
also called the base index and the last index of an array will be total size of
the array minus 1. Shown below is the pictorial representation of the array
we discussed above –
145
Accessing Array Elements:
An element is accessed by indexing the array name. This is done
by placing the index of the element within square brackets after the
name of the array. For example −
The above statement will take the 10th element from the array and
assign the value to salary variable. The following example Shows
how to use all the three above mentioned concepts viz. declaration,
assignment, and accessing arrays −
Demo
#include <stdio.h>
int main () {
return 0;
}
t[0] = 100
t[1] = 101
t[2] = 102
t[3] = 103
t[4] = 104
t[5] = 105
146
t[6] = 106
t[7] = 107
t[8] = 108
t[9] = 109
#include<stdio.h>
void MyArray(int a);
int main()
{
147
int mArray[] = { 2, 3, 4 };
MyArray(mArray[2]); //Passing array element myArray[2] only.
return 0;
}
void MyArray(int a)
{
printf("%d", a);
}
Output
4
int main()
{
float avg;
int marks[] = {99, 90, 96, 93, 95};
avg = findAverage(marks); // name of the array is passed as
argument.
printf("Average marks = %.1f", avg);
return 0;
}
#include <stdlib.h>
#include <stdio.h>
149
int main( void ) {
return 0;
#include<stdio.h>
int main()
{
int arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");
for (i = 0; i < 3; ++i)
{
scanf("%d", &arr[i][j]);
150
}
}
// passing the array as argument
displayArray(arr);
return 0;
}
void displayArray(int arr[3][3])
{
int i, j;
printf("The complete array is: \n");
for (i = 0; i < 3; ++i)
{
// getting cursor to new line
printf("\n");
for (j = 0; j < 3; ++j)
{
// \t is used to provide tab space
printf("%d\t", arr[i][j]);
}
}
}
151
How to initialize strings?
• Here, we are trying to assign 6 characters (the last character is '\0') to a char
array having 5 characters. This is bad and you should never do this.
int main()
char name[20];
scanf("%s", name);
return 0;
}
• Output
Enter name: Anita Jaykar
152
Your name is Anita.
Even though Anita Jaykar was entered in the above program, only ―Anita"
was stored in the name string. It's because there was a space after Anita.
char name[30]
;
printf("Enter name: ");
printf("Name: ");
return 0;
Output:
#include <stdio.h>
int main()
char str[50];
153
printf("Enter string: ");
gets(str);
return 0;
}
void displayString(char str[])
{
puts(str);
String Manipulation:
string.h
• C supports a large number of string handling functions in the standard
library "string.h".
• Note: Though, gets() and puts() function handle strings, both these
functions are defined in "stdio.h" header file.
Strlen ():
• In C, strlen() function calculates the length of string. It takes only one
argument, i.e, string name.
154
• Defined in Header File <string.h>
• Syntax of strlen() :
temp_variable = strlen(string_name);
{
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];
gets(c);
return 0;
• Function strcpy() copies the content of one string to the content of another
string.
• It takes two arguments.
• Defined in Header File <string.h>
• Syntax of strcpy() :
strcpy(destination,source);
155
• Here, source and destination are both the name of the string. This
statement, copies the content of string source to the content of string
destination.
Example of strcpy():
#include <stdio.h>
#include <string.h>
int main()
char a[10],b[10];
gets(a);
puts(b);
return 0;
}
strcat():
• In C programming, strcat() concatenates(joins) two strings.
• It takes two arguments, i.e, two strings and resultant string is stored in the
first string specified in the argument.
Syntax of strcat()
• strcat(first_string,second_string);
#include <stdio.h>
#include <string.h>
int main()
156
strcat(str1,str2); //concatenates str1 and str2 and resultant string is stored in
str1.
puts(str1);
puts(str2);
return 0;
Output :
My name is Anita.
Anita
Strcmp():
• In C programming, strcmp() compares two string and returns value 0,
if the two strings are equal.
• Function strcmp() takes two arguments, i.e, name of two string to
compare.
• strcmp(string1,string2);
• #include <stdio.h>
• #include <string.h>
• int main()
• {
• char str1[30],str2[30];
• printf("Enter first string: ");
• gets(str1);
• printf("Enter second string: ");
• gets(str2);
• if(strcmp(str1,str2)==0)
• printf("Both strings are equal");
• else printf("Strings are unequal");
• return 0;
• }
Output:
Enter first string: Apple
Enter second string: Apple
Both strings are equal.
12
POINTERS
Unit Structure
12.0 Objectives
12.1 Fundamentals Of Pointers
12.2 Address Operations
12.4 Pointer Assignment
12.5 Pointer Arithmetic
12.0 OBJECTIVES
Pointers are variables that hold a memory location. One can access
the value of the variable pointed to using the dereferencing operator *. A
pointer is a value that designates the address (i.e., the location in memory),
of some value.
158
Fig 1. Pointer *ptr stores the address of a character value ‘A’
Advantages of pointers:
1) Pointer reduces the code and improves the performance, it is used to
retrieving strings, trees, etc. and used with arrays, structures, and
functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's
memory.
#include <stdio.h>
int main () {
int va1;
char var2[10];
Output:
159
Address of var1 variable: 3400
Address of var2 variable: 9656
Address operators:
160
The actual data type of the value of all pointers, whether integer,
float, character, or otherwise, is the same, a long hexadecimal number that
represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that the
pointer points to.
Pointers (that is, pointer values) are generated with the ``address-
of'' operator &, which we can also think of as the ``pointer-to'' operator.
We demonstrate this by declaring (and initializing) an int variable i, and
then setting ip to point to it:
int *ptr;
int i = 5;
ptr = &i;
Another Example:
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
161
return 0;
}
Output:
Explanation:
#include <stdio.h>
int main()
{
int *ptrn;
long *ptrlng;
ptrn++; //increments by sizeof(int) (4 bytes)
ptrlng++; //increments by sizeof(long) (8 bytes)
return 0;
}
ptr2 = ptr1 + 8;
162
That would mean ptr2 would point to the memory location 8 bytes
ahead of ptr1.
Incrementing a Pointer:
#include <stdio.h>
const int MAX = 3;
int main () {
#include <stdio.h>
int main () {
163
int var[] = {10, 100, 200};
int i, *ptr;
return 0;
}
Output:
Pointer Comparisons:
Pointers may be compared by using relational operators, such as
==, <, and >. If p1 and p2 point to variables that are related to each other,
such as elements of the same array, then p1 and p2 can be meaningfully
compared.
int main () {
164
/* let us have address of the first element in pointer */
ptr = var;
i = 0;
return 0;
Output:
*****
165
13
ADVANCED POINTERS
Unit Structure
13.0 Objectives
13.1 Functions & pointers
13.2 Arrays & pointers
13.3 Pointer arrays
13.4 Passing functions to other functions
13.5 Questions
13.0 OBJECTIVES
To build on the fundamentals of pointers learnt in the previous chapter
To understand the use of pointers as parameters to functions
To use of pointers with reference to an array
To study the use of pointer arrays
To learn how to pass function pointers as parameters
int main () {
166
unsigned long sec;
getSeconds( &sec );
return 0;
}
Output:
Number of seconds :1394450468
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
return;
}
Let Let us now call the function swap() by passing values by reference
as in the following example:
Output:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
167
It shows that the change has reflected outside the function as well, unlike
call by value where the changes do not reflect outside the function.
#include <stdio.h>
int main() {
int x[4];
int i;
return 0;
Output:
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448
Notice that, the address of &x[0] and x is the same. It's because the
variable name x points to the first element of the array.
Similarly,
168
&x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
...
#include <stdio.h>
int main() {
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i) {
// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
// Equivalent to sum += x[i]
sum += *(x+i);
}
printf("Sum = %d", sum);
return 0;
}
Output:
Enter 6 numbers:
2
3
4
4
13
4
Sum = 29
#include <stdio.h>
int main() {
int x[5] = {1, 2, 3, 4, 5};
int* ptr;
169
printf("*ptr = %d \n", *ptr); // 3
printf("*(ptr+1) = %d \n", *(ptr+1)); // 4
printf("*(ptr-1) = %d", *(ptr-1)); // 2
return 0;
}
Output:
*ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2
#include <stdio.h>
int main () {
return 0;
}
Output:
#include <stdio.h>
int main () {
return 0;
}
Output:
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
#include <stdio.h>
int main () {
char *names[] = {
"RAMESH",
"REENA",
"SHYAM",
"ALI"
};
171
int i = 0;
Output:
(void (*f)(int)).
A simple example:
#include <stdio.h>
void print()
{
printf("Hello World!");
}
int main(void)
{
172
helloworld(print);
return (0);
}
Here, we see that the function named “print “ is being passed as a
parameter to the function helloworld in main.
Function Pointers:
For example:
double (*p2f)(double, char)
Output
Output1: Call using function pointer: 23
Output2: Call using function name: 23
2. You can even remove the ampersand from this statement because a function
name alone represents the function address. This means the above statement
can also be written like this:
13.5 QUESTIONS
*****
174
14
STRUCTURES AND UNIONS
Unit Structure
14.0 Objectives
14.1 Introduction
14.2 Initialization
14.3 Assignment
14.4 Nested Structures
14.5 Structures And Functions
14.6 Structures And Arrays
14.2 Unit End Questions
14.0 OBJECTIVES
14.1 INTRODUCTION
14.2 INITIALIZATION
175
struct structureName
{
dataType member1;
dataType member2;
...
};
Example:
struct Employee
int id;
char name[50];
int age;
char address[100];
float salary;
};
Note: Members inside the structures will not store any memory location
until they are associated with structure variables.
So, we have to create the structure variable before using it. We can
declare the C structure variables in multiple ways
Method #1
Create a struct variable after the declaration of structure.
Example:
struct Employee
{
int id;
char name[50];
int age;
char address[100];
float salary;
} emp1 , emp2;
176
14.2 ASSIGNMENT
Example:
emp1.id = 191;
emp1.age = 35;
emp1.salary = 25000;
SAMPLE PROGRAM:
struct Distance
{
int feet;
float inch;
} dist1, dist2, sum;
int main()
{
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
// adding feet
sum.feet = dist1.feet + dist2.feet;
// adding inches
sum.inch = dist1.inch + dist2.inch;
// changing to feet if inch is greater than 12
177
while (sum.inch >= 12)
{
++sum.feet;
sum.inch = sum.inch - 12;
}
struct name_of_structure1
{
----------
----------
};
struct name_of_structure2
{
----------
----------
struct name_of_structure1 var_name;
};
#include<stdio.h>
struct Address
{
char area[20];
char town[25];
char pin[6];
};
struct Employee
{
int Id;
char Name[25];
178
float salary;
struct Address addr;
};
void main()
{
int i;
struct Employee emp1;
printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",emp1.Id);
printf("\n\tEmployee Name : %s",emp1.Name);
printf("\n\tEmployee salary : %f",emp1.salary);
printf("\n\tEmployee House area : %s",emp1.addr.area);
printf("\n\tEmployee town : %s",emp1.addr.town);
printf("\n\tEmployee pin Code : %s",emp1.addr.pin);
}
Output :
Details of Employees
Employee Id : 101
Employee Name : Ajit Sharma
Employee salary : 45000
179
Employee area : Andheri
Employee town : Mumbai
Employee pin Code : 400033
struct Distance
{
int feet;
float inch;
} dist1, dist2, sum;
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
return 0;
}
We print the sum of dist1 and dist2 , dist1 with itself and dist2 with
itself in the above code, by calling the function printSum( dist1 , dist2) ,
printSum( dist1 , dist1) and printSum( dist2 , dist2) respectively.
When we talk about structures and arrays let us look at the 2 ways they
can be used
1. Arrays of structures
2. Structures containing arrays
Arrays of Structures:
An array of structres in C can be defined as the collection of
multiple structures variables where each variable contains information
about different entities. The array of structures in C are used to store
information about multiple entities of different data types. The array of
structures is also known as the collection of structures.
181
Below is the demonstration of a program that uses the concept of the array
within a structure.
#include <stdio.h>
#include <string.h>
struct student
{
int seatno;
float percentage;
};
int main()
{
int i;
struct student record[2];
Output:
Records of STUDENT : 1
Seat No is: 1
Percentage is: 86.500000
Records of STUDENT : 2
Seat No is: 2
Percentage is: 90.500000
Records of STUDENT : 3
Seat No is: 3
Percentage is: 81.50000
182
Structures containing arrays:
Let us know discuss the use of arrays in a structure. For this we will
see the example below which demonstrates the use of a structure called
Books which contains 2 character arrays for storing the title and author of
the book in addition to a integer variable for bookid.
#include <stdio.h>
#include <string.h>
struct Book {
int bk_id;
char title[50];
char author[50];
};
int main( ) {
/* book 1 specification */
bk1.bk_id = 650;
strcpy( bk1.title, "Let Us C");
strcpy( bk1.author, "Yashvant K");
/* book 2 specification */
bk1.bk_id = 651;
strcpy( bk2.title, "The Secret of Nagas");
strcpy( bk2.author, "Amish T");
return 0;
}
When the above code is compiled and executed, it produces the following
result –
183
Book 1 bk_id : 650
Book 1 title : Let Us C
Book 1 author : Yashvant K
Book 2 bk_id : 651
Book 2 title : The Secret of Nagas
Book 2 author : Amish T
Now, you can store the address of a structure variable in the above
defined pointer variable. To find the address of a structure variable,
place the '&'; operator before the structure's name as follows −
struct_pointer = &Book1;
struct_pointer->title;
Example:
#include <stdio.h>
#include <string.h>
struct Book {
char title[50];
int bk_id;
};
/* function declaration */
void printBook( struct Book *book );
int main( ) {
/*
/* print Book1 info by passing address of Book1 */
printBook( &bk1 );
return 0;
}
When the above code is compiled and executed, it produces the following result
Book title : Let Us C
Book bk_id : 750
Book title : The Secret of Nagas
Book bk_id : 751
14.9 UNION
Example:
#include <stdio.h>
#include <string.h>
union student
185
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
record2.percentage = 14.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}
Output:
186
14.10 UNIT END QUESTIONS
*****
187