Beruflich Dokumente
Kultur Dokumente
Program:
A computer program is a set of instructions which are executed in a sequential order. In a
C program, the instructions (statements) execute in the order in which they appear until unless
the order is not specifically changed by control structures in C.
History of C:
C is originally developed by Dennis Ritchie at AT and T’s Bell Laboratories in 1972. C
was evolved from ALGOL, BCPL and B and uses many concepts from these languages and
added the concept of data types and other powerful features. One of the most popular operating
systems, UNIX is developed in C.
Many version of C were proposed and to assure that the C language remains standard,
ANSI (American National Standards Institute) appointed a technical committee in 1983 to define
a standard for C. The committee approved a version in 1989 and is referred to ANSI C. It is later
approved by ISO (International Standards Organization).
Features of C:
The increasing popularity of C is due to its many desirable qualities:
• It is a highly portable language and can be easily implemented in different
operating systems.
• It is robust language; with its rich set of built in functions and operators we can
write any complex programs easily.
• Programs written in C are efficient and fast than other languages like BASIC
• C language is well suited for structured programming, in which the programmer
thinks of a problem in terms of function modules or blocks. A proper collection of
these modules (blocks) make a complete program. That is why a C program can
termed as a collection of different functions. One of those functions is compulsory
and is it the main() function. C compiler starts execution of the program by
making a call to main function.
• C has ability to extend itself; we can continuously as add our own functions to the
C Library.
Executing a C program:
The following are series of steps involved:
• Creating the program (using a editor)
• Compiling the program
• Linking the program with functions that are needed from the C library;
• Executing the program
We can use any text editor to create a C program.
C Compiler is the software tool (or component) that is responsible for converting the high level
C program into machine understandable code (machine level language). This code is called
object code and is stored in file with the extension “.obj”. The Linker is used to link the various
functions called in program. If the functions are user defined, the definition of the function
should be in the range of the program. The operating system handles the execution of the
programs and all input and output operations are channeled through the operating system.
Commenting in C:
Comments are generally written to explain the logic of the program, sometimes to specify
the problem statement and sometimes to specify the details of the author of the program. These
comments are purely for better understandability of the user (programmer) and do not make any
sense to the C compiler. The compiler ignore the comments while generating the object code.
Therefore the file with extension .obj doesn’t contain the conversions for these comments.
Commenting in C can be done in 2 ways:
Multi-Line Commenting (/*…..*/) – the text placed between /* and */ will be commented
(ignored by compiler) and it also supports multiple lines of the commented text.
Single Line Commenting (//) – when a sequence of two forward slashes appears in the program,
the entire text following it in the same line will be commented. “\\” can comment only a single
line of text.
Flow Chart:
Flow Chart is a diagrammatic (pictorial) representation of an algorithm. It is built using
different types of shapes (rectangle, oval, etc) and symbols. Different shapes are selected to
represent different types of operations.
Flow chart helps to understand the program easily.
As different shapes are used to specify different operations it is easy to understand the
complex programs.
In the simplest form the flow chart consists of a series of interconnected rectangle in
which each rectangle specifies a specific instruction.
The following are the most commonly used symbols in a flow chart
Start/End Block: To indicate the start and end of the flow chart
Function calls
Start
No
No
z is largest.
Output z
End
Character Set:
C Tokens:
In a C program, the basic element recognized by the compiler is the "token." A token is
source-program text that the compiler does not break down into component elements. Token are
formed with the combinations of characters in character set of C. The keywords, identifiers,
constants, string literals, and operators are examples of tokens. Punctuation characters such as
brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens.
Constants:
A constant is a quantity that doesn’t change during the execution of the program.
Constants are also called literals. C supports various kinds of constants (different kind of
constants for different data types).
Illustration:
Integer Constants:
Integer constant refers to a sequence of digits. Decimal integer consists of a set of digits,
0 through 9. Integer can negative or positive. Negative integers are indicated by using the unary
operator minus (-).
Eg: 867 -124
Real Constants: are also called floating point constants. These can be represented in 2 forms
fractional form or exponential form.
In fraction form a decimal point is used.
Eg: 23.456 768.45 -945.45
The exponential form is usually used for when the value of real constant is either too small or too
large. The real constant is represented in 2 parts namely mantissa and exponent. Mantissa
appears before ‘e’ and exponent appears after ‘e’. Range of real constants expressed in
exponential form is -3.4e38 to 3.4e38.
Eg: 3.2e-5 4.1e8 +467e31
Note: ANSI C supports unary plus (+) which was not supported earlier.
Character Constants:
A character constant is either a single alphabet or a single digit or a single special symbol
enclosed within single inverted commas (apostrophes).
Eg: ’A’ ’g’ ’9’ ’*’
Each character has an integer value known as ASCII (American Standard Codes for Information
Interchange) code. For example the ASCII code associated with ’a’ is 97. To print the ASCII
code of a character we can use the format specifier %d instead of %c while in the printf
statement.
String Constants:
A string Constant is a sequence of characters enclosed in a pair of double quotes. The character
may be alphabets, digits, special characters and blank spaces.
Eg: “INDIA” “Indian Engineer” “What a pleasant day!” “?_)…-?”
Backslash Character Constants (Escape Sequences):
C supports special kind of characters which are formed by combining the normal characters with
the escape character (\). These characters have special meaning. Each represents a single
character although it has 2 characters.
Some of Escape Sequences:
Identifiers are user defined names formed with different combinations of alphabets,
digits and underscore in character set with certain rules. Identifiers are used to name the
variables, functions, arrays, etc.
Rules to forming identifiers (user defined name):
Variables:
Variable is data name that may be used to store the data value. Unlike constants (literals)
variables may have different value during the execution of program. In general a meaningful
name is chosen for a variable depending upon the context on the program. Variable names are
case sensitive and therefore variable AMOUNT is different from variable amount. Since the
variable name is identifier, the above mentioned rules need to be followed.
Declaring of variables:
Before using the variables in a program, they should be declared. Declaration tells the
compiler what the variable name is and what type of data it can store. Undefined usage of
variables results in error during compilation.
Syntax: <data type> <name>;
Separate statements need to be used to declare variables of different kinds. Multiple
variables of same kind can be defined in a single statement by separating them with commas
(separate statements are also allowed).
Eg: int a,b,c;
float x;
char str;
Initializing and assigning value to Variables: To initialize or assign a value to a variable we use
the assignment operator “=”. The variable can be initialized during declaration or can be
assigned a value anytime later.
Eg: int a=3; int sum=0; int x; x=45;
If a variable is not initialized; unpredicted values will be stored, until any value is assigned.
Data Types:
Data Types are used to specify what type of data can be stored, exchanged or returned by a
variable or a function. C supports a variety of data types which can be classified into two groups:
o Primary (Fundamental or Primitive) Data Types
The range of integers that can be stored depends on the word length of the computer. If
we use a 16 bit word length, the size of the integer is limited to the range -32768 to -32767 (i.e -
215 to 215-1). A signed integer uses the first bit for sign and 15 bit for the magnitude of the integer. If the
first bit is 1 then it indicated negative numbers. If it is Zero then it is positive number. A 32 bit word
length computer can store integers ranging from -2147483648 to 2147483647. The range of the integers
can be restricted or increased by qualifying “int” with the proper combination keywords short, long and
unsigned. “short” decreases the range where as “long” and “unsigned” increases the range. The use of
qualifier “signed” is optional because by default integers are signed integers.
Note: To distinguish long integer literals from regular literals they are appended by a qualifier L (or l).
Similarly U (or u) is appended for unsigned integers. For L and U any case can be used.
Eg: 56789U (unsigned int) 987654321ul (unsigned long integer)
987.34567784787L (long double)
Floating Point Data Type:
Floating point numbers are real numbers which can have fractional values (decimal point).
Floating Point numbers are stored with 6 digits of precision and uses 32 bits (4 bytes) of memory. The
keyword used is float. “double” can be used to increase the range real numbers and also to increase the
accuracy with higher precision. Double (double precision numbers) uses 64 bits of memory (8 bytes)
giving a 14 digit precision. To increase the precision even more we can use long double which uses 80
bits.
Character Type:
A single character type can be declared using the key word “char”. Character uses 8 bits (1 byte)
of memory for storage. While storing the chars the corresponding ASCII value is stored in binary format.
The qualifiers signed and unsigned can be used to change the range of chars. By default char is signed
char whose range is -128 to 127, where as the range of unsigned char is 0 to 255.
Void Types:
The void has no values. It is generally used to specify the type of the function and a function is
said to be void when it does not return any value. There will not be any void variables.
The size and range of different data types on a 16 bit computer are listed here:
typedef usage:
C allows the programmer to define a new data type and give it a user friendly name
which originally represents the existing data type. In other words the we can rename a existing
data type using typedef.
Syntax: typedef <type> <new name>;
Where, type can be any of the fundamental data type or a derived data type (such as structure)
which is available before execution of this statement.
units a,b;
units u=9;
Constant Variables:
A variable can be made constant throughout the execution of the program by declaring it
using the key word const.
The control string can be a format specifier or a collection of format specifiers which specify the
type of the values that can be read into the variables (variable1, variable2,..etc).
The ampersand symbol (&) before each variable is a pointer operator; which indicates the
address of the variable. This means that the values read are stored in the address of the variable.
More on this will be understood when we learn pointers.
Eg: scanf(“%d”, &var1);
%d is the format specifier which specifies that a integer value must be read from the user console
(or terminal).
To display any text (or string) or the value of any variables, we can use the printf
function. General format:
printf(“Simple String”);
printf(“Simple String + Control String”, variable1, variable2,…);
printf(“Control String”, variable1, variable2,…);
Control string specifies the type of the value that is displayed from the variables.
Eg: printf(“Hello World”);
printf(“Value of the variable x is %d”, x);
printf(“%f”, avg);
The following are the various format specifier that we can used in scanf and printf functions
as above)
%c character
%0.2f Limits the number of number Used in printf to to define the accuracy
of digits after decimal point needed. For example while dealing with cost
to 2 (can be any value less of any items, we need only two digits (that
than 6) represent paise) after decimal point.
%u Unsigned int
Operators:
C supports a huge variety of operators. An operator is use to ask the computer to perform
certain mathematical or logical manipulations. Operators are used to manipulate data and
variables.
Following are the categories of operators in C:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operator
Increment and Decrement Operators
Conditional Operators
Bitwise Operators
Special Operators
Arithmetic Operators:
These operators are used to perform the basic Arithmetic operations such as addition,
subtraction, multiplication and division.
Unary minus operator in effect multiplies its single operand by -1 there by changing the
sign of the operand.
Integer Division truncates (does not round off) any fractional part
The modulo division operator gives the reminder after performing the integer division.
Modulo Division cannot be performed on floating point.
% Modulo Division. Can be used only for integers and Binary (2)
produces reminder of integer division
If both operands of an arithmetic operation are integers then it is called integer expression and
the result of the integer expression will be an integer.
Eg: 2+3 the result is 5
5/2 the result is 2 and not 2.5 (decimal part is truncated in integer division)
5%2 the result is 1 (% returns the reminder of integer division of 5 by 2)
If an expression has both real operands (float or double) then it is called real expression and
result will be a real number.
5.0/2.0 the result is 2.5
4.3/8.45 0.508876
An expression involving one integer operand and one real operand can be called as mixed mode
operation and the result of mixed mode operation is a real number.
5.0/2 2.5 (even if 2 is integer 5.0 is real and so result is real).
Relational Operators:
These operators are used to compare two quantities to determine the relation between
those quantities.
An expression that contains relational operators is called relational expression. The result of the
relational expression is either one or zero (true or false in advanced languages). Zero
corresponds to false and one corresponds to true.
Eg: a<b i<20 u>=34 etc
Following are the 6 relational operations:
Operator Description Cardinality
< used to check if the left hand operand is less than right hand Binary(2)
operand
> used to check if the left hand operand is greater than right Binary
hand operand
== This is used to check if the value of left hand operator is equal Binary
to right hand operator. Note that this is different from
assignment operator (=)
Relational operations can be performed on multiple arithmetic expressions. In such cases the
arithmetic expression are evaluated first and then the results are compared.
Eg: (a+2) < (b-c);
Relational expressions are used to form conditions in the decision statements (will be explained
later).
Logical Operators:
Logical Operators are used to perform logical AND, logical OR and NOT. Logical
operators are used to check more than one condition.
&& -- Logical AND
|| -- Logical OR
! -- Logical NOT
“&&” and “||” are binary operations and “!” is a unary operator.
An expression which combines 2 or more relational expressions by using logical operations is
called a compound relational expression.
Eg: a>b && x==10 d<=f || r>=e !(d!=f)
Truth Table
Op1 Op2 Value of the Expression
Non-Zero (1) 0 0 1
0 Non-Zero (1) 0 1
0 0 0 0
NOT (!) has only operand and can represented as !Op1. If Op1 is a Non-Zero value then the
result of !Op1 is zero. If the value of Op1 is zero then the result of !Op1 is 1.
Assignment Operators:
Assignment operators are used to assign the result of an expression to a variable. The
operator “=” is used for assignment.
Eg: v1= 20; v2= v1+v3;
C also supports shorthand assignment operators of the form
v op= exp;
where v is a variable, exp is an expression and op is a binary arithmetic operation. The operator
op= is known as the shorthand assignment operator.
The statement v op= exp is equivalent to v = v op exp. The operation op can be +, -, %, / or *.
Eg: a *=b (a= a*b) x += 2 (x= x+2) a /= n+2 [a= a/(n+2)]
Shorthand assignment makes the statement more concise and easy to read and makes it more
efficient.
printf(“%d %d %d”,a,b,c);
Output: 7 5 7
Conditional Operator:
The conditional operator “?:” is used to form conditional expressions of the form
exp1 ? exp2 : exp3;
where exp1, exp2 and exp3 are expressions.
exp1 is evaluated first and if it is nonzero (true), then the expression exp2 is evaluated and
becomes the value of the expression. If exp1 is zero (false) then exp3 is evaluated and it becomes
the value of the expression (can be assigned to any variable).
Eg: q = (f>g)?f:g
The above statement makes the variables to be assigned with greatest of both f and g. If f=5 and
g=6 then f>g condition returns false and so q=g i.e. q=6.
Logically this is equivalent to using if else block.
if(f>g)
q=f;
else
q=g;
Bitwise Operators:
These operators are used to manipulate the data at bit level. They can be used for testing
the bits, shifting them right or left. Bitwise operators may not be applied to float or double.
Bitwise AND “&” is used to perform AND operation on individual bits of the operands. It is a
binary operation and needs two operations.
Eg: c=2 & 3;
First the two operands are converted into binary bits and then AND operation is
applied on individual bits. If assume the word length of a computer as 16bit we will have 16
digits in the binary conversion.
2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1
----------------------------------------
2 & 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 2 (result)
Bitwise OR “|” (single pipeline) is used to perform OR operation on individual bits of the
operands. This is again a binary operations and it needs 2 operands.
Eg: j= 5 | 9;
First 5 and 9 are converted into binary system and later on OR operation is performed
on each bit of the numbers.
5 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
9 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1
----------------------------------------
5 | 9 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 13 (result)
Bitwise exclusive OR “^” – this is similar to the operations except that it performs exclusive OR
operation on
Shift left or left shift “<<” is used to shift the significant bits of the operand to left.
Eg: c= a<<b;
Where “a” is operand whose bits has to be shifted left and “b” is number of positions that they
should be shifted. The result of the operation is assigned to “c”.
Let value of “a” be 5 and value of “b” be 1. This means the significant bits of the binary
conversion of 5 should be shifted left by one position.
5 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
5<<1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 10
In the above illustration the underlined bits are the significant bits as all other digits before them
are zero’s. They are shifted left and gap formed on the right is filled with zero.
Note: Left shifting a number by one position will double the value (in above case result of 5<<1
is 10). Therefore x=x<<1 will simply double the value of “x”. Similarly x=x<<2 will make it
four times.
Shift right or right shift “>>” is used to shift the significant bits of the operand to right.
Eg: c= a>>b;
Where “a” is operand whose bits has to be shifted right and “b” is number of positions that they
should be shifted. The result of the operation is assigned to “c”.
Let value of “a” be 4 and value of “b” be 1. This means the significant bits of the binary
conversion of 4 should be shifted left by one position.
4 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
4>>1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 2
In the above illustration the underlined bits are the significant bits as all other digits before them
are zero’s. They are shifted right and gap formed on the left is filled with zero. Notice that right
most digit (0 in this case) is eliminated.
Note: Right shifting a number by one position will half the value (in above case result of 4>>1 is
2). Therefore x=x>>1 will simply reduce the value of “x” to half. Similarly x=x>>2 will make it
reduced to 1/4th.
One’s Complement “~” (can also be referred to as bitwise NOT) is a unary operation that
applies on a single operand and performs logical NOT operation on individual bits of the binary
conversion of the operand.
Eg: c= ~a;
where “a” is the operand on which one’s complement is applied and the value is assigned to “c”.
Let value of a be 6.
6 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0
~6 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 1
Special Operators:
C supports some special operators such as comma (,) operator, sizeof operator, pointer
operator (& and *) and member selection operators (, and ->).
Comma Operator “,” is used to link the related expressions together. A comma-linked
expression is evaluated left to right. The value of the right most expression is the value of the
combined expression.
Eg: x = (a = 34, b = 4, a+b);
In the above statement first the value 34 is assigned to “a” and then 4 us assigned to “b” and the
addition (a+b) is performed and the result of a+b is stored in “x”.
Since comma operator has lowest precedence use of parenthesis is compulsory. Some
applications of comma operator are as follows
Notice that both i and j are initialized using comma operator and the “;” is used to specify the
condition and in the last section both i and j are incremented using comma operator.
while(c=getch(), c!= ’z’)
A character is read from the user and stored in c and a condition is formed on the value of c.
sizeof operator is a compile time operator and which is performed on only one operand to find
the number of bytes the operand occupies. The operand may be a variable, constant or a data
type. This operator is generally used to find the size of arrays, structures, etc.
Eg: x= sizeof(sum);
printf(“The size of int is %d“,sizeof(int));
Simple if statement:
The if statement is a powerful decision making statement and is used to control the flow
of execution of statements. The general form of a simple if is:
if (test expression)
{
Statement-block;
}
Statement-x;
The statement block can be a single statement or a group of statements. If the test-expression is
true, the statement block is executed and the control continues to statement-x. If the test-
expression is false then statement block inside the ‘if’ is skipped and the execution continues
with statement-x. Therefore when the test-expression is true both statement block and statement-
x are executed where as in other case only statement-x is executed. The flow of simple can be
represented in the following way:
if(num%2==1)
printf(“The entered number %d is a odd number”, num);
}
De Morgan’s Rule: when applying logical NOT on complex relational expressions we have to
keep in mind that the expressions will be evaluated using De-Morgan’s rule.
Eg: !(a||b && !(p>q)) will be equivalent to !x && !b || !p < !q
!(a && b) ≈ !a || !b
if..else statement:
This is the extension of simple if statement and the general form is
if(test-expression)
{
Statement-block-x; //true block
}
else
{
Statement-block-y //false block
}
Statement-block-z;
If the test-expression is true, then the Statement-block-x (true block) is executed; if the test-
expression is false, then the Statement-block-y is executed. In both the cases the control is passed
to Statement-block-z. The flow of the if..else statement can be show in the following way:
Note:
An else cannot exist without the if block; else should always pair with if.
After a single if block, there can be only one else block following it.
There cannot be any other statements between if block and else block.
The sequence of execution of the statements can be described using the following table:
Lets represent condition as c-1,c-2, etc and statement as s-a, s-b, etc.
c-1 c-2 c-3 s-a (executed Y/N) s-b s-c s-d s-e s-f
Flow Chart:
Entry
C-1
true
Statement-a
false
C-2
true
false
Statement-b
Statement-c
Statement-e
false C-3 true Statement-d
Statement-f
if-else ladder:
The if-else ladder is another way of using multiple if. This is used when choice has to be made
among multiple blocks of statements based on various test conditions. The general form of if-
else ladder is:
if(condition 1)
statement-1;
else if(condition-2)
statement-2;
else if(condition-n)
statement-n;
else
statement-default;
statement-x;
In the above illustration when condition-1 is true only statement-1 is executed and when
condition-2 is true only statement-2 is executed and in general when condition-n is true
statement-n is executed. Therefore statement 1 through n are executed mutually exclusive (if one
is executed rest all are skipped). When all n conditions are false, then the statement-default in the
last else is executed. In an ‘if-else’ ladder each else block is paired with the ‘if’ statement
immediately above it. The flow chart for the above general form is as follows:
Switch Statement:
switch (expression)
{
case value-1:
statement block-1;
break;
case value-2:
statement block-2;
break;
………………………
………………………
default:
default-block;
break;
}
statement-x;
• Absence of break in any of the case block makes the execution to continue with the next
case statements as well until break is reached or end of switch is reached. (Eg: Lab Ex-10)
Flow Chart illustrating the selection of statements in switch:
printf(“Illegal choice”);
}
C supports goto statement to support unconditional branching from one point to another
point of program. In other words goto statement makes the flow of control to jump to a
location in the program unconditionally.
goto requires a label to identify the place where the control has to be jumped. Label can
be any valid name followed by a colon “:”. The label is place just above the statements
where the control has to be transferred.
Depending on place of the label in the program goto will result in either forward jump or
backward jump. Below is a illustration:
Eg:
main()
{
int x,y;
read:
scanf(“%d”, &x);
if(x<0)
goto read;
y=x*x;
if(y<25)
goto read;
}
Note: In a structured programming like C, it not essential to use goto. Since the control
is made to jump unconditionally here and there, the best practice is to avoid goto
statements until unless it is inevitable (not avoidable).
In a nested loop structure when a break statement is used in the inner most loops,
it will just break the inner most loop and continue the execution of outer loop(s). If there
is requirement where in all loops’ execution has to be stopped we can use goto.
Eg:
for(i=1:i<4;i++) for(i=1:i<4;i++)
{ {
for(j=1;j<4;j++) for(j=1;j<4;j++)
{ {
if(j==3) if(j==3)
break; goto label1;
printf(“%d-%d ”,i,j); printf(“%d-%d ”,i,j);
} }
} }
label1:
printf(“ --End”); printf(“ --End”);
Ouput: 1-1 1-2 2-1 2-2 3-1 3-2 --End 1-1 1-2 --End