C-Programming Unit 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

Fundamentals of C Programming

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.

5.2 Components of C language


C language is basically a basically a very small instruction set, coupled with few standard rules and
predefined formats. To write a C program, one needs to use appropriate instructions and follow the
standard rules.

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.

5.3 Standard I/O in C


Reading the data into the computer and providing results are the two activities that each program
performs. To perform these activities, most of the computer languages provide commands. By writing
those commands in specified syntax, activities like reading the data or displaying the result can be
very easily performed through program. Note that C language does not provide any command for such
operations; rather it provides functions for them. For example, getchar, scanf etc. are few functions
that read the data from the standard input (i.e. Keyboard). Similarlyputchar, printf etc. are few
functions that display the data on standard output. In C language, all standard input, output related
functions have been compiled and put in a library, named stdio.h. This library is often referred to as
standard I/O library.

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.

4. Each statement should be terminated with a semicolon sign (;).

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.*/

5.5 Data Types


Different types of data that could be used in any language are referred to as data types. Data type tells
the compiler:
 Name of the variable.
 Which type of value that variable can hold.
 How much memory space it reserves.

C supports three classes of data types:


1. Primary (or fundamental) Data Type
2. Derived Data Type
3. User-defined Data Type

5.5.1 Primary or Fundamental Data Type


All C compilers support five fundamental data types, namely integer (int), character (char), floating
point (float), double-precision floating point (double) and void. Many of them also offered extended
data type such as long int and long double.

Data Type Used for Size (Byte) Range Format Specifier


int Integer 2 -23768 to +32767 %d
char Character 1 -128 to +127 %c
Single precision floating
float 4 -3.4e38 to 3.4e38 %f
point number
Double-precision floating
double 8 -1.7e308 to 1.7e308 %lf
point number
void --- -- --- ---
Integer Types:
Integers are whole numbers with a range of values supported by a particular machine. Generally,
integers occupy one word of storage, and since the word size of machines vary (typically 16 bits or 32
bits) the size of an integer that can be stored depends on the computer. If we use a 16-bit word length,
the size of the integer value is limited to the range -32768 to +32767. Similarly, a 32-bit word length
can store an integer ranging from -2,147,483,648 to 2,147,483,647.

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

Floating Point Types:


Floating point (or real numbers) are stored in 32 bits (on all 16 bit and 32 bit machines), with 6 digits
of precision. Floating point numbers are defined in C by the keyword float. When the accuracy
provided by a float number is not sufficient, the type double can be used to define the number. A
double data type number uses 64 bits giving a precision of 14 digits. These are known as double
precision numbers. Remember that the double type represents the same data type that float represents,
but with a greater precision. To extend the precision further, we may use long double which uses 80
bits.
Data Type Size (Byte) Range Format specifier
float 4 -3.4e38 to 3.4e38 %f
double 8 -1.7e308 to 1.7e308 %lf
long double 10 -1.7e4932 to +1.7e4932 %Lf

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.

Data Type Size (Byte) Range Format specifier


char or signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c

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.

5.5.3 User Defined Data Type


C supports a feature known as “type definition” that allows the user to define an identifier that would
represent an existing data type. The user defined data type identifier can later be used to declare
variables. It takes the general form:
typedef type identifier;
Ex: typedefint marks;

5.6 Storage Classes


To fully define a variable oneneeds to mention not only its ‘type’ but also its ‘storage class’. Inother
words, not only do all variables have a data type, they alsohave a ‘storage class’.

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.

Moreover, a variable’s storage class tells us:


(i) Where the variable would be stored.
(ii) What will be the initial value of the variable, if initial value is not specifically assigned,
(i.e. the default initial value).
(iii) What is the scope of the variable; i.e. in which functions the value of the variable
would be available.
(iv) What is the life of the variable; i.e. how long would thevariable exist.

There are four storage classes in C:


(i) Automatic storage class
(ii) Register storage class
(iii) Static storage class
(iv) External storage class

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
}

