C-Programing by Pankaj Sir
C-Programing by Pankaj Sir
FOR
[ B. Tech., B.Sc. and Diploma]
B HARAT P UBLICATIONS
5A/12, Ground Floor, Ansari Road, Darya Ganj, New Delhi - 110002
B.O. 135-A, Santpura Road, Yamuna Nagar - 135001 (Haryana)
Phone: 01732-227178, 232178, +91-9416227140
Email: [email protected]
© Reserved with the publisher
ISBN– 13:978–93–81252–20 –7
Legal Warning : The publisher has taken all possible precautions in publishing this book, in spite of al the efforts some errors might have
crept in. Any mistake, error or discrepancy noted may be brought to our knowledge which shall be taken care of in the next edition. It is
notified that neither the publisher nor the book seller or the author will be responsible for any damage or loss of action to anyone, of any kind,
in any manner, therefrom. For missing pages or misprints the publisher takes responsibility to exchange within 15 days of purchase of hte
same edition. All costs in this connection are to be borne by the purchaser.
(ii)
Introduction to C 1
1.1 OVERVIEW OF C PROGRAMMING
C language is one of the most popular computer languages today because it is
a structured, high level, machine independent language. It allows software developers
to develop programs without worrying about the hardware platforms where they will
be implemented. C is called a high level, compiler language. The aim of any high
level computer language is to provide an easy and natural way of giving a programme
of instructions to a computer.
C is one of a large number of high level languages which can be used for
general purpose programming, i.e., anything from writing small programs for personal
amusement to writing complex applications. It is unusual in several ways. Before C,
high level languages were criticized by machine code programmers because they
shielded the user from the working details of the computer. The C language has
been equipped with features that allow programs to be organized in an easy and
logical way. This is vitally important for writing lengthy programs because complex
problems are only manageable with a clear organization and program structure.
C allows meaningful variable names and meaningful function names to be used
in programs without any loss of efficiency and it gives a complete freedom of style,
it has a set of very flexible loop constructions and neat ways of making decisions.
These provide an excellent basis for controlling the flow of programs. Another
feature of C is the way it can express ideas concisely. The richness of a language
shapes what it can talk about. C gives us the apparatus to build neat and compact
programs. C tries to make the best of a computer by linking as closely as possible to
the local environment.
The increasing popularity of C is probably due to its many desirable qualities.
It is a robust language whose rich set of built-in functions and operators can be used
to write any complex program. The C compiler combines the capabilities of an
assembly language with the features of a high-level language and therefore it is well
suited for writing both system software and business packages. Programs written in
C are efficient and fast. This is due to its variety of data types and powerful operators.
C is highly portable. This means that C programs written for one computer can be
run on another with little or no modification. Another feature of C is its ability to
extend itself.
Development of "C" (Introduction and history)
"C" is a programming language developed at AT & T Bell Laboratories of USA
in 1972. It was developed Dennis Ritche in late 1970’s. it began to replace the
more familiar languages of that time like PL/1, ALGOL etc.
1.1
1.2 Programming in C
1. "C" became popular because of its reliability, simple and easy to use.
2. It was friendly capable and reliable
3. ALGOL60 was developed and did not become popular because it was too
general and too abstract.
4. They developed "CPL" (Combined Programming Language)
5. Next as it could not come up to make ALGOL 60 better one they moved to
"BCPL" (Basic Combines Programming Language. Developed by martin
Richard Cambridge university)
6. At the same time a language called "B" written by ken Thompson at AT &
Ts’. Bell laboratories as a further simplification of BCPL.
7. "C" s compactness and coherence is mainly due to its one main language.
e.g., LISP.
Note: C is a middle level language because it was due to have both a relatively good
programming efficiency and relativity good machine efficiency.
Application Of C Programming
C Programming is best known programming language. C Programming is
near to machine as well as human so it is called as Middle level Programming
Language. C Programming can be used to do verity of tasks such as networking
related, OS related.
Application of C Programming are listed below :
1. C language is used for creating Computer Applications.
2. Used in writing Embedded software's.
3. Firmware for various electronics, industrial and communications products
which use micro-controllers.
Introduction to C 1.3
Documentation
Global declarations
Main ( )
{
Local declarations
Program statements Body of the
Main ( ) function
Calling user defined functions (option to user)
}
User defined functions
Function 1
(Option to user)
Function 2
Function n
Fig. 1.1.
Preprocessor Statements
The preprocessor statement begins with # symbol and is also called the
preprocessor directive. These statements instruct the compiler to include C
preprocessors such as header files and symbolic constants before compiling the C
program. Some of the preprocessor statements are listed below.
#include<studio.h>
#include<math.h>
#include<studio.h> header files
#include<CONIO.h>
1.4 Programming in C
#define P L 3.1412.
#define TRVE 1 symbolic constat
#define FALSE 0
Global Declarations
The variables are declared before the main ( ) function as well as user defined
functions are called global variables. These global variables can be accessed by all the
user defined functions including main ( ) function.
The main ( ) function
Each and Every C program should contain only one main ( ). The C program
execution starts with main () function. No C program is executed without the main
function. The main ( ) function should be written in small (lowercase) letters and it
should not be terminated by semicolon. Main ( ) executes user defined program
statements, library functions and user defined functions and all these statements
should be enclosed within left and right braces.
Braces
Every C program should have a pair of curly braces ({ }). The left braces
indicates the beginning of the main ( ) function and the right braces indicates the end
of the main ( ) function. These braces can also be used to indicate the user-defined
functions beginning and ending. These two braces can also be used in compound
statements.
Local Declarations
The variable declaration is a part of C program and all the variables are used in
main ( ) function should be declared in the local declaration section is called local
variables. Not only variables, we can also declare arrays, functions, pointers etc.
These variables can also be initialized with basic data types. For example :
Code:
main ( )
{
int sum = 0;
float y;
}
Here, the variable sum is declared as integer variable and it is initialized to
zero. Other variables declared as int and float and these variables inside any function
are called local variables.
Program statements
These statements are building blocks of a program. They represent instructions
to the computer to perform a specific task (operations). An instruction may contain
an input-output statements, arithmetic statements, control statements, simple
assignment statements and any other statements and it also includes comments
that are enclosed within /* and */ . The comment statements are not compiled and
executed and each executable statement should be terminated with semicolon.
Introduction to C 1.5
Code:
#include <stdio.h>
main()
{
printf ("welcome to the world of C/n");
}
Editing
Create/modify
program source code
Source File
Compiling (*.c)
Generate machine
instructions
Yes
Error? Object File
(*.obj)
No
Linking
Link in
libraries, etc.
Yes
Error? Executable File
(*.exe)
No
Executing
Run program
Yes
Error?
No
Complier
This reads the entire source program and converts it to the object code. It
provides error not of one line, but errors of the entire program. It executes as a
whole and it is fast
Interpreter
It reads only one line of a source program at a time and converts it into an
object code. In case of errors/same will be indicated instantly. It executes line by line
and it is slow.
Introduction to C 1.7
Linker is a function which links up the files that present in the operating system,
it also links the files for the hardware and makes the system ready for executing.
Preprocessor
This is a program that processes the source program before it is passed on to
the compiler. The program typed in the editor is the source code to the preprocessor,
and then it passed the source code to the compiler. It is not necessary to write
program with preprocessor & activity
Preprocessor directories are always initialized at the beginning of the program.
It begins with the symbol (#) hash. It place before the main() function
e.g.,
# include <station>
# define PI 3.14
Header Files
Header files contain definitions of functions and variables which can be
incorporated into any C program by using the pre-processor #include statement.
Standard header files are provided with each compiler, and cover a range of areas,
string handling, mathematical, data conversion, printing and reading of variables.
To use any of the standard functions, the appropriate header file should be
included. This is done at the beginning of the C source file. For example, to use the
function printf() in a program, the line
#include <stdio.h>
should be at the beginning of the source file, because the definition for printf() is
found in the file “stdio.h” All header files have the extension .h and generally
reside in the /include subdirectory.
#include <stdio.h>
#include "mydecls.h"
The use of angle brackets <> informs the compiler to search the compilers
include directory for the specified file. The use of the double quotes “” around the
filename inform the compiler to search in the current directory for the specified file.
A Simple C Program
The following program is written in the C programming language :
#include <stdio.h>
main()
{
printf("Programming in C is easy.\n");
}
A Note about C Programs
In C, lowercase and uppercase characters are very important! All commands in
C must be lowercase. The C programs starting point is identified by the word
main()
1.8 Programming in C
This informs the computer as to where the program actually starts. The brackets
that follow the keyword main indicate that there are no arguments supplied to this
program (this will be examined later on).
The two braces, { and }, signify the begin and end segments of the program.
The purpose of the statement
include <stdio.h>
is to allow the use of the printf statement to provide program output. Text to
be displayed by printf() must be enclosed in double quotes. The program has only
one statement
printf("Programming in C is easy.\n");
print f() is actually a function (procedure) in C that is used for printing variables
and text. Where text appears in double quotes "", it is printed without modification.
There are some exceptions however. This has to do with the \ and % characters.
These characters are modifiers, and for the present the \ followed by the n character
represents a newline character. Thus the program prints
Programming in C is easy.
and the cursor is set to the beginning of the next line. As we shall see later on, what
follows the \ character will determine what is printed, i.e., a tab, clear screen, clear
line etc. Another important thing to remember is that all C statements are terminated
by a semi-colon ;
1.4 CHARACTERISTICS OF C
We briefly list some of C's characteristics that have lead to its popularity as a
programming language and define the language. Naturally we will be studying many
of these aspects throughout our tutorial.
q Extensive use of function calls
q Small size
q Loose typing - unlike PASCAL
q Structured language
q Low level (Bitwise) programming readily available
q Pointer implementation - extensive use of pointers for memory, array,
structures and functions.
C has now become a widely used professional language for various reasons.
q It has high-level constructs.
q It produces efficient programs.
q It can handle low-level activities.
q It can be compiled on a variety of computers.
The main drawback of c is that it has poor error detection which can make it
off putting to the beginner. However diligence in this matter can pay off handsomely
since having learned the rules of the C we can break them. Not all languages allow
this. This if done carefully and properly leads to the power of C programming.
Introduction to C 1.9
Special Symbol Symbols other than the Alphabets and Digits and white-spaces
Operators A symbol that represent a specific mathematical or non
mathematical action
"C" Tokens
Individual words and punctuation marks are characters. In a "C" program the
smallest individual units are known as "C" tokens. It has 6 types of tokens.
Keywords
Constants
Identifier
Tokens
Strings
Special
Symbols
Operators
Keywords
Keywords are reserved words by compiler. Keywords are assigned with fixed
meaning and they cannot be used as variable name. No header file is needed to
include the keywords.
1.10 Programming in C
Identifiers
Identifiers are names of variables, functions, and arrays. They are user-defined
names, consisting sequence of letters and digits, with the letter as the first character.
e.g.,
# define NUM 10
int A 20;
"NUM", "A" are user - defined id.
Constants
Constants in "C" are applicable to the values which not change during the
execution of a program. C constants can be divided into two major categories:
1. Primary Constants
2. Secondary Constants.
These constants are further categorized as shown in Fig. 1.2.
C Constant
(b) Real Constants: Real constants are often known as floating constants.
e.g., 2.5, 5.521, 3.14 etc.
(c) Character Constants: A single character constants are given within a
pair of single quote mark. The sequence of characters within double
quote marks is called String Constant.
e.g., 'a', '8', "Straight", "India", "4", etc.
Variables
This is a data name used for storing a data, its value may be changed during
the execution. The variables value keeps changing during the execution of the
program.
e.g., height, average, sum, etc.
Integer Types: Integers are whole numbers with a range of variables supported
by a particular machine. In a signed integer uses one bit for sign and 15 bits for
magnitude C has three classes of integer storage
1. short int
2. int
3. long int
It has a set of qualifiers i.e.,
1. sign qualifier
2. unsigned qualifier.
short int uses half the range of storage amount of data, unsigned int use all the
bits for the magnitude of the number and are positive.
1.12 Programming in C
void data type: A void type has no value this is usually used to specify the
return type of function, this function does not return any value to calling function.
Variable Initialization in C
Variables are initialized (assigned a value) with an equal sign followed by a
constant expression. The general form of initialization is:
variable_name = value;
Variables can be initialized (assigned an initial value) in their declaration. The
initializer consists of an equal sign followed by a constant expression as follows:
type variable_name = value;
Some examples are:
int d = 3, f = 5; /* initializing d and f. */
byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly otherwise,
sometime program would produce unexpected result. Try following example which
makes use of various types of variables:
#include <stdio.h>
int main ()
{
/* variable declaration: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces following result:
value of c : 30
value of f : 23.333334
1.14 Programming in C
PROGRAMS EXAMPLES
PROGRAM 1.1 : To Find Sum and Average of Three Real Numbers
#include <stdio.h>
main()
{
float a, b, c, sum, avg;
printf("\nEnter value of three numbers: ");
scanf("%f %f %f", &a, &b, &c);
sum = a + b + c;
avg = sum / 3;
#include <stdio.h>
main()
{
float c, f;
printf("\nEnter temperature in degree Centigrade: ");
scanf("%f", &c);
f = (1.8*c) + 32;
#include <stdio.h>
#include <math.h>
main()
{
float p, r, t, si, ci;
si = (p * r * t) / 100;
ci = p * pow((1 + r/100), t) - p;
printf("Radius: ");
scanf("%f", &r);
a = PI * r * r;
printf("%f\n", a);
return 0;
}
#include<stdio.h>
#include<math.h>
int main(){
float a,b,c;
float s,area;
s = (a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
return 0;
}
PROGRAM 1.7 : To find the surface area of cube.
Surface area = 6 * a2
int main(){
float a;
float surface_area,volume;
surface_area = 6 * (a * a);
volume = a * a * a;
printf("Surface area of cube is: %.3f",surface_area);
printf("\nVolume of cube is : %.3f",volume);
return 0;
}
Introduction to C 1.17
main()
{
int a, b, temp;
printf("\n\nBefore Swapping:\n");
printf("\na = %d\n", a);
printf("\nb = %d\n", b);
temp = a;
a = b;
b = temp;
printf("\n\nAfter Swapping:\n");
printf("\na = %d\n", a);
printf("\nb = %d\n", b);
getch();
}
main()
{
int a, b, temp;
printf("\n\nBefore Swapping:\n");
printf("\na = %d\n", a);
printf("\nb = %d\n", b);
a = a + b;
b = a - b;
a = a - b;
printf("\n\nAfter Swapping:\n");
printf("\na = %d\n", a);
printf("\nb = %d\n", b);
getch();
}
1.8 OPERATORS
An expression is a sequence of operators and operands that specifies
computation of a value, or that designates an object or a function, or that generates
side effects, or that performs a combination thereof.
1.18 Programming in C
Example:
#include <stdio.h>
main()
{
int sum = 50;
float modulus;
Example:
#include <stdio.h>
main()
{
int count = 0, loop;
Output:
enter a year:2004
the above given year IS a leap year
Example:
#include <stdio.h>
main()
{
int input;
PROGRAM 1.12 : Tto accept a year and check the given year is leap or
not by using ternary:
# include <stdio.h>
# include <conio.h>
main( )
{
int y,leap;
clrscr( );
printf("enter any yr");
scanf("%d",&y);
leap=(y%400= =0)?:(y%100!=0)?(y%4= =0)?1:0:0;
if(leap= =1)
printf(" the given year is leap year");
else
printf("given year is not leap year);
getch( );
}?
Bit Operations
C has the advantage of direct bit manipulation and the operations available
are,
Example:
/* Example program illustrating << and >> */
#include <stdio.h>
main()
{
int n1 = 10, n2 = 20, i = 0;
Example:
/* Example program using EOR operator */
#include <stdio.h>
main()
{
int value1 = 2, value2 = 4;
value1 ^= value2;
value2 ^= value1;
value1 ^= value2;
printf("Value1 = %d, Value2 = %d\n", value1, value2);
}
Example:
/* Example program using AND operator */
#include <stdio.h>
main()
{
int loop;
for( loop = 'A'; loop <= 'Z'; loop++ )
printf("Loop = %c, AND 0xdf = %c\n", loop, loop & 0xdf);
}
x = x ^ y;
y = x ^ y;
x = x ^ y;
are evaluated. Associativity is then applied, if the need arises. Precedence of the
Operator and Associativity are Listed in the following table and this table is summarized
in decreasing Order of Priority i.e., topmost operator has highest priority and
bottommost operator has lowest priority.
Precedence of the Operator are Listed in the Following Table and This Table is
Summarized in decreasing Order of Priority i.e., Topmost Operator has Highest
Priority and Bottommost Operator has Lowest Priority.
Type Conversion
Type conversion is done while evaluating expressions, the compiler breaks
each expression down into individual sub-expressions. Typically, these sub-expressions
involve a unary or binary operator and some operands. Most binary operators require
their operands to be of the same type. If operands of mixed types are used, the
compiler will convert one operand to agree with the other. To do this, it uses a
hierarchy of data types:
High Level
long double
double
float
long int
long int
Unsigned int
int
short char
Lower Level
However, some type conversions are inherently unsafe, and if the compiler
can detect that an unsafe conversion is being implicitly requested, it will issue a
warning.
float f =3.5;
int i;
i=f;
In the second example, the fractional part of the double value (3.5) is dropped
to (3) because integers can not support fractional values. Because converting a double
to an int usually causes data loss (making it unsafe). Other unsafe conversions involve
assigning unsigned variables to signed variables (and vice-versa), and assigning long
integers (eg. a 4-byte long) to integer variables of a smaller size (eg. a 2-byte short).
Similarly if we convert an int to a short int or int to char, the compiler just drops the
extra bits.
Thus, we can observe the following changes that are unavoidable when
performing type conversion.
q When a float value is converted to an integer value, the fractional part is
truncated.
q When a double value is converted to a float value, the rounding of digit
is done.
q When a long int value is converted to an int value, the excess higher
order bits are dropped.
Typecasting
Typecasting is also known as forced conversion. Casting represents a request
by the programmer to do an explicit type conversion. It is done when the value of
higher data type has to be converted into the value of lower data type. However, this
cast is under the programmer’s control and not under the compiler’s control. For
example if we need to explicitly type cast a floating variable into an integer variable.
In standard C programming, casts are done via the () operator, with the name of the
type to cast to inside. For example:
float salary = 10000.00;
int sal;
sal = (int)salary;
As we see in the code, typecasting can be done by placing the destination data
type in parentheses followed by the variable name that has to be converted. Hence,
we conclude that typecasting is done to make a variable of one data type to act like
a variable of another type.
We can also typecast integer values to its character equivalent (as per ASCII
code) and vice-versa. Type casting is also done in arithmetic operation to get correct
result. For example, when dividing two integers, the result can be of floating type.
Also, when multiplying two integers the result can be of ling. So, to get correct
precision value, typecasting can be done. For instance,
int a = 500, b = 70;
float res;
res = (float) a / b;
Let us look at some more examples of typecasting.
q res = ( int) 9.5
9.5 is converted to 9 by truncating and then assigned to res.
Introduction to C 1.27
ANSWERS
REVIEW QUESTIONS
1. What is C language?
2. Describe the several features of C language.
3. Explain the structure of c program.
4. Explain why C language is called middle level language.
5. What are header file? Why are they important? Can we write C program without
using any header file?
6. What do you understand by identifiers and keywords?
7. List all the basic or primary data-types available in C with their format specifier.
8. Write about space requirement for variables of different data types?
9. What are variables?
10. Explain the difference between declaration and definition.
11. What is the benefit of using const for declaring constants?
12. What is an operator? Describe the different types of operators that are included in
the ‘C’ language with the example for each?
13. What is unary operator?
14. What is a modulus operator? What are the restrictions of a modulus operator?
1.40 Programming in C
15. Explain pre and post increment-decrement operator with suitable example.
16. List all the Bitwise operators available in C. Explain with suitable example
17. Explain sizeof () operator with suitable example.
18. Explain conditional operator or turnery operator with suitable example.
19. Explain precedence and associatively with suitable example.
20. Explain automatic type conversion and casting with suitable some example.
21. What are logical operators are used in C? Illustrate with examples.
22. Why n++ executes faster than n+1?
23. List all the storage class available in c and specify the scope, lifetime, storage and
their default initial value.
24. Why do we need different types of storage classes ?
25. What are advantages and disadvantages of external storage class?
26. What are the advantages of auto variables?
27. Which bit wise operator is suitable for checking whether a particular bit is on or
off ?
28. Differentiate between typecasting and type conversion.
___________