Anda di halaman 1dari 11

UNIT – II

Introduction to C Language – C Language Elements, Variable Declarations and Data Types, Executable Statements, General Form of a C Program, Expressions,
Precedence and Associativity, Expression Evaluation, Operators and Expressions, Type Conversions, Decision Statements – If and Switch Statements, Loop
Control Statements – while, for, do-while Statements, Nested for Loops, Other Related Statements -break, continue, goto.

Introduction to C Language
C is a programming language which born at
“AT & T’s Bell Laboratories” of USA in 1972. It
was written by Dennis Ritchie. This language was
created for a specific purpose: to design the UNIX
operating system (which is used on many computers). From the beginning, C was intended to be useful--to
allow busy programmers to get things done.
Because C is such a powerful, dominant and supple language, its use quickly spread beyond Bell
Labs. In the late 70’s C began to replace widespread well-known languages of that time like PL/I, ALGOL
etc. Programmers everywhere began using it to write all sorts of programs. Soon, however, different
organizations began applying their own versions of C with a subtle difference. This posed a serious problem
for system developers. To solve this problem, the American National Standards Institute (ANSI) formed a
committee in 1983 to establish a standard definition of C. This committee approved a version of C in 1989
which is known as ANSI C. With few exceptions, every modern C compiler has the ability to adhere to this
standard. ANSI C was then approved by the International Standards Organization (ISO) in 1990.

Why Use C?
In today's world of computer programming, there are many high-level languages to choose from, such as
Pascal, BASIC, and Java. But C stands apart from all these languages. This is due to its many desirable
qualities. It is a robust language whose rich set of built-in functions and operators can be used to write any
complex logic program. The C language compiler combines the capabilities of a low level language with the
features of a high level language. Therefore the language is suitable for writing both system software as well
as business packages & other software.
 Program written in c are very efficient and fast. This is due to its variety of data types and powerful
operators. It is many time faster than BASIC. This helps developers in saving their valuable time.
 C is a powerful and flexible language which helps system developers to deliver various complex
tasks with ease. C is used for diverse projects as operating systems, word processors, graphics,
spreadsheets, and even compilers for other languages.
 C is popular among professional programmers for programming, as a result, a wide variety of C
compilers and helpful accessories are available.
 C is highly portable language. This means that a C program written for one computer system (an
IBM PC, for example) can be run on another system (a DEC VAX system, perhaps) with little or no
modification. Portability is enhanced by the ANSI standard for C, the set of rules for C compilers.
 C’s another striking feature is its ability to extend itself. A C program is basically a collection of
various function supported by C library (also known as header files). We can also add our own
functions to the C library. These functions can be reused in other applications or programs by
passing pieces of information to the functions, you can create useful, reusable code.
 Writing C program with user-defined functions makes program more simple and easy to understand.
Breaking a problem in terms of functions makes program debugging, maintenance and testing easier.

1
Structure of C program or General form of C Program
/* Documentation Section
This section give details or documentation about the program */
/* Link Section
This section provides the instruction to the compiler to link functions from system library */
/* Definition Section
The definition section defines all symbolic constants */
/* Global declaration Section
The variable which is declared as global, out side of main(), having the visibility to all
functions */

void main(int argc, char *argv[])


{
/* Function Prototypes
The model of the function should be declared before its calling and its definition */
/* Variable Declaration
Declaring the variables before its usage */
/* Input part
Reading data from console or initializing variables*/
/* Calculation Part */

/* Output Part
Print the result as output */
}
/* Sub program or user defined program section */
return_type function_name(argument_list)
{
/* Body of the function which is same as main() */
}

A Simple C program
void main()
{
/* variable declarion & Initialization */
int i=10; /* integer variable i and its value is 10 */
float f=2.34; /* float variable f and its value is 2.34 */
char c=’x’; /* char variable c and its value is ‘x’ */

/* Output */
printf(“\nThe integer value is %d”,i);
printf(“\nThe float value is %d”,f);
printf(“\nThe char value is %d”,c);
}

Variables
Variables in C are memory locations that are given names and can be assigned values. We use
variables to store data in memory for later use.
There are 2 basic kinds of variables in C which are numeric and character.
Numeric variables
Numeric variables can either be integer values or they can be Real values. Integer values are whole
numbers without a fraction part or decimal point in them. Real numbers can have a decimal point in them.

Character variables

