C-Programming Unit 1
C-Programming Unit 1
C-Programming Unit 1
5.1 Introduction
Computers are basically dumb electronic equipments. Be it their internal functioning (like transferring
data from keyboard to memory, from memory to processor, or from memory to output device) or
automation of a manual task (like computerization of examination system, railway reservation system
etc.), they require proper instructions. Without instructions they do not do anything. They don’t accept
instructions in natural languages (like Hindi, English etc.). They follow the instructions provided to
them in computer languages.
In the year 1970, two computer scientists Dennis Ritchie and Brain Kernighan, at Bell Laboratories of
USA, developed C language. It was quite powerful language. Its scope of operations was very wide. It
not only provided means and commands for writing programs for computer’s internal functioning but
it also provides instructions for automating manual tasks. In other words you can say that it had the
penetrating power of low level language and had the features of high level language too. Within short
span of time, C language became quite popular all across the world. Although it came into existence,
long time back, but it is still being used.
To make the C programming easy, many programs for primitive functions have already been written
and compiled in the form of libraries. Programs of these libraries are so commonly used that they are
almost considered as part of C language. stdio.h, string.h, stdlib.h, etc. are the names of few standard
libraries.
To make use of any program (called function), available library, the name of the library need to be
included in the main program. Following is the format, using which function libraries are included in
any program:
#include<library-name>
Here #include is keyword which is to be written as such and library-name is the name of that library
which is to be included in the program.
To make use of the standard input/output functions in your program, you have to include this library at
the beginning of the program. Following is the command, using which this library can be included in
the program. #include<stdio.h>
5.4 Programming Rules
Following are the rules of C programming. They should be strictly followed. In case of any violation,
compilation error occurs and the program doesn’t execute.
1. A C program consists may consists of one or more functions. One of them must be named as
main( ). Execution of the program always starts from main( ) function.
2. All the statements of main( ) function should be written, within the opening and closing
brackets, which mark the beginning and end of the function, respectively.
3. Practically there is no limit to the number of statements that could include in the main( )
function. However to make the program manageable use of multiple function should be
promoted instead of too many lines in one function.
5. C is a case sensitive language. A differentiation is always made between uppercase and lower
case letters.
6. Comments can always be included in the program by placing the matter in between /* and */
delimiters. Following is the general format for placing comments in the program.
/* Comments */
E.g. /* This program calculates the factorial value of a given number.*/
In order to provide some control over the range of numbers and storage space, C has three classes of
integer storage:
short int
int
long int
All the classes of integers are in both signed and unsigned format.
Data Type Size (Byte) Range Format specifier
short int or signed short
2 -32768 to +32767 %d
int
unsigned short int 2 0 to 65535 %u
int or signed int 2 -32768 to +32767 %d
unsigned int 2 0 to 65535 %u
long int or signed long -2,147,483,648 to
4 %ld
int +2.147,483,647
unsigned long int 4 0 to 4,294,967,295 %lu
Character Type:
A single character can be defined as character (char) type data. Characters are usually stored in 8 bits
(one byte) of internal storage. The qualifier signed or unsigned may be explicitly applied to char.
While unsigned chars have values between 0 and 255, signed chars have values between -128 and 127.
Void Type:
The void type has no values. This is usually used to specify the type of functions. The type of a
function is said to be void when it does not return any value to the calling function. It can also play the
role of a generic type, meaning that it can represent any of the other standard types.
5.5.2 Derived Data Type
Derived data types are those data types those are derived from predefined data types. Examples of the
derived data types are Array, Pointer, Structure, Union etc.
From C compiler’s point of view, a variable name identifies somephysical location within the
computer where the string of bitsrepresenting the variable’s value is stored. There are basically
twokinds of locations in a computer where such a value may be keptMemory and CPU registers. It is
the variable’s storage class thatdetermines in which of these two locations the value is stored.
Default Initial
Storage Classes Storage Scope Life
Value
Till the control remains
Local to the block in
Automatic Memory Garbage within the block in which
which it is defined.
the variable is defined.
Till the control remains
CPU Local to the block in
Register Garbage Value within the block in which
Registers which it is defined.
the variable is defined.
Value of the variable
Local to the block in
Static Memory Zero persists between different
which it is defined.
function calls.
As long as the program’s
External Memory Zero Global execution doesn’t come to
an end.
Example of automatic storage class:
void main()
{
auto int a=5;
{
auto int a=10;
printf(“a=%d”,a); // display a=10
}
printf(“a=%d”,a); // display a=5
}
The only difference between auto and register is, the execution of register variable is much faster than
autovariable.
Output:
a=1
a=2
a=3
Example of external storage class:
inti ;
main( )
{
printf( "\ni = %d", i ) ;
increment( ) ;
increment( ) ;
decrement( ) ;
decrement( ) ;
}
increment( )
1{
i=i+1;
printf( "\non incrementing i = %d", i ) ;
}
decrement( )
{
i=i-1;
printf( "\non decrementing i = %d", i ) ;
}
Example:
int x = 21 ;
main( )
{
extern inty ;
printf( "\n%d %d", x, y ) ;
}
int y = 31 ;
5.7 Operator
Operator is a symbol that operates on one or more operands. It also tells the computer to perform
certain mathematical or logical manipulations. Operators are used in program to manipulate data and
variables. Operands can be a variable, a constant or anexpression.
Example:
a++ or++a
Note- If increment operator is used with association of another operator, it behaves differently.
Example:
Case-1 Case-2
int a=10; int a=10;
int b=a++; int b=++a;
In case-1, first value of a is assigned into b then value of a is incremented. That is a=11 and b=10.
In case-2, first value of a is incremented, Then value of a is assigned into b .That is a=11 and b=11.
Decrement Operator is used to decrease value by 1. The symbol used with decrement operator is “-
-”.
Example:
a- -or - -a
Note- If decrement operator is used with association of another operator, it behaves differently.
Example:
Case-1 Case-2
int a=10; int a=10;
int b=a- -; int b= - -a;
In case-1, first value of a is assigned into b then value of a is decremented. That is a=9 and b=10.
In case-2, first value of a is decremented, Then value of a is assigned into b .That is a=9 and b=9.
Operand1 = Operand2
Note- In the Left hand side of Assignment operator, it must be a variable. And in the Right hand side
ofthe assignment, it must be a constant number or variable or an expression.
Example-
int a=10,b;
b=a;
In this value of a variable is assigned to b variable.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift left
>> Shift Right
Thus, ch>> 3 would shift all bits in ch three places to the right. Similarly, ch>> 5 would shift all bits
5places to the right.
Example:
If the variable ch contains the bit pattern 11010111, then, ch>> 1 would give 01101011 and ch>>
2would give 00110101.
Left Shift Operator
This is similar to the right shift operator, the only difference being that the bits are shifted to the left,
and foreach bit shifted, a 0 is added to the right of the number.
Example:
If the variable ch contains the bit pattern 11010111, then, ch<< 1 would give 10101110 and ch<<
2would give 01011100.
Also, conversion of float to int causes truncation of fractional part, conversion of double to float
causesrounding of digits and the conversion of long int to int causes dropping of excess higher order
bits.
Associativity is "a property that determines how operators of the same precedence are grouped in the
absence of parentheses."
For example, the multiplication (*), division (/) and modulus (%) operators all have the same level of
precedence. So if they are all included in an expression without parentheses, the associativity of the
operators determines the order in which they will be evaluated. All of the operators have precedence
levels and associativity.
The table below shows all the operators in C with precedence and associativity.
Note: Precedence of operators decreases from top to bottom in the given table.
5.11 C Programming Keywords and Identifiers
Character set
Character set are the set of alphabets, letters and some special characters that are valid in C language.
Alphabets:
Uppercase: A B C .................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits:
012345689
Special Characters:
~ ‘ ! @ # $ % ^ & * ( ) _ -
= + \ | { } [ ] ; : ‘ “ < >
, . ? /
Keywords:
Keywords are the words whose meaning has already beenexplained to the C compiler (or in a broad
sense to the computer).The keywords cannot be used as variable names because if we doso we are
trying to assign a new meaning to the keyword, which isnot allowed by the computer. Some C
compilers allow you toconstruct variable names that exactly resemble the keywords.However, it would
be safer not to mix up the variable names andthe keywords. The keywords are also called ‘Reserved
words’.
For example:
int money;
Here, int is a keyword that indicates, 'money' is of type integer.
Note: As, C programming is case sensitive; all keywords must be written in lowercase.
Here, money is an identifier which denotes a variable of type integer. Similarly, mango_tree is another
identifier, which denotes another variable of type integer.
Variables
Variables are memory location in computer's memory to store data. To indicate the memory location,
eachvariable should be given a unique name called identifier. Variable names are just the symbolic
representationof a memory location. Examples of variable name are sum, car_no, count etc.
Declaration of Variable
Variable are declared as:
DataTypeVariable_name;
Example:
intnum;
Here, num is a variable of integer type. That is num is a variable that hold integer type value.
Constants:
Constants are fixed value that can't be changed during the execution of a program.
For example:
1 2.5 ‘h’ "Programming is easy"
1. Integer Constants:
Integer constants are the numeric constants (constant associated with number) without any fractional
part orexponential part.
Example:
0, -9, 22 etc
2. Floating-Point Constants:
Floating point constants are the numeric constants that have either fractional form or exponent form.
For example:
-2.0 , 0.0000234 , -0.22E-5
Note: Here, E-5 represents 10-5. Thus, -0.22E-5 = -0.0000022.
3. Character Constants:
Character constants are the constant which use single quotation around characters.
For example:
'a' , 'l' , 'm' , 'F' etc.
4. Escape Sequence
Sometimes, it is necessary to use newline (enter), tab, quotation mark etc. in the program which either
cannotbe typed or has special meaning in C programming. In such cases, escape sequence are used.For
example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way the
charactersare interpreted by the compiler.
Escape Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\’ Single Quotation Mark
\” Double Quotation Mark
\? Question Mark
\0 Null Character
5. String Constants:
String constants are the constants which are enclosed in a pair of double-quote marks.
For example:
"good" //string constant
"" //null string constant
"" //string constant of six white space
"x" //string constant having single character.
"Earth is round\n" //prints string with newline
6. Enumeration Constants:
Keyword enum is used to declare enumeration types. For example:
enum color {yellow, green, black, white};
Here, the variable name is color and yellow, green, black and white are the enumeration constants
havingvalue 0, 1, 2 and 3 respectively by default.
printf() – used to display data on the standard output device according specified format
string,and returns number of characters printed.
General form of printf () function
printf(“format string ”,variableList);
1. Format string may contains
format specifiers,
Alphabets
Escape character
2. Variable List define list of variable .Each variable is separated by commas (,) operator.
Example:
printf( "%f", si ) ;
printf( "%d %d %f %f", p, n, r, si ) ;
printf( "Simple interest = Rs. %f", si ) ;
printf( "Principal = %d \nRate = %f", p, r ) ;
Note- Sometimes we can drop variable list from printf() function.Therefore printf() function
can be written as:
printf(“Format string”);
Example:
printf(“Enter the Number \n “);
scanf( )- scanf reads data from the standard input, interprets them according to the
specification informat, and stores the results into given locations.
Structure of C Program:
Example:
#include <stdio.h> //Preprocessor directive .This is needed to run printf() function.
intmain() // program execution start here
{
printf("C Programming"); //displays the content inside quotation
return 0;
}
Output:
C Programming
Explanation:
Every program starts from main() function.
printf( ) is a library function to display output which only works if #include<stdio.h>is
included at the beginning.
Here, stdio.h is a header file (standard input output header file) and #include is preprocessor
directive used to insert the header file when necessary. When compiler encounters printf( )
function and doesn't find stdio.h header file, compiler shows error.
return 0; indicates the end of program.
Every statement is terminated with semicolon ( ; ).
Example:
Write a program to read two integer numbers and display that numbers.
#include<stdio.h>
void main()
{
inta,b;
printf(“Enter the two numbers \n ”);
scanf(“%d %d”,&a,&b); // input a as 10 and b as 20
printf("value of a is %d and value of b is %d ",a,b);
}
Output:
Value of a is 10 and value of b is 20.