Sie sind auf Seite 1von 26

C & DS for I MCA Unit-1 VVIT

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

Staff: Janaki Ram N. Dept of IT Page:1


C & DS for I MCA Unit-1 VVIT

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.

Algorithm and Flow Chart:


Since we will be solving lot of logical problems while writing C programs, it is necessary
to understand the components (namely Algorithm/ Pseudo code and Flow Chart) that can be used
to represent solutions for complex problems.

Algorithm/ Pseudo code:


An algorithm is a method of representing the step-by-step procedure for solving a
problem. An algorithm is very useful for finding the right solution for a problem by breaking the
problem into simple cases. An algorithm is also called Pseudo code. For example a simple
algorithm for finding a large among three numbers can be written like this.
Begin
1. Read 3 numbers x,y,z from the user.
2. if x>y and x>z
3. then x is the largest
4. else if y>z and y>z
5. then y is the largest among the 3 numbers
6. else
7. Z is the largest of the three.
8. End-if
End.

Staff: Janaki Ram N. Dept of IT Page:2


C & DS for I MCA Unit-1 VVIT

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

Process Block: To place individual statements those are to be processed?

Decision Block: To place decision making conditions

Output statements (displaying output)

Function calls

Connector: used to connect different paths which are merging.

Staff: Janaki Ram N. Dept of IT Page:3


C & DS for I MCA Unit-1 VVIT

Flow chart for the above algorithm will be as follows:

Start

Read values for x,y,z

x>y & Yes X is largest.


x>z Output x

No

y>x & Yes y is largest.


Output y
y>z

No

z is largest.
Output z

End

Getting started with C:


Learning C language is similar to learning the English language. The classical method of
learning English to learn the set of alphabets (character set in C), words (tokens) and sentences
(sentences) and paragraphs (program). It is just that they are termed differently in C.

Character Set:

The character set of C language contains the following:


Alphabets – A, B, C, …….X, Y Z
a, b, c……….. x, y, z
Digits – 0, 1, 2, 3…….9
Special symbols: ~ ` ! @ # % $ & * ( ) _ - + = | \ { } [ ] : ; “ ‘ < > , . ? /

Staff: Janaki Ram N. Dept of IT Page:4


C & DS for I MCA Unit-1 VVIT

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

Staff: Janaki Ram N. Dept of IT Page:5


C & DS for I MCA Unit-1 VVIT

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:

’\b’ blank space ’\’’ single quote


’\f’ form feed ’\”’ Double Quote
’\n’ new line ’\?’ Question Mark
’\r’ carriage return ’\\’ back slash
’\t’ horizontal tab ’\0’ Null
’\v’ vertical tab ’\a’ audible alert

Keyword and Identifiers


Keywords are the word in C which has fixed meaning and these meanings cannot be
changed. They serve as the building blocks of the program. The following is the list of 32
keywords in C.

Staff: Janaki Ram N. Dept of IT Page:6


C & DS for I MCA Unit-1 VVIT

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

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

 Identifiers must start with an alphabet or underscore.


 Identifiers cannot contain special character other than underscore.
 Maximum length should be 31 characters.
 Should not be a keyword

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.

Eg: x, sum, Avg, Root1, Nearest_Number.

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

Staff: Janaki Ram N. Dept of IT Page:7


C & DS for I MCA Unit-1 VVIT

o User Defined Data Types (Derived Data Types)

Primary Data Types:


C compiler supports 5 fundamental data types namely int, float, double, char and void.
Many compilers also support extended data types such as long int, long double, unsigned int,
short int, unsigned long int, unsigned short int, unsigned char, etc.

Integer types (int):


Integers are the natural numbers (1, 2, 3….) including 0 and their negatives (-1, -2, -3,
….). int is the keyword used to declare variable or functions of type integer. On a 16 bit
computer when an integer is declared it is allocated 2 bytes of memory.
Eg: int x;

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.

Eg: float avg; double discriminant; long double acc_value;

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:

Staff: Janaki Ram N. Dept of IT Page:8


C & DS for I MCA Unit-1 VVIT

User-defined Data Types (Derived Data Types):


These data types are created by the user (programmer), which are either derived from
primitive data types or formed by different combination of the primitive data types. Derived data
type can be a structure, union, enum, pointer or it can be type defined using typedef keyword.

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.

Eg: typedef int units;


Once the above statement is executed, a new data type units is available whose behavior
exactly same as int. So we can now create variable, functions, etc of type units.

units a,b;
units u=9;

Other user defined data types will be discussed later.

Constant Variables:
A variable can be made constant throughout the execution of the program by declaring it
using the key word const.

Staff: Janaki Ram N. Dept of IT Page:9


C & DS for I MCA Unit-1 VVIT

Eg: const int size=100;


In the above case, the value of the variable size is always 100. It variable size can be used
anywhere in the program but the value cannot be altered. Constant variable must compulsorily be
initiated while they are declared. They cannot be initialized in a separate statement as we can do
in case of normal variables.

Reading and Displaying Data:


As we have seen earlier, variables can be assigned values with the help of the assignment
operator. Another way of assigning a value to variable is by using scanf function.

The general format of scanf is: scanf(“control string”, &variable1,&variable2,…);

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

Format Used to Represent Comment


specifier

%d signed decimal integer used in both scanf and printf

%i signed decimal integer (same used in both scanf and printf

Staff: Janaki Ram N. Dept of IT Page:10


C & DS for I MCA Unit-1 VVIT

as above)

%c character

%s string (character array) In scanf multi word strings cannot be read.

%f Floating Point Number By default displays the 6 precision digits when


used in printf

%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

%% Used to display the percent used only in printf not in scanf


symbol

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.

Staff: Janaki Ram N. Dept of IT Page:11


C & DS for I MCA Unit-1 VVIT

Operator Description Cardinality

+ This is used to perform addition on integers or real Binary/Unary (2


numbers. This can also be used as unary plus (optional) or 1)

- This used to perform subtraction on integers or real Binary/Unary (2


numbers. This is also used as unary minus or 1)

* This is called asterisk and is used to perform Binary (2)


multiplication.

/ Forward slash operator is used to perform division Binary (2)

% 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

Staff: Janaki Ram N. Dept of IT Page:12


C & DS for I MCA Unit-1 VVIT

<= less than or equal to Binary

> used to check if the left hand operand is greater than right Binary
hand operand

>= greater than or equal to Binary

== 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 (=)

!= not equal to Binary

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

Op1 && Op2 Op1 || Op2

Non-Zero (1) Non-Zero (1) 1 1

Non-Zero (1) 0 0 1

0 Non-Zero (1) 0 1

0 0 0 0

Staff: Janaki Ram N. Dept of IT Page:13


C & DS for I MCA Unit-1 VVIT

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.

Increment and Decrement Operators:


Both the operators are unary and operate on only one operand. Increment operator is ++
and increases the value of the operand by 1. Decrement operator is – and subtracts 1 from the
operand.
Based the place the operator is placed w.r.t operand there can post increment and pre decrement.
Similarly post decrement and pre decrement also exists.
If the operator is placed before the operand then it is pre (increment or decrement) else if it
placed after the operand then it called post (increment or decrement).
Eg: i++ ++i --j j--
i++ and ++i are equivalent to i=i+1 and --j and j-- are equivalent to j=j-1.
++i and i++ mean the same when they are independent statements. But when used in a
expression they behave differently. In an expression when ++i is used, the value of i is
incremented before it is used in the evaluation of the expression, where as when i++ is used, the
previous value i is first used for evaluating the expression and later incremented.
Sample code for illustration:
int a=5,b,c;
a++; //increment value of a by 1 so a value is 6
--a; //decrements the value of a by one and so value of a will be 5
b=a++; //since post increment is used, the value of a (5) is assigned to b and later
//incremented. Therefore b will be 5 and a will be 6
c=++a; //since pre-increment is used, the value of a is incremented before assigning it to c
// Therefore value of c will be 7 and value of a will be 7

Staff: Janaki Ram N. Dept of IT Page:14


C & DS for I MCA Unit-1 VVIT

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.

Staff: Janaki Ram N. Dept of IT Page:15


C & DS for I MCA Unit-1 VVIT

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.

Staff: Janaki Ram N. Dept of IT Page:16


C & DS for I MCA Unit-1 VVIT

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

for( i=0, j=10; i<=j; i+=2, j++)

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

Staff: Janaki Ram N. Dept of IT Page:17


C & DS for I MCA Unit-1 VVIT

Operator Precedence and Associativity:


In general expressions can involve many operators and when multiple operators are used,
the order in which operations are performed should be defined. The precedence and associativity
of operators are used to determine how an expression involving multiple operators should be
evaluated. There are different levels of precedence and the operation involving highest
precedence operator will be evaluated first. The operators of same precedence are evaluated
either from left to right or right to left depending on the associativity property of the operator.
Most of the operator will have left to right associativity where some of them have right to
left associativity. Here is a table:

Staff: Janaki Ram N. Dept of IT Page:18


C & DS for I MCA Unit-1 VVIT

Decision Making Statements:

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:

Eg: Program to check if a number is even or not.


#include<stdio.h>
void main()
{
int num;
printf(“Enter the number: ”);
scanf(“%d”, &num);
if(num%2==0)
printf(“The entered number %d is a even number”, num);

Staff: Janaki Ram N. Dept of IT Page:19


C & DS for I MCA Unit-1 VVIT

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:

Staff: Janaki Ram N. Dept of IT Page:20


C & DS for I MCA Unit-1 VVIT

Eg: The above program can be re-written in the following way.


#include<stdio.h>
void main()
{
int num;
printf(“Enter the number: ”);
scanf(“%d”, &num);
if(num%2==0)
printf(“The entered number %d is a even number”, num);
else
printf(“The entered number %d is a odd number”, num);
}

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.

Nested if – else statements:


When a series of decisions are involved, we may have to use more than on if-else
statements in the nested form and it can be something like this.
if(condition-1)
{
Statement-block-a;
if(condition-2)
Statement-block-b;
else
{
Statement-block-c;
}
if(condition-3)
{
Statement-block-d;
}
}
else
{
Statement-block-e;
}
Statement-block-f;

Staff: Janaki Ram N. Dept of IT Page:21


C & DS for I MCA Unit-1 VVIT

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

True True True Y Y N Y N Y

True True False Y Y N N N Y

True False False Y N Y N N Y

True False True Y N Y Y N Y

False True/False True/False N N N N Y Y

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

Staff: Janaki Ram N. Dept of IT Page:22


C & DS for I MCA Unit-1 VVIT

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:

Staff: Janaki Ram N. Dept of IT Page:23


C & DS for I MCA Unit-1 VVIT

Switch Statement:

A switch control structure or statement is an alternative to if..else ladder. It is also known


as multiple branch selection statement. In order to use switch control statement, four keywords
are required. They are: switch, case and break. The general form follows:

switch (expression)
{
case value-1:
statement block-1;
break;
case value-2:
statement block-2;
break;
………………………
………………………

default:
default-block;
break;
}
statement-x;

• The expression is an integer expression or a character. Cannot be a real or other


expression.
• The value-, value-2, … are the constants or constant expressions and are known as case
labels. These labels are the possible values of the expression given in switch. Case labels
end with “:” which are followed by statement blocks.
• There cannot be two case labels with same value.
• When a switch is executed, the value of expression is compared with case labels and the
statement block defined in that case is executed.
• The break statement at the end of each block causes the exit from the switch statement,
there by achieving the exclusivity among the multiple statement blocks. In other words;
when expression evaluates to value-1, only statement-block1 is executed; if it is value-2
only statement-block-2 is executed and so on.
• The default executed when the value of expression matches none of the case labels. The
default section is generally defined at the end of switch and it is optional. When it is used
as last section, usage of break statement is also optional.
• When default is not defined and none of the case labels match the expression value, the
execution continues to statement-x without executing any block in the switch.

Staff: Janaki Ram N. Dept of IT Page:24


C & DS for I MCA Unit-1 VVIT

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

Ex: printf(“Enter day value”);


scanf(“%d”,&day);
switch(day)
{
case 1:
printf(“Sunday”);break;
case 2:
printf(“monday”);break;
case 3:
printf(“tueday”);break;
case 4:
printf(“wednesday”);break;
case 5:
printf(“thursday”);break;
case 6:
printf(“friday”);break;
case 7:
printf(“Saturday”);break;
default:

printf(“Illegal choice”);
}

Staff: Janaki Ram N. Dept of IT Page:25


C & DS for I MCA Unit-1 VVIT

The goto statement:

 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

Staff: Janaki Ram N. Dept of IT Page:26

Das könnte Ihnen auch gefallen