2
Character variables are letters of the alphabet as well as all characters on the ASCII chart and even
the numbers 0 - 9. Characters must always be put between single quotes. A number put between single
quotes is not the same thing as a number without them.

Constants
The difference between variables and constants is that variables can change their value at any time
but constants can never change their value. Constants can be useful for items such as Pi or the charge on an
electron. Using constants can stop you from changing the value of an item by mistake.

To declare a variable we first put the type of variable and then give the variable a name.

C Tokens
The tokens are the individual words and punctuation marks. C programs are written using these
tokens and the syntax of the language.
1. Keywords - float,while,auto
2. Identifiers - x,y,sal
3. Constants - 11,22,29.60,’a’
4. Strings - “abc”,”hello”
5. Special Symbols - #,[].{}
6. Operators - +,-,*

Character Set in C
The character set in C are grouped into
1. Letters - A,B….Z,a,b…z
2. Digits - 0,1,2,….9
3. Special Characters - @,#,^
4. White Spaces -

Escape Sequences
An escape sequence provides special formatting control. An escape sequence consists of a backslash (\)
followed by a single character. \n is an escape sequence, it is called the newline character, and it means
"move to the start of the next line." Escape sequences are also used to print certain characters.
Character combinations consisting of a backslash (\) followed by a letter or by a combination of
digits are called "escape sequences." To represent a newline character, single quotation mark, or certain
other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a
single character and is therefore valid as a character constant.
Escape sequences are typically used to specify actions such as carriage returns and tab movements
on terminals and printers. They are also used to provide literal representations of nonprinting characters and
characters that usually have special meanings, such as the double quotation mark (").
List of Escape Sequences
S. No Escape Represents

1 \a Bell (alert)
2 \b Backspace
3 \f Formfeed
4 \n New line
5 \r Carriage return
6 \t Horizontal tab
7 \v Vertical tab
8 \' Single quotation mark
9 \" Double quotation mark
10 \\ Backslash
11 \? Literal question mark
12 \ ooo ASCII character in octal notation
3
13 \x hh ASCII character in hexadecimal notation
14 Unicode character in hexadecimal notation if this escape sequence is used in
a wide-character constant or a Unicode string literal.
\x hhhh
For example, WCHAR f = L'\x4e00' or WCHAR b[] = L"The
Chinese character for one is \x4e00".
15 / Preprocessor line continuation, must be immediately followed by a newline.
16 \0 Null 000 Displays a null character – End of String
Program:
#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
printf("\vMy C Program");
printf("\nMy C Program"); /* \n - prints in new line */
printf("\tMy C Program"); /* \t - Horitantal Tab */
printf("\vMy C Program"); /* \v - Vertical Tab */
printf("\aMy C Program"); /* \a - Alert Bell */
printf("My C \r Program"); /* \r - Carriage Return */
printf("My \" C \" Program"); /* \" - prints double quote */
printf("My \' C \' Program"); /* \' - prints single quote */
printf("\nMy C Program\b\b"); /* \b - Back Space */
printf("My \\ C \\ Program"); /* \\ - prints \ */
printf("My C Program"); /* \v - Vertical Tab */
}

Data Types

Format Specifier or Control String


A conversion specifier consists of the percent sign (%) followed by a single character.
The example, the conversion specifier is %d. A conversion specifier tells printf() how to interpret the
variable(s) being printed. The %d tells printf() to interpret the variable x as a signed decimal integer.
Data Type Format Specifier
int %i or %d
signed int %d Identifiers
unsigned int %u In C, the names of
Octal int %o variables, functions,
Hexa decimal %x labels, and various other
Long int %ld user-defined items are
Float %f called
Long float or double %lf identifiers. The length of
Char %c these identifiers can vary
String %s from one to several
4
characters. The first character must be a letter or an underscore, and subsequent characters must be either
letters, digits, or underscores.
Ex:- salary, marks, _num, m1,m2

Keywords (or) Reserve words


32 keywords defined by the C89 standard. Keywords are the words whose meaning has been already
explained to the C compilers.
Keywords can’t be used as a variable name because if we do so we are trying to assign new meaning
to the existing keyword, which is not allowed. The keywords are also called reserved words.
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
Keywords Added by C99
_Bool _Imaginary restrict
_Complex inline