Example of Register storage class:


void main()
{
register int a=5;
{
register 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.

Example of static storage class:


void Increment()
{
static int a=1;
printf(“a=%d”,a);
a++;
}
void main()
{
Increment();
Increment();
Increment();
}

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 ) ;
}

The output would be:


i=0
on incrementing i = 1
on incrementing i = 2
on decrementing i = 1
on decrementing i = 0

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.

 When an operator operates on one operand, is called unary operator.


 When an operator operates on two operands, is called binary operator.
 When an operator operates on three operands, is called ternaryoperator.
5.8 Types of Operators
C operators can be classified into a number of categories. They include
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Ternary operator
5. Increment and Decrement operator
6. Assignment operator
7. Bitwise operator

5.8.1 Arithmetic Operator


C provides all the basic arithmetic operators. They are listed in the following table. These operators
are used to perform arithmetic operations.

Operator Meaning Precedence Associativity


+ Addition 2 Left to Right
- Subtraction 2 Left to Right
* Multiplication 1 Left to Right
/ Division 1 Left to Right
% Modulo Division 1 Left to Right

5.8.2 Relational Operator


We often compare two quantities and depending on their relation, take certain decision. These
comparisons can be done with the help of relational operators.

Operator Meaning Precedence Associativity


< Less Than 1 Left to Right
<= Less Than or Equal To 1 Left to Right
> Greater Than 1 Left to Right
>= Greater Than or Equal to 1 Left to Right
== Equal to 2 Left to Right
!= Not Equal To 2 Left to Right

5.8.3 Logical Operators


An expression, which combines two or more relational expressions, is termed as a logical expression
or compound relational expression.

Operator Meaning Precedence Associativity


&& Logical AND 2 Left to Right
|| Logical OR 3 Left to Right
! Negation 1 Left to Right

Truth Table for Logical Operators


Opnd1 Opnd2 Opnd1&&Opnd2 Opnd1!!Opnd2 !Opnd1
0 0 0 0 1
0 1 0 1 1
1 0 0 1 0
1 1 1 1 0
5.8.4 Ternary Operator
The ternary operators operate on three operands. It is also known as conditional operator. Ternary
operator comes with the pair ? and :.

General Form of the ternary operator is:


Expression1? Expression2: Expression3

If Expression1 is true, then Expression2 is executed otherwise Expression3 is executed.

5.8.5 Increment /Decrement Operator


Increment Operator is used to increase value by 1.Symbol used “++”.

Example:
a++ or++a

Forms of Increment operator:


Pre –increment: In this operator is defined before the operand.
Example: ++a

Post-increment: In this operator is defined after the operand.


Example: 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

Forms of Decrement operator:


Pre –decrement: In this operator is defined before the operand.
Example: - -a

Post-decrement: In this operator is defined after the operand.


Example: 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.

5.8.6 Assignment Operator


Assignment operators are used to assign the result of an expression to a variable. It is also used to
assign the value of one operand into another operand. “ = “ is used as assignment operator.

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.

5.8.6 Bitwise Operator


C has a distinction of supporting special operators known as bitwise operators for manipulation of data
at bit level. These operators are used for testing the bits, or shifting them right or left. Bitwise
operators may not be applied to float or double.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift left
>> Shift Right

Truth Table for Bitwise Operators


Opnd1 Opnd2 Opnd1&Opnd2 Opnd1 | Opnd2 Opnd1^Opnd2
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Right Shift Operator


The right shift operator is represented by >>. It needs two operands. It shifts each bit in its left operand
to theright and for each bit shifted, a 0 is inserted to the left. The number of places the bits are shifted
depends onthe number following the operator (i.e. its right operand).

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.

5.9 C Type Conversion


The process of converting one predefined type into another is called type conversion.Type conversion
in c can be classified into the following two types:
1. Implicit Type Conversion.
2. Explicit type conversion

5.9.1 Implicit Type Conversion:


When the type conversion is performed automatically by the compiler, such type of conversion is
knownas implicit type conversion or type promotion.The compiler converts all operands into the data
type of the largest operand.The sequence of rules that are applied while evaluating expressions are
given below:

All short and char are automatically converted to int, then,


1. If either of the operand is of type long double, then others will be converted to long double and
result will be long double.
2. Else, if either of the operand is double, then others are converted to double.
3. Else, if either of the operand is float, then others are converted to float.
4. Else, if either of the operand is unsigned long int, then others will be converted to unsigned
long int.
5. Else, if one of the operand is long int, and the other is unsigned int, then
6. If a long int can represent all values of an unsigned int, the unsigned int is converted to long
int.
7. Otherwise, both operands are converted to unsigned long int.
8. Else, if either operand is long int then other will be converted to long int.
9. Else, if either operand is unsigned int then others will be converted to unsigned int.
10. It should be noted that the final result of expression is converted to type of variable on left side
ofassignment operator before assigning value to it.

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.

5.9.2 Explicit Type Conversion


The type conversion performed by the programmer by converting the data type of the expression of
specifictype is known as explicit type conversion.The explicit type conversion is also known as type
casting.

Type casting in c is done in the following form:


(data_type)expression;
Where, data_type is any valid c data type, and expression may be constant, variable or expression.
For example,
x=(int)a+b*d;
The following rules have to be followed while converting the expression from one type to another to
avoid theloss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.

5.10 Operator Precedence and Associativity


Precedence is the priority for grouping different types of operators with their operands.

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.

Example of assigning this expression to variable x


int x = 8 + 3 * 6 / 2
Since the assignment operator (=) has right-to-left associativity, the expression on the right of the
equals signwill be evaluated before variable x is given the value. The arithmetic operators have left-to-
right associativity,and multiplication and division have higher precedence than addition. So starting
from the left of theequation, the highest precedence operator is multiplication, so 3 * 6 (= 18) is
performed, then 18 / 2 (= 9) isperformed. The expression is evaluated again from the left with the next
level of precedence being addition, so8 + 9 (= 17) is performed. Finally, the right side of the
assignment operator is assigned to variable x (again,because the assignment operator's associativity is
right-to-left).

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:

~ ‘ ! @ # $ % ^ & * ( ) _ -

= + \ | { } [ ] ; : ‘ “ < >

, . ? /

White space Characters:


blank space, new line, horizontal tab, carriage return and form feed.

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.

There are only 32 keywords available in C.


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Fig: Keywords
Identifiers
In C programming, identifiers are names given to C entities, such as variables, functions, structures
etc.Identifiers are created to give unique name to C entities to identify it during the execution of
program.
For example:
int money;
intmango_tree;

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.

Rules for Writing Identifier


 An identifier can be composed of letters (both uppercase and lowercase letters), digits and
underscore '_' only.
 The first letter of identifier should be either a letter or an underscore.

5.11 C Programming Variables and Constants

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.

Rules for writing variable name in C


 A variable name is any combination of alphabets, digits or underscores.
 The first character in the variable name must be an alphabet or underscore.
 No commas or blanks are allowed within a variable name.
 No special symbol other than an underscore can be used in a variable name.

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"

In C, constants can be classified as:

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.

5.12 Standard Input Output (I/O) in C


ANSI standard has defined many library functions for standard input and output in C
language.Functions printf() and scanf() are the most commonly used to display out and take input
respectively.printf() and scanf() function are defined in header file stdio.h (standard input output
header file).

 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.

General form is:


scanf(“format string”,&VariableList);

Format string can only contain format specifiers.


Example:
scanf ("%d", &x);
scanf ("%d %d", &x, &y);
scanf("%s", name); // char name[1000];

5.13 Fundamental of C Programming

Structure of C Program:

Declaration of Preprocessor Directive


Declaration of Global variable
void main() //Program execution start with main function
{
Local variable; // declaration of local variable
Statment1;
Statment2;
Statment3;
Statment4;
}

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.

You might also like