Type Conversions
Converting an expression of a given type into another type is known as type-casting.
Implicit conversion:- Implicit conversions do not require any operator. They are automatically performed
when a value is copied to a compatible type.
float a=2.345;
int b;
b=a;
Here, the value of a has been promoted from float to int and we have not had to specify any type-casting
operator. This is known as a standard conversion. Standard conversions affect fundamental data types, and
allow conversions such as the conversions between numerical types (short to int, int to float, double to int...),
to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision,
which the compiler can signal with a warning. This can be avoided with an explicit conversion.
Explicit conversion:- Many conversions, specially those that imply a different interpretation of the value,
require an explicit conversion.
(data type ) Expression;
Ex: res = (float)5/2;

Precedence and Associativity


Hierarchy of Operations
While executing an arithmetic statement, which has two or more operators, we may have some
problems as to how exactly does it get executed. For example, does the expression 2 * x - 3 * y correspond
to (2x)-(3y) or to 2(x-3y)? Similarly, does A / B * C correspond to A / (B * C) or to (A / B) * C? To answer
these questions satisfactorily one has to understand the ‘hierarchy’ of operations. The priority or precedence
in which the operations in an arithmetic statement are performed is called the hierarchy of operations.
1st Operators */%
2nd +-
3rd =
Each operator in ‘C’ has a precedence associated with it. This Precedence is used to determine how
an expression involving more than one operator is evaluated. Precedence is used to determine the order in
which different operators in a complex expression are evaluated.
There are distinct levels of precedence and an operator may belong to one of these levels. The
relative precedence of arithmetic operators can be given from two distinct levels, they are
HIGH PRIORITY: * , / , %
5
LOW PRIORITY: +, –
The basic evaluation procedure includes 2 left to right passes. During the first pass, the high priority
operators are applied as they are Encountered during the second pass, the low priority operators are applied
as they are encountered.
Example:
1) a*b+c first a*b will calculate, and result will be added with c
2) a*(b+c) first (a+b) will calculate, because parentheses are having high priority than arithmetic
operators, next result will multiplied with a.
Associativity can be left – to – right or right – to – left evaluation of expressions. Left – to – right
associativity evaluates the expression by starting on the left and moving to the right. Conversely, right – to –
left associativity evaluates the expression by proceeding from right to the left. However, the associativity is
used only when the operators all have the same precedence.

Left – to – right associativity:


a * b / c % d * e is evaluated as

a*b /c %d *e

Right – to – left associativity:


a += b *= c -= d += e is evaluated as

d +=
a += b *= c -=
e

List of Precedence and Associativity

Operators : Operators are the operations performed on operands. In general operators are
1. Arithmetic Operators (+, -, *, /, %)
2. Relational Operators (<, <=, >, >=, ==)
3. Logical Operators (&&, ||, !)
4. Bitwise Operators (&,|,^,~,<<,>>)
5. Comma Operators (,)
6. Assignment Operators (=)
7. Conditional Operators (? :)
We can classified operators based on number of operands, they are
1. Unary Operators (++, --)
In Unary operator, the operator operates on a single operand only.
X++, y--
2. Binary Operators (+,-,<)
In Binary operator, the operator operates on two operands.
x+y, a<b
3. Ternary Operators (? :)
In Ternary operator, the operator operates on two operands or expressions
(a>b)?printf(“a is big”):printf(“b is big”);

6
Bitwise Operators (& , | , ^ , ~ , >> , <<)
A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits.
Operator Expression Description
& R=2&3 2= 0000 0000 0000 0010 The bitwise-AND operator compares each bit of its first operand to
3= 0000 0000 0000 0011 the corresponding bit of its second operand. If both bits are 1, the
2&3=0000 0000 0000 0010 corresponding result bit is set to 1. Otherwise, the corresponding
result bit is set to 0.
^ R=2^3 2= 0000 0000 0000 0010 The bitwise-exclusive-OR operator compares each bit of its first
3= 0000 0000 0000 0011 operand to the corresponding bit of its second operand. If one bit is
2^3= 0000 0000 0000 0001 0 and the other bit is 1, the corresponding result bit is set to 1.
Otherwise, the corresponding result bit is set to 0.
| R=2|3 2= 0000 0000 0000 0010 The bitwise-inclusive-OR operator compares each bit of its first
3= 0000 0000 0000 0011 operand to the corresponding bit of its second operand. If either bit
2|3= 0000 0000 0000 0011 is 1, the corresponding result bit is set to 1. Otherwise, the
corresponding result bit is set to 0.
~ 0 0000 0000 0000 0000 The bitwise complement operator, the tilde, ~, flips every bit. A
(complement)
useful way to remember this is that the tilde is sometimes called a
~0 1111 1111 1111 1111 twiddle, and the bitwise complement twiddles every bit: if you have
a 1, it's a 0, and if you have a 0, it's a 1.
Bitwise Shift Operator (<< , >>)
• The bitwise shift operators move the bit values of a binary object. The left operand specifies the value to be
shifted. The right operand specifies the number of positions that the bits in the value are to be shifted. The
result is not an lvalue. Both operands have the same precedence and are left-to-right associative.
• Each operand must have an integral or enumeration type. The compiler performs integral promotions on the
operands, and then the right operand is converted to type int. The result has the same type as the left
operand (after the arithmetic conversions).
• The right operand should not have a negative value or a value that is greater than or equal to the width in bits of
the expression being shifted. The result of bitwise shifts on such values is unpredictable.
• If the right operand has the value 0, the result is the value of the left operand.
• The << operator fills vacated bits with zeros.

Left Shift Operator (<<)

X=8
Shift left for multiplication purpose
X<<2
x = 0000 0000 0000 Y = n X 2s
1000 where n – number, s – no.
x<<2 = 000 0000 0000
10000
of shifts
00 0000 0000

Right Shift Operator (>>)

Shift left for multiplication purpose


X=8
X>>2 Y = n / 2s
x = 0000 0000 0000 where n – number, s – no.
1000 of shifts
x>>2 = 00000 0000 0000
100
000000 0000 0000

7
Decision Statements or Branching
The C language programs follow a sequential form of execution of statements. A C program is a set
of statement which is normally executed sequentially in the order in which they appear. Many times it is
required to alter the flow of the sequence of instructions. This happens when no option or no repetitions of
certain calculation are necessary. C language provides statements that can alter the flow of a sequence of
instructions. These statements are called control statements. These statements help to jump from one part of
the program to another. The control transfer may be conditional or unconditional.
C language possesses such decision - making capabilities by supporting the following statement
1. if statement
2. switch statement
3. conditional operator statement
4. goto statement
1. if statement (two – way branching)
The if statement is a powerful decision - making system statement and it used to control flow of execution of
statement. It is basically a two - way decision statement and in conjunction with an expression. It allows the
computer to evaluate the expression first and then, depending on whether the value of the expression
(relation or condition) is 'true' ( or non-zero) or 'false' (zero), it transfers the control to a particular statement.
Syntax:
if (condition)
{
/* True block */
Statements;
}
else
{
/* False block */
Statements;
}
The if statement may be implemented in a different form s depending on the complexity of condition to be
tested. The different forms are:
1. Simple if statement
if (condition)
{
/* True block */
Statements;
}
2. if ......else statement
if (condition)
{
/* True block */
Statements;
}
else
{
/* False block */
Statements;
}
3. Nested if ......else statement
if (condition)
{
if(condition)
{
if(condition)
{
Statements;
}
}
}
8
4. else if statement (else – if ladder )
if (condition)
{
/* True block */
Statements;
}
else
if (condition)
{
/* True block */
Statements;
}
else
if (condition)
{
/* True block */
Statements;
}

These statements are popularly known as decision - making statements. Since these statements 'control' the
flow of execution , they are also known as control statements.

2. switch statement (Multi – way Branching)


The switch-case statement is a multi-way decision statement. Unlike the multiple decision statement that can
be created using if-else, the switch statement evaluates the conditional expression and tests it against
numerous constant values. The branch corresponding to the value that the expression matches is taken
during execution.
The value of the expressions in a switch-case statement must be an ordinal constant type i.e. integer, char,
short, long, etc. Float and double are not allowed.

Syntax:
switch( expression )
{
case constant-expression1:
statements1;
break;
case constant-expression2:
statements2;
break;
case constant-expression3:
statements3;
break;
default :
statements4;
}
1. Control passes to the statement whose case constant-expression matches the value of switch
( expression ). The switch statement can include any number of case instances, but no two case
constants within the same switch statement can have the same value. Execution of the statement
body begins at the selected statement and proceeds until the end of the body or until a break
statement transfers control out of the body.
2. You can use the break statement to end processing of a particular case within the switch statement
and to branch to the end of the switch statement. Without break, the program continues to the next
case, executing the statements until a break or the end of the statement is reached. In some situations,
this continuation may be desirable.
3. The default statement is executed if no case constant-expression is equal to the value of switch
( expression ). If the default statement is omitted, and no case match is found, none of the statements
in the switch body are executed. There can be at most one default statement. The default statement

9
need not come at the end; it can appear anywhere in the body of the switch statement. A case or
default label can only appear inside a switch statement.
4. The type of switch expression and case constant-expression must be integral. The value of each case
constant-expression must be unique within the statement body.
5. The case and default labels of the switch statement body are significant only in the initial test that
determines where execution starts in the statement body.
6. Switch statements can be nested. Any static variables are initialized before executing into any switch
statements.

Loops or Repetetions or Iterations


Loops are used to repeat a block of statements. To perform a block of code repeatedly, use loops.
During looping a set of statements are executed until some conditions for termination of the loop is
encountered. A program loop therefore consists of two segments one known as body of the loop and other is
the control statement. The control statement tests certain conditions and then directs the repeated execution
of the statements contained in the body of the loop.
Loops are classified into two types based on condition checking.
1. Entry controlled loops or Pre Test loops: In this loops, the condition will be checked before entering
in to the body of loop. If the condition is true or success, the block of statements will be performed.
If not, the loop will terminate. While and for loops are the example for this type of loops.
2. Exit controlled loops or Post Test loops: In this loops, the condition will be checked after executing
the statements of loop. If the condition is true or success, the loop will repeat again. If not, the loop
will terminate. The statements of the loop executed at least once even condition failed in the
beginning. Do-while is the example for this type of loops.
Loops are again classified into two types.
1. Event controlled loops: In this loops, the loop repeats based on user choice. We can not count the
loop iterations.
2. Counter controlled loops: In this loops, the loop repeats based on counter. We can count the loop
iterations exactly.
In looping process in general would include the following four steps
1. Setting and initialization of a counter
2. Exertion of the statements in the loop
3. Test for a specified conditions for the execution of the loop
4. Incrementing / decrementing the counter or modifying the counter
The test may be either to determine whether the loop has repeated the specified number of times or to
determine whether the particular condition has been met.
Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks
in programming -- many programs or websites that produce extremely complex output (such as a message
board) are really only executing a single task many times. (They may be executing a small number of tasks,
but in principle, to produce a list of messages only requires repeating the operation of reading in some data
and displaying it.) Now, think about what this means: a loop lets you write a very simple statement to
produce a significantly greater result simply by repetition.

break
Loops performs a set of operations repeatedly until the control variable fails to satisfy the test condition. The
number of times a loop is repeated is decided in advance and the test condition is written to achieve this.
Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to leave the loop
as soon as a certain condition occurs. ‘C’ permits a jump from one statement to another within a loop or out
of a loop.

10
To exit/jump out of a loop can be accomplished by the break statement based on condition. We can
use a break statement to terminate a loop or a switch. Use break statement within a if condition, and end
with semicolon(;)
EX: 1) Write a program, find the given number is prime or not.

Continue
The continue statement does not terminate the loop but simply transfers to the testing expression in loops.
Continue statement causes the loop to be continued with the next iteration after skipping any statements in
between. The continue statement tells the compiler, “SKIP THE FOLLOWING STATEMENTS AND,
CONTINUE WITH NEXT ITERATION”. Use continue statement within if condition.

exit()
exit() is a function. It is used to quit the program. We can use exit() function in a if condition. The ‘C’
compiler will exit the program after executes the exit() function.

goto Statement
A goto statement causes your program to unconditionally transfer control to the statement associated with
this label specified on the goto statement.
Syntax: goto label_identifier;
Because, the goto statement can interface with the normal sequence of processing, it makes a
program more difficult to read and maintain. Often, a break statement, a continue statement or a function
call can eliminate the need for a goto statement.
Often active block is exited using a goto statement, any local variables are destroyed when control is
transferred from that block.
You can not use a goto statement to jump over initialization.
A goto may be used to exiting a loop from within a deeply nested loop.

1) The goto required a label in order to identify the place where the branch is to be made.
2) A label is any variable name, and must be followed by a colon(:) except that a label is not declared.
3) The label is placed immediately before the statement where the control is to be transferred.
4) The label can be anywhere in the program either before or after the goto statement.

Advantages:
1) goto statement can transfer the control to any place in a program unconditionally.
2) Exiting the program from deeply nested loops.

Dis – advantage: Program logic complicated, unstructured and unreadable program code.

11

Anda mungkin juga menyukai