You are on page 1of 64

C PROGRAMMING: UNIT I

Table of Contents
PART1: C BASICS ..................................................................................................................... 5
INTRODUCTION TO C ......................................................................................................... 5
WHAT IS C?........................................................................................................................ 5
What is a programming language? ...................................................................................... 5
Objective for developing programming languages .............................................................. 5
Why study programming languages .................................................................................... 5
PL can be divided into 2 categories ..................................................................................... 6
HISTORY OF C .................................................................................................................. 6
SERIES OF EVOLUTION .............................................................................................. 6
SALIENT FEATURES OF C .............................................................................................. 7
BUILDING BLOCKS OF C LANGUAGE / ELEMENTS OF C LANGUAGE ....................... 7
1. C character set .................................................................................................................. 7
2. TOKENS .......................................................................................................................... 9
3. IDENTIFIERS .................................................................................................................. 9
4. KEYWORDS ................................................................................................................... 9
5. Datatypes ........................................................................................................................ 10
Fundamental data types...................................................................................................... 10
6. Constants ........................................................................................................................ 10
Integer constants ................................................................................................................ 11
Real constants in C............................................................................................................. 11
Character constants ............................................................................................................ 11
String constants .................................................................................................................. 11
7. Variables......................................................................................................................... 11
Rules for naming C variable: ............................................................................................. 12
STARTING WITH C PROGRAM ........................................................................................... 12
Declaring a variable ............................................................................................................... 12
Prepared By:Ms.Ankita Page 1
C PROGRAMMING: UNIT I

Initializing variables .............................................................................................................. 12


Structure of a C program ....................................................................................................... 14
P1 SIMPLE C PROGRAM ................................................................................................... 15
P2 PROGRAM TO ADD 2 NUMBERS ................................................................... 17
SYMBOLIC CONSTANTS ...................................................................................................... 17
ADVANTAGES OF USING SYMBOLIC CONSTANTS .................................................. 18
P3 SYMBOLIC CONSTANTS ................................................................................ 18
COMPOUND STATEMENT / BLOCK................................................................................... 19
EXPRESSION AND OPERATORS ......................................................................................... 19
OPERATORS............................................................................................................................ 20
Arithmetic Operators ............................................................................................................. 20
Conversion ............................................................................................................................. 21
Implicit conversion ............................................................................................................ 23
Explicit conversion ............................................................................................................ 23
Output: ............................................................................................................................... 23
Unary operators: Increment, Decrement and sizeof Operators ............................................. 24
Relational operators ............................................................................................................... 25
Program to find relationship between 2 numbers. ............................................................. 26
Logical operators ................................................................................................................... 26
Assignment operator .............................................................................................................. 28
Conditional Operator .......................................................................................................... 28
Bitwise Operators ................................................................................................................ 30
Bitwise AND operator in C programming. ........................................................................ 30
Bitwise OR operator in C ................................................................................................... 31
C Programming Bitwise XOR(exclusive OR) operator..................................................... 32
Bitwise compliment operator ............................................................................................. 32
Shift Operator ........................................................................................................................ 33
Bitwise Right Shift Operator in C ...................................................................................... 33
Quick Overview of Right Shift Operator ....................................................................... 33
Syntax :........................................................................................................................... 33
Prepared By:Ms.Ankita Page 2
C PROGRAMMING: UNIT I

Example : Bitwise Operator [Right Shift Operator]....................................................... 34


Output :........................................................................................................................... 34
Bitwise Left Shift Operator in C ........................................................................................ 34
Quick Overview of Left Shift Operator ......................................................................... 34
Syntax : Bitwise Left Shift Operator .............................................................................. 35
Example : Bitwise Operator [Left Shift Operator] ......................................................... 35
Output :........................................................................................................................... 35
Explanation of Left Shift Binary Operator :................................................................... 35
Observations and Conclusion : ....................................................................................... 36
Part 2: C constructs ................................................................................................................... 37
DECISION CONTROL STRUCTURES .............................................................................. 38
1. The if- statement ....................................................................................................... 38
Forms of if-statement ..................................................................................................... 38
1. SIMPLE IF STATEMENT .............................................................................. 38
Syntax ................................................................................................................... 38
2. C if...else statement ............................................................................................... 41
Syntax of if...else .................................................................................................. 41
Nested if...else statement (if...elseif....else Statement) ............................................. 43
Syntax of nested if...else statement. ...................................................................... 43
2. Switch statements...................................................................................................... 46
Syntax of switch...case ................................................................................................... 46
LOOPING STATEMENTS ................................................................................................... 51
1. FOR LOOP ............................................................................................................... 53
2. WHILE LOOP .......................................................................................................... 58
3. Do-while ................................................................................................................... 59
JUMPING STATEMENTS ................................................................................................... 60

Prepared By:Ms.Ankita Page 3


C PROGRAMMING: UNIT I

C basics: C character set, Identifiers and keywords, Data types, constants, variables and arrays,
declarations, expressions statements, symbolic constants, compound statements, arithmetic
operators, unary operators, relational and logical operators, assignment operators, conditional
operators, bit operators.

C constructs: If statement, if….else statement, if…..else if….else statement, while statement,


do….while statement, for statement, switch statement, nested control statement, break operator,
continue operator, comma operator, goto statement.

Prepared By:Ms.Ankita Page 4


C PROGRAMMING: UNIT I

PART1: C BASICS

INTRODUCTION TO C

WHAT IS C?
C is a programming language.

What is a programming language?


A programming language is a formal constructed language [constructed language refers to as an
artificial or invented language] designed to communicate instructions to a machine, particularly
a computer.

Objective for developing programming languages


Computer programming languages are developed with the primary objective of facilitating a
large number of people to use computers without the need for them to know in detail the internal
structure of the computer.

Why study programming languages


 To improve your use of existing programming languages

 To increase your vocabulary of useful programming constructs

 To allow a better choice of programming language

 To make it easier to learn a new language

 To make it easier to design a new language

flowchart Prog lang.


algorithm

Algorithm: series of steps arranged in a logical sequence

Flowchart: pictorial representation of sequence of instructions given to the computer.

ALGORITHMS ARE EXPRESSED USING A PROGRAMMING LANGUAGE

Prepared By:Ms.Ankita Page 5


C PROGRAMMING: UNIT I

PL can be divided into 2 categories


1. Machine dependent or low level language
2. Machine independent or high level language

1. MACHINE DEPENDENT
a. The language whose design is governed by the circuitry and the structure of the
machine is known as machine language.
b. This language is difficult to learn and use.
c. It is specific to a given computer and is different for different computers i.e these
languages are machine dependent.

Example assembly language

2. High level language or machine independent


a. These languages were developed to allow application programs to follow a
precise set of rules.
b. They are developed to allow application programs to be run on a variety of
computers.

Example: FORTRAN, BASIC, PASCAL, C, C++, JAVA

HISTORY OF C
C is a programming language developed at AT & T‟s Bell laboratory of YSA in 1972. It was
designed and written by Denis Ritchie.

An international committee was set up to develop a general purpose language.

SERIES OF EVOLUTION

1. ALGOL 60 was invented


a. It was too abstract and too general
2. CPL – combined programming language
a. To improve ALGOL 60 , CPL was invented at Cambridge university.
b. It was too difficult to learn and was too complex.
3. BCPL – basic CPL
a. It was much less powerful and too specific.
4. B
a. Simplified version of BCPL
b. Developed by ken Thompson
Prepared By:Ms.Ankita Page 6
C PROGRAMMING: UNIT I

c. Also too specific


5. Finally, Ritchie inherited the feature of B and BCPL and added some features on his own
and developed a language called C.

C proved to be compact and consistent.

BCPL -------------- B------------- C

SALIENT FEATURES OF C

BUILDING BLOCKS OF C LANGUAGE / ELEMENTS OF C LANGUAGE

1. C character set
A C program is a sequence of characters. When these characters are submitted to the computer,
they are interpreted in various contexts as characters, identifiers, constants and statements.

The characters used in a C program, belong to the ASCII set.[ ASCII = American Standard Code
for Information Interchange] .

Characters are grouped into the foll. Categories

1. Letters
2. Digits
3. White space characters
4. Special characters
5. Delimiters

Prepared By:Ms.Ankita Page 7


C PROGRAMMING: UNIT I

1. Letters
a. Upper case: A-Z
b. Lower case: a-z
2. Digits : 0-9
3. White space characters:
a. Blank space
b. Horizontal tab
c. Carriage return
d. Form feed
e. New line
4. Special characters/ symbols:

5. Delimiters: A delimiter is a unique character or series of characters that indicates the


beginning or end of a specific statement, string or function body set.

Delimiters Use
:(Colon) Useful for label
;(Semicolon) Terminates statement.
# (Hash) Preprocessor directive.
,(comma) Variable Separator.
{ } (Curly Brace) Scope of statement.
[] (Square bracket) Used for array declaration.

Prepared By:Ms.Ankita Page 8


C PROGRAMMING: UNIT I

2. TOKENS
A token is the smallest entity that can have a meaning in itself in C.

Eg. Float const pie=2.14;

The above statement consists of 6 tokens, that are “float”, “const”,”pie”,”=”,”2.14”,”;”

3. IDENTIFIERS
An identifier is basically a name in a program. Identifiers can be used to denote variables and
functions. In C, an identifier is composed of sequence of characters, where each character can be
a letter, a digit or an underscore but it cannot start with a digit.

Examples

VALID IDENTIFIER NAME INVALID


Myfile 10file
Roll_no Pin.code
Date_of_birth My-file
_abc Last name
File10
N1ton10
aBcD

4. KEYWORDS
Keyword or reserved word is word whose meaning is well defined for compiler we can use it in
our program but we can not alter its meaning.
e.g. int, float, do, while etc.
keywords are always used in lower case, although uppercase of same can be used as identifier.
There are such 32 keywords.

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

Prepared By:Ms.Ankita Page 9


C PROGRAMMING: UNIT I

auto double int struct


do if static while

5. Datatypes
Data types are used to define a variable before its use. The definition of a variable will assign
storage for the variable and define the type of data that will be held in the location.

Types of data types:

1. Fundamental Data Types


o Integer types
o Floating Type
o Character types
2. Derived Data Types
o Arrays
o Pointers
o Structures
o Enumeration

Fundamental data types

Format
S.No C Data types storage Size in bytes Range
specifier
1 char 1 –128 to 127 %c
2 int 2 –32,768 to 32,767 %d
3 float 4 -3.4E38 to +3.4E38 %f
4 double 8 1.7E -308 to 1.7 E +308 %lf
%Lf/
5 long double 10 1.7E -308 to 1.7 E +308
%lf
6 long int 4 –2,147,483,647 to 2,147,483,647 %ld
8 unsigned int 2 0 to 65,535 %u

6. Constants
A constant is an entity that doesn‟t change.

 Integer constants
 Real or Floating point constants

Prepared By:Ms.Ankita Page 10


C PROGRAMMING: UNIT I

 Character constants
 String constants

Integer constants

 An integer constant must have at least one digit.


 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign precedes an integer constant, it is assumed to be positive.
 The allowable range for integer constants is -32768 to 32767.

Examples:- 125 , +7000 , -600 , -7005

Real constants in C

 A real constant must have at least one digit


 It must have a decimal point
 It could be either positive or negative
 If no sign precedes an integer constant, it is assumed to be positive.
 No commas or blanks are allowed within a real constant.

Examples:- +325.34 , 426.0 , -32.76 , -48.5792

Character constants

 A character constant is a single alphabet, a single digit or a single special symbol


enclosed within single quotes.
 The maximum length of a character constant is 1 character.

Example „A‟, „3‟, „&‟

String constants

 String constants are enclosed within double quotes.

Example : “aa”, “12”

7. Variables
It is an identifier whose value changes from time to time during program execution.

Prepared By:Ms.Ankita Page 11


C PROGRAMMING: UNIT I

 C variable is a named location in a memory where a program can manipulate the data.
This location is used to hold the value of the variable.
 The value of the C variable may get change in the program.
 C variable might be belonging to any of the data type like int, float, char etc.

All variable shave 3 essential attributes:

a. Name
b. Value
c. Memory, where the value gets stored

Rules for naming C variable:

1. Variable name must begin with letter or underscore.


2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5.

Examples: sum, height, _value

In C the length of a variable name is unlimited (although the first 31 characters must be unique).

STARTING WITH C PROGRAM


Writing a C program consists of 3 major parts:

1. Declaring variables
2. Initializing variables
3. Structure of a C program

Declaring a variable
Declaration means assigning a name to memory location where data can be stored.

Syntax :

Datatype varname

int x;

float y;

Initializing variables
When variables are to be created, then they can be initialized in 2ways:

Prepared By:Ms.Ankita Page 12


C PROGRAMMING: UNIT I

a. Within a type declaration i.e at the time of declaring a variable

Eg. int a=10;

float b=12.4;

char c =‟a‟;

b. Using assignment statement i.e values are assigned after declarations are made.

Example
a. int a;

a=10

b. float b;

b=0.5;

What is the difference between declaring a variable and defining a variable?

Declaration of a variable in C hints the compiler about the type and size of the variable
in compile time. Similarly, declaration of a function hints about type and size of function
parameters. No space is reserved in memory for any variable in case of declaration.

Example: int a;

Here variable 'a' is declared of data type 'int'

Defining a variable means declaring it and also allocating space to hold it.

We can say "Definition = Declaration + Space reservation".

Example: int a = 10;

Here variable "a" is described as an int to the compiler and memory is allocated to hold
value 10

Prepared By:Ms.Ankita Page 13


C PROGRAMMING: UNIT I

Structure of a C program

Preprocessor directives
Global data declarations
main()
{
Declaration part;
Program statements;
}

One function is always present in C language i.e main().

main() is the function that is called up when program execution begins.

Prepared By:Ms.Ankita Page 14


C PROGRAMMING: UNIT I

P1 SIMPLE C PROGRAM

1. #include<stdio.h> //6 preprocessor directives


2. main()
3. {
4. printf(“Hello World \n 8 ”);7
5. }

1. #include<stdio.h>.

#include<stdio.h> tells the compiler to include this header file for compilation. To access the
standard functions that comes with your compiler, you need to include a header with the #include
directive.

2. main()
It is the main program (that is why the name „main‟) that is always executed first. It is always
written (expressed) in lower case.
3. {

These curly braces are equivalent to stating "block begin“and "block end ". The code in between
is called a “block”.

4. printf()
The actual print statement.
Text to be printed is always enclosed in double quotes.
5. }
These curly braces are equivalent to stating "block begin“and "block end ". The code in between
is called a “block”.

6. // Comments
They may appear anywhere within a program.
2 types of comments

i. // single line comment


ii. /*…*/ multiple lines comment

7. ; semi colon
Every statement within a function ends with a terminator i.e. semi colon.

8. \n new line
\n at the end of text tells the program / compiler to print a new line as part of the output.

Prepared By:Ms.Ankita Page 15


C PROGRAMMING: UNIT I

Why use comments?


1. Helps in explaining difficult sections of code.
2. Describes the program, author, date, changes, revisions etc.

Prepared By:Ms.Ankita Page 16


C PROGRAMMING: UNIT I

P2 PROGRAM TO ADD 2 NUMBERS

#include<stdio.h>

void main()
{
int n1, n2, sum; // variable declaration

printf("Enter two numbers to add\n");


scanf("%d%d",&n1,&n2);

sum = n1 + n2;

printf("addition of entered numbers = %d\n",sum);// to


display the output

n1.n2,sum ---------------variables
int -------------------------datatype (integer)
n1 and n2 will accept integer values
printf---------------------to ask the user to enter values of n1 and n2.
scanf---------------------to intake the values into the program provided by the user.
%d----------------------format specifier
Indicates what type of value is to be printed

In last line, sum is not displayed in double quotes because we want its value to be printed.

SYMBOLIC CONSTANTS
It is a name that substitutes for a sequence of characters or a numeric constant or a character
constant or a string constant.

When program is compiled each occurrence of a symbolic constant is replaced by its


corresponding character sequence.

Prepared By:Ms.Ankita Page 17


C PROGRAMMING: UNIT I

SYNTAX

#define symbolic_name text or value

symbolic_name in uppercase

text implies value or text

examples

#define MAX 100

#define TRUE 1

#define FALSE 0

#define SIZE 12

ADVANTAGES OF USING SYMBOLIC CONSTANTS

1. They can be used to assign names to values.


2. Replacement of values has to be done at one place and wherever the
name appears in the text, it gets the value by execution of the
preprocessor. This saves time.

If the symbolic constant appears 20 times, then it needs to be changed at 1 place only.

P3 SYMBOLIC CONSTANTS

#include <stdio.h>
#define TAX_RATE 0.10

void main()
{
float balance,tax;
balance=72.10;
tax=balance*TAX_RATE;
printf( “calculated tax= %f”, tax);
}

Prepared By:Ms.Ankita Page 18


C PROGRAMMING: UNIT I

COMPOUND STATEMENT / BLOCK


The compound statement or a block is a group of statements enclosed by braces, namely { and }.

The individual statements enclosed by braces are executed in the order in which they appear.

General form:

Statement 1;
Statement 2;
.
.
.
Statement n;
}

No semicolon is to be used after closing braces.

For example

{
scanf (“%f %f”, &a, &b);
c=a+b;
printf (“a=%f,b=%f,c=%f”,a,b,c);
}

is a compound statement .

A semicolon separates one statement from the next.

EXPRESSION AND OPERATORS


An expression is a sequence of operators and operands.

Operator – performs an operation on one or more operand.

Operand – sub-expression on which operator acts.

For example

a+b, where

Prepared By:Ms.Ankita Page 19


C PROGRAMMING: UNIT I

a & b are operands

+ is an operator

OPERATORS
C language supports following type of operators.

1. Arithmetic Operators( +, - , *, / , %)

2. Unary operators : Increment, Decrement and sizeof Operators

3. Assignment Operators (=)

4. Relational Operators (>, <,>=. <=,!=,==)

5. Logical Operators (!, &&, ||)

6. Conditional Operators ( ? : )

7. Bitwise Operators

8. Special Operators (comma)

Arithmetic Operators
Operator Meaning of Operator

+ addition or unary plus

- subtraction or unary minus

* multiplication

/ division

% remainder after division( modulo division)

Prepared By:Ms.Ankita Page 20


C PROGRAMMING: UNIT I

Example of working of arithmetic operators

/* Program to demonstrate the working of arithmetic operators in C. */

#include <stdio.h>
void main(){
int a=9,b=4,c;
c=a+b;
printf("a+b=%d\n",c);
c=a-b;
printf("a-b=%d\n",c);
c=a*b;
printf("a*b=%d\n",c);
c=a/b;
printf("a/b=%d\n",c);
c=a%b;
printf("Remainder when a divided by b=%d\n",c);
getch();
}
a+b=13
a-b=5
a*b=36
a/b=2
Remainder when a divided by b=1

Explanation

Here, the operators +, - and * performed normally as you expected. In normal calculation, 9/4
equals to 2.25. But, the output is 2 in this program. It is because, a and b are both integers. So,
the output is also integer and the compiler neglects the term after decimal point and shows
answer 2 instead of 2.25. And, finally a%b is 1,i.e. ,when a=9 is divided by b=4, remainder is 1.

Conversion
Operands in an arithmetic expression can be of integer, float, double type. So conversion needs
to be done.

Conversion can be done in 2 ways

Prepared By:Ms.Ankita Page 21


C PROGRAMMING: UNIT I

In some cases, the value of the expression is promoted or demoted depending on the type of
variable on LHS of assignment operator (=).

Suppose a=5.0, b=2.0, c=5 and d=2


In C programming, if

Operand1 Operand 2 result


Int Int Int
Int Float Float
Float Float Float
Float Double Double

a/b=2.5
a/d=2.5
c/b=2.5
c/d=2

Note: % operator can only be used with integers.

Prepared By:Ms.Ankita Page 22


C PROGRAMMING: UNIT I

Implicit conversion
#include<stdio.h>

#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
printf(“implicit value is %d”,p);
getch();
}

Here, the value of “a” has been promoted from int to double and we have not specified any type-
casting operator. This is known as a standard conversion.

 Typecasting concept in C language is used to modify a variable from one date type to
another data type. New data type should be mentioned before the variable name or value
in brackets which to be typecast.

Explicit conversion
C type casting example program:

 In the below C program, 7/5 alone will produce integer value as 1.


 So, type cast is done before division to retain float value (1.4).

#include <stdio.h>
void main ()
{
float x;
x = (float) 7/5;
printf("%f",x);
getch();
}

Output:
1.400000

Note:

 It is best practice to convert lower data type to higher data type to avoid data loss.

Prepared By:Ms.Ankita Page 23


C PROGRAMMING: UNIT I

 Data will be truncated when higher data type is converted to lower. For example, if float
is converted to int, data which is present after decimal point will be lost.

http://www.programiz.com/c-programming/c-operators

Unary operators: Increment, Decrement and sizeof Operators

In C, ++ and -- are called increment and decrement operators respectively. Both of these
operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts
1 to operand respectively. For example:

Let a=5 and b=10

a++; //a becomes 6

a--; //a becomes 5

Expression Explanation
++a First increment a by 1, then use the new value of a.
a++ First use given value of a, then increment a by 1.
--b First decrement b by 1, then use the new value of b.
b-- First use given value of b, then decrement b by 1.

Precedence of these operators is from

Right to left

For example

int a=2,b=3,c;

c=++a – b--;

printf(“a=%d, b=%d,c=%d \n”,a,b,c);

Output: a=3, b=2, c=0

Explanation

Since the precedence of these operators is from right to left, then

1. First b is evaluated. Since, it is a post decrement operator, current value of b will be used
in the expression i.e. 3 and then b will be decremented by 1.

Prepared By:Ms.Ankita Page 24


C PROGRAMMING: UNIT I

2. Then,a preincrement is used with „a‟. So, first „a‟ is incremented to 3 and then its value
will be used.
3. After this b=3
a=3
c=a-b
= 3-3
=0

sizeof Operator

This operator returns the sizeof its operand, in bytes.


The sizeof operator always precedes its operand.
For example sizeof(int) = 2 bytes
sizeof(char)= 1 bytes
unary operators have higher precedence than arithmetic operators.

Relational operators

Using relational operators we can compare two variables in the program.

Operator Meaning of Operator Example Associativity

== Equal to 5==3 returns false (0) Left to right

> Greater than 5>3 returns true (1) Left to right

< Less than 5<3 returns false (0) Left to right

!= Not equal to 5!=3 returns true(1) Left to right

Greater than or Left to right


>= 5>=3 returns true (1)
equal to

Less than or equal Left to right


<= 5<=3 return false (0)
to

Prepared By:Ms.Ankita Page 25


C PROGRAMMING: UNIT I

Program to find relationship between 2 numbers.


#include <stdio.h>

main()

int a,b;

printf(“please enter 2 integers:”);

scanf (“%d %d “, &a, &b);

if (a<=b)

printf(“%d <= %d \n”,a,b)

else

printf (“%d > %d \n”,a ,b);

Output

Please enter 2 integers: 10 12

10 <= 12

Logical operators
These type of operators are used to evaluate expressions which may be true or false.

Expressions which involve logical operations are evaluated and found to be one of two values :
true (1) or false (0).

C provides logical operators that may be used to form more complex conditions by combining
simple conditions.

Prepared By:Ms.Ankita Page 26


C PROGRAMMING: UNIT I

Meaning of
Operator Example
Operator

Logial If c=5 and d=2 then,((c==5) &&


&&
AND (d>5)) returns false.

Logical If c=5 and d=2


||
OR then, ((c==5) || (d>5)) returns true.

Logical
! If c=5 then, !(c==5) returns false.
NOT

Explanation

For expression, ((c==5) && (d>5)) to be true, both c==5 and d>5 should be true but, (d>5) is
false in the given example. So, the expression is false. For expression ((c==5) || (d>5)) to be true,
either the expression should be true. Since, (c==5) is true. So, the expression is true. Since,
expression (c==5) is true, !(c==5) is false.

OR operator

Prepared By:Ms.Ankita Page 27


C PROGRAMMING: UNIT I

Assignment operator

The most common assignment operator is =. This operator assigns the value in right side
to the left side. For example:

var=5 //5 is assigned to var

a=c; //value of c is assigned to a

5=c; // Error! 5 is a constant.

Operator Example Same as

= a=b a=b

+= a+=b a=a+b

-= a-=b a=a-b

*= a*=b a=a*b

/= a/=b a=a/b

%= a%=b a=a%b

Conditional Operator
Conditional operator takes three operands and consists of two symbols ? and : . Conditional
operators are used for decision making in C.

This operator is also known as ternary operator as it takes 3 operands.

Prepared By:Ms.Ankita Page 28


C PROGRAMMING: UNIT I

1st operand: condition

2nd operand: represents the value of the entire conditional expression if the condition is true.

3rd operand: represents the value of the entire conditional expression if the condition is false.

Syntax (condition)? Expression 1 : expression 2 ;

If condition is true, expression1 is evaluated otherwise expression2 is evaluated.

For example:

1. c=(c>0)?10:-10;

If c is greater than 0, value of c will be 10 but, if c is less than 0, value of c will be -10

2.

#include <stdio.h>

void main(){

char feb;
int days;
printf("Enter l if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days=(feb=='l')?29:28;
/*If test condition (feb=='l') is true, days will be equal to 29. */
/*If test condition (feb=='l') is false, days will be equal to 28. */
printf("Number of days in February = %d",days);
getch();
}
Output

Enter l if the year is leap year otherwise enter n: l

Number of days in February = 29

Prepared By:Ms.Ankita Page 29


C PROGRAMMING: UNIT I

Bitwise Operators

Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

~ Bitwise complement

<< Shift left

>> Shift right

Bitwise AND operator in C programming.


The output of logical AND is 1 if both the corresponding bits of operand is 1. If either of bit is 0
or both bits are 0, the output will be 0. It is a binary operator(works on two operands) and
indicated in C programming by & symbol. Let us suppose the bitwise AND operation of two
integers 12 and 25.

12 = 00001100 (In Binary)

25 = 00011001 (In Binary)

Bit Operation of 12 and 25

00001100

& 00011001

________

00001000 = 8 (In decimal)

As, every bitwise operator works on each bit of data. The corresponding bits of two inputs are
check and if both bits are 1 then only the output will be 1. In this case, both bits are 1 at only one

Prepared By:Ms.Ankita Page 30


C PROGRAMMING: UNIT I

position,i.e, fourth position from the right, hence the output bit of that position is 1 and all other
bits are 0.

#include <stdio.h>

int main()

int a=12,b=39;

printf("Output=%d",a&b);

return 0;

Output

Output=4

Bitwise OR operator in C

The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1. In C
Programming, bitwise OR operator is denoted by |.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)

#include <stdio.h>
int main()
{
int a=12,b=25;
printf("Output=%d",a|b);
return 0;

Prepared By:Ms.Ankita Page 31


C PROGRAMMING: UNIT I

Output

Output=29

C Programming Bitwise XOR(exclusive OR) operator

The output of bitwise XOR operator is 1 if the corresponding bits of two operators are
opposite(i.e., To get corresponding output bit 1; if corresponding bit of first operand is 0
then, corresponding bit of second operand should be 1 and vice -versa.). It is denoted by
^.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
| 00011001
________
00010101 = 21 (In decimal)

#include <stdio.h>
int main()
{
int a=12,b=25;
printf("Output=%d",a^b);
return 0;
}
Output=21

Bitwise compliment operator

Bitwise compliment operator is an unary operator(works on one operand only). It


changes the corresponding bit of the operand to opposite bit,i.e., 0 to 1 and 1 to 0. It is
denoted by ~.

35=00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)

Prepared By:Ms.Ankita Page 32


C PROGRAMMING: UNIT I

Shift Operator

There are two shift operators in C programming: Right shift operator and Left shift
operator.

Bitwise Right Shift Operator in C

1. It is denoted by >>

2. Bit Pattern of the data can be shifted by specified number of Positions


to Right

3. When Data is Shifted Right , leading zero’s are filled with zero.

4. Right shift Operator is Binary Operator [Bi – two]

5. Binary means , Operator that require two arguments

Quick Overview of Right Shift Operator


Original Number A 0000 0000 0011 1100

Right Shift by 2 0000 0000 0000 1111

Leading 2 Blanks Replaced by 0 ,Shown in RED

Direction of Movement of Data Right ========>>>>>>

Syntax :

[variable]>>[number of places]

Prepared By:Ms.Ankita Page 33


C PROGRAMMING: UNIT I

Example : Bitwise Operator [Right Shift Operator]

#include<stdio.h>

int main()
{
int a = 60;

printf("\nNumber is Shifted By 1 Bit : %d",a >> 1);


printf("\nNumber is Shifted By 2 Bits : %d",a >> 2);
printf("\nNumber is Shifted By 3 Bits : %d",a >> 3);

return(0);
}
Output :
Number is Shifted By 1 Bit : 30
Number is Shifted By 2 Bits : 15
Number is Shifted By 3 Bits : 7

Bitwise Left Shift Operator in C


1. It is denoted by <<

2. Bit Pattern of the data can be shifted by specified number of Positions


to Left

3. When Data is Shifted Left , trailing zero’s are filled with zero.

4. Left shift Operator is Binary Operator [Bi – two]

5. Binary means , Operator that require two arguments

Quick Overview of Left Shift Operator


Original Number A 0000 0000 0011 1100

Left Shift 0000 0000 1111 0000

Trailing Zero’s
Replaced by 0

Prepared By:Ms.Ankita Page 34


C PROGRAMMING: UNIT I

(Shown in RED)

Direction of Movement of Data <<<<<=======Left

Syntax : Bitwise Left Shift Operator

[variable]<<[number of places]

Example : Bitwise Operator [Left Shift Operator]


#include<stdio.h>

int main()
{
int a = 60;

printf("\nNumber is Shifted By 1 Bit : %d",a << 1);


printf("\nNumber is Shifted By 2 Bits : %d",a << 2);
printf("\nNumber is Shifted By 3 Bits : %d",a << 3);

return(0);
}
Output :
Number is Shifted By 1 Bit : 120
Number is Shifted By 2 Bits : 240
Number is Shifted By 3 Bits : 480

Explanation of Left Shift Binary Operator :

We know the binary representation of the 60 is as below –

0000 0000 0011 1100

Now after shifting all the bits to left towards MSB we will get following bit pattern
0000 0000 0011 1100 = 60

Prepared By:Ms.Ankita Page 35


C PROGRAMMING: UNIT I

<< 1
-------------------
0000 0000 0111 1000 = 120

Observations and Conclusion :


Shfting Binary 1 to Left By ‘X’ Bits Decimal Value Converted Value

0 Bit 2^0 1

1 Bit 2^1 2

2 Bits 2^2 4

3 Bits 2^3 8

4 Bits 2^4 16

5 Bits 2^5 32

6 Bits 2^6 64

7 Bits 2^7 128

8 Bits 2^8 256

Prepared By:Ms.Ankita Page 36


C PROGRAMMING: UNIT I

Part 2: C constructs

Control statements determine the “flow of control” in a program and enable us to specify the
order in which the various instructions in a program are to be executed by the computer.

There are 3 basic control statements:

1. Sequence instruction
2. Selection/ decision instruction
3. Repetition or loop instruction

1. Sequence instructions means executing one instruction after another, in the order in
which they occur in the source file.
2. Selection means executing different sections of code depending on a specific condition or
the value of a variable.

C provides 3 selection structures:

1. If
2. If…else
3. Switch

3. Repetition or looping means executing the same section of code more than once. A
section of code may either be executed a fixed number of times, or while some condition
is true.

C provides 3 looping structures:

1. While
2. Do…while
3. for

Prepared By:Ms.Ankita Page 37


C PROGRAMMING: UNIT I

DECISION CONTROL STRUCTURES

1. The if- statement


It is used to execute an instruction or sequence / block of instructions only if a condition is
fulfilled.

In if statements:

Firstly expression is evaluated

Then, depending on whether the value of expression is “true” or “false”, it transfers the control to
a particular statement or a group of statements.

Forms of if-statement
1. Simple If statement
2. If else
3. Nested if else

1. SIMPLE IF STATEMENT
It is used to execute an instruction or block of instructions only if a condition is fulfilled.

Syntax
if (test expression) {

statement/s to be executed if test expression is true;

The if statement checks whether the text expression inside parenthesis () is true or not. If the test
expression is true, statement/s inside the body of if statement is executed but if test is false,
statement/s inside body of if is ignored.

Prepared By:Ms.Ankita Page 38


C PROGRAMMING: UNIT I

Flowchart of if statement

Prepared By:Ms.Ankita Page 39


C PROGRAMMING: UNIT I

Example 1: C if statement
Write a C program to print the number entered by user only if the number entered is
negative.

#include <stdio.h>

int main(){

int num;

printf("Enter a number to check.\n");

scanf("%d",&num);

if(num<0) { /* checking whether number is less than 0 or not. */

printf("Number = %d\n",num);

/*If test condition is true, statement above will be executed, otherwise it will not be executed */

printf("The if statement in C programming is easy.");

return 0;

Output 1

Enter a number to check.

-2

Number = -2

The if statement in C programming is easy.

When user enters -2 then, the test expression (num<0) becomes true. Hence, Number = -2 is
displayed in the screen.

Output 2

Enter a number to check.

Prepared By:Ms.Ankita Page 40


C PROGRAMMING: UNIT I

The if statement in C programming is easy.

When the user enters 5 then, the test expression (num<0) becomes false. So, the statement/s
inside body of if is skipped and only the statement below it is executed.

2. C if...else statement
The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false.

Syntax of if...else
if (test expression) {

statements to be executed if test expression is true;

else {

statements to be executed if test expression is false;

Prepared By:Ms.Ankita Page 41


C PROGRAMMING: UNIT I

Flowchart of if...else statement

Example 2: C if...else statement

Write a C program to check whether a number entered by user is even or odd

#include <stdio.h>

void main(){

int num;

printf("Enter a number you want to check.\n");

scanf("%d",&num);

if((num%2)==0) //checking whether remainder is 0 or not.

printf("%d is even.",num);

Prepared By:Ms.Ankita Page 42


C PROGRAMMING: UNIT I

else

printf("%d is odd.",num);

getch();

Output 1

Enter a number you want to check.

25

25 is odd.

Output 2

Enter a number you want to check.

2 is even.

Nested if...else statement (if...elseif....else Statement)


The nested if...else statement is used when program requires more than one test expression.

Syntax of nested if...else statement.


if (test expression1){

statement/s to be executed if test expression1 is true;

else if(test expression2) {

statement/s to be executed if test expression1 is false and 2 is true;

else if (test expression 3) {

statement/s to be executed if text expression1 and 2 are false and 3 is true;

Prepared By:Ms.Ankita Page 43


C PROGRAMMING: UNIT I

else {

statements to be executed if all test expressions are false;

How nested if...else works?

The nested if...else statement has more than one test expression. If the first test expression is true,
it executes the code inside the braces{ } just below it. But if the first test expression is false, it
checks the second test expression. If the second test expression is true, it executes the statement/s
inside the braces{ } just below it. This process continues. If all the test expression are false,
code/s inside else is executed and the control of program jumps below the nested if...else

The ANSI standard specifies that 15 levels of nesting may be continued.

Prepared By:Ms.Ankita Page 44


C PROGRAMMING: UNIT I

Example 3: C nested if else statement


Write a C program to relate two integers entered by user using = or > or < sign.

#include <stdio.h>

void main(){
int numb1, numb2;
printf("Enter two integers to check\n");
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d = %d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d > %d",numb1,numb2);
else
printf("Result: %d > %d",numb2,numb1);
getch();
}
Output 1

Enter two integers to check.

Result: 5 > 3

Output 2

Enter two integers to check.

-4

-4

Result: -4 = -4

Practice questions
1. Get the number inputted from the user and check for positive / negative
2. Ask user to enter number. Find its remainder. Check if it is 5, them print the appropriate message.
3. Add 3 numbers and check answer lies between 100 -200.
4. Ask user to enter any year and check whether it‟s a leap year or not.
5. Get the number from year and check for even / odd.
Prepared By:Ms.Ankita Page 45
C PROGRAMMING: UNIT I

6. Ask user to enter any number and check whether it‟s greater than or less than or equal to zero,
and print appropriate message.
7. Check whether the candidate‟s age is greater than 17 or not. If yes, display message “ eligible for
voting”
8. Find smallest/ largest from 2 numbers.
9. Find smallest/ largest from 3 numbers.

2. Switch statements

Decision making are needed when, the program encounters the situation to choose a particular
statement among many statements. If a programmer has to choose one block of statement among
many alternatives, nested if...else can be used but, this makes programming logic complex. This
type of problem can be handled in C programming using switch statement.

Syntax of switch...case

switch (n) {

case constant1:

code/s to be executed if n equals to constant1;

break;

case constant2:

code/s to be executed if n equals to constant2;

break;

default:

code/s to be executed if n doesn't match to any cases;

Prepared By:Ms.Ankita Page 46


C PROGRAMMING: UNIT I

The value of n is either an integer or a character in above syntax. If the value of n matches
constant in case, the relevant codes are executed and control moves out of the switch statement.
If the n doesn't matches any of the constant in case, then the default codes are executed and
control moves out of switch statement.

Default case is executed if no other statement match is found. It can be placed at any place.

Break and continue keywords

break continue

1. break is a keyword used to terminate the loop 1. continue is a keyword used for skipping the
or exit from the block. The control jumps to next current iteration and go to next iteration of the
statement after the loop or block. loop .

Prepared By:Ms.Ankita Page 47


C PROGRAMMING: UNIT I

2.Syntax: 2.Syntax:
{ {
Statement 1; Statement 1;
Statement 2; continue;
Statement n; Statement 2;
break; }
}

3. break can be used with for, while, do- while, 3. This statement when occurs in a loop does not
and switch statements. When break is used in terminate it but skips the statements after this
nested loops i.e. within the inner most loop then continue statement. The control goes to the next
only the innermost loop is terminated. iteration. Continue can be used with for, while
and do-while.

4. Example: 4. Example:
i = 1, j = 0; i = 1, j = 0;
while(i<=5) while(i<=5)
{ {
i=i+1; i=i+1;
if(i== 2) if(i== 2) break;
j=j+1;
}
continue;
j=j+1;
}

Prepared By:Ms.Ankita Page 48


C PROGRAMMING: UNIT I

Example of switch...case statement

Write a program that asks user an arithmetic operator('+','-','*' or '/') and two operands and
perform the corresponding calculation on the operands.

/* C program to demonstrate the working of switch...case statement */

/* C Program to create a simple calculator for addition, subtraction,

multiplication and division */

# include <stdio.h>

int main() {

char op;

float num1,num2;

printf("Select an operator either + or - or * or / \n");

scanf("%c",&op);

printf("Enter two operands: ");

scanf("%f%f",&num1,&num2);

switch(op) {

case '+':

printf("%.1f + %.1f = %.1f",num1, num2, num1+num2);

break;

case '-':

printf("%.1f - %.1f = %.1f",num1, num2, num1-num2);

break;

case '*':

Prepared By:Ms.Ankita Page 49


C PROGRAMMING: UNIT I

printf("%.1f * %.1f = %.1f",num1, num2, num1*num2);

break;

case '/':

printf("%.1f / %.1f = %.1f",num1, num2, num1/num2);

break;

default:

/* If operator is other than +, -, * or /, error message is shown */

printf("Error! operator is not correct");

break;

return 0;

Output

Enter operator either + or - or * or /

Enter two operands: 2.3

4.5

2.3 * 4.5 = 10.3

The break statement at the end of each case cause switch statement to exit. If break statement is not used,
all statements below that case statement are also executed.

Practice questions:
1. Check whether the entered alphabet is vowel or not.
2. Display day of the week as per the number entered [1-7]

Prepared By:Ms.Ankita Page 50


C PROGRAMMING: UNIT I

LOOPING STATEMENTS

A loop is defined as a block of statements which are repeatedly executed for certain number of times.

1. WHILE
2. DO-WHILE
3. FOR

While For Do while


While loop keeps repeating an For loop is frequently used, usually Similar to while, but the condition is
action until an associated where the loop will be traversed a fixed checked after the loop body is
condition returns false. number of times. executed.

This is useful where the This ensures that the loop body is run
programmer does not know in at least once.
advance how many times the
loop will be traversed.

Syntax Syntax Syntax

Initialize loop counter; For(initialize; test condition; inc/dec) Do


While(condition) { {
{ Do this; This;
Do this; And this; And this;
And this; And this; And this;
}while( condition is true);
Increment/decrement loop }
counter;

}
Also known as entry controlled Also known as entry controlled loop Also known as exit controlled loop
loop

Prepared By:Ms.Ankita Page 51


C PROGRAMMING: UNIT I

Flowchart Flowchart Flowchart

void main() for(i = 2; i <= 6; i = i + 2) void main()


{ printf("%d\t", i + 1); {
int j; int j = -5; // initialization
j = -5; do
// while loop {
while(j <= 0) printf("%d\n", j);
{ j = j + 1;
printf("%d ", j); }
j = j + 1; while(j <= 0); // condition
} getch();
getch();; }
}

Prepared By:Ms.Ankita Page 52


C PROGRAMMING: UNIT I

1. FOR LOOP
The basic syntax of the for statement is,

for (initialization expression; test expr; increment expr)

program statement;

Prepared By:Ms.Ankita Page 53


C PROGRAMMING: UNIT I

Example

int sum=10;
for (i=0; i<6; ++i)
sum = sum+i;

The operation for the loop is as follows

1) The initialization expression is evaluated.

2) The test expression is evaluated. If it is TRUE, body of the loop is executed. If it is

FALSE, exit the for loop.

3) Assume test expression is TRUE. Execute the program statements making up the

body of the loop.

4) Evaluate the increment expression and return to step 2.

5) When test expression is FALSE, exit loop and move on to next line of code.

Prepared By:Ms.Ankita Page 54


C PROGRAMMING: UNIT I

Trace the execution of the sample loop

int sum=10; 1 4
for ( i=0 ; i<6 ; ++i )
{ 2
sum = sum+i; 3
}

Various forms of for loop :

1. The Infinite Loop:


for( ; ; )
{
printf("This loop will run forever.\n");
}

When the conditional expression is absent, it is assumed to be true.

OR

initialize- before the loop

Condition & inc/dec – inside the loop

You can terminate an infinite loop by pressing Ctrl + C keys.


Prepared By:Ms.Ankita Page 55
C PROGRAMMING: UNIT I

2. Multiple Initialization Statement inside For

for(i=0,j=0;i<5;i++)
{
statement1;
statement2;
statement3;
}

Multiple initialization statements must be seperated by Comma in for loop.

3. Missing Increment/Decrement Statement

for(i=0;i<5;)
{
statement1;
statement2;
statement3;
i++;
}

However we have to explicitly alter the value i in the loop body.

4. Missing Initialization in For Loop

i = 0;
for(;i<5;i++)
{
statement1;
statement2;
statement3;
}

We have to set value of „i‟ before entering in the loop otherwise it will take garbage value of „i‟.

5. No condition

For(initialize; ; inc/dec)
{
statement1;
statement2;

Prepared By:Ms.Ankita Page 56


C PROGRAMMING: UNIT I

statement3;
}
In this case, condition must be given inside the body, otherwise it will be an infinite loop.

6. No initialize, no condition

for( ; ; inc/dec)
{
statement1;
statement2;
statement3;
}
In this case, initialization musy be done before and condition must be given inside the loop.

7. No test, no inc/ dec

For(initialize ; ; )
{
statement1;
statement2;
statement3;
}
Test and inc/dec must be given inside the body of the loop.

8. Initialization & Update not used


for ( ; i<10 ; )

Initialization and inc/dec must be given inside the body of the loop.

Sentinel value
 Used as a “stopping” value
 It is like a flag or an indicator
 Used to let the program know that the user has finished with inputting information.

For example 999,-99,-1 etc can be used as sentinel value.

int age;
printf (“enter an age” (-1 to stop)”);
scanf (“%d”,&age);
While (age != -1)
{
Printf ( “ enter an age( -1 to stop) ” );
Scanf ( “ %d” , &age);

Prepared By:Ms.Ankita Page 57


C PROGRAMMING: UNIT I

2. WHILE LOOP

Initialize loop counter;


While(condition)
{
Do this;
And this;

Increment/decrement loop counter;

The C while statement creates a structured loop that executes as long as a specified condition is
true at the start of each pass through the loop
While Loop is also Entry Controlled Loop.[i.e conditions are checked if found true then and
then only code is executed ]

FOR EXAMPLE
#include <stdio.h>

void main ()
{

int a = 10; /* local variable definition */

/* while loop execution */


while( a < 20 )
{
printf("value of a: %d\n", a);
a++ ;
}

getch();
}

When the above code is compiled and executed, it produces the following result:

Prepared By:Ms.Ankita Page 58


C PROGRAMMING: UNIT I

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

3. DO-WHILE LOOP
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.

If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false

do
{
statement(s);

}while( condition );

For example
#include <stdio.h>

void main ()
{
/* local variable definition */
int a = 10;

/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );

Prepared By:Ms.Ankita Page 59


C PROGRAMMING: UNIT I

getch();
}

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Difference between while and do-while


While Do-while
Condition is specified at the top Condition is mentioned at the bottom
Body statement is executed when condition is Body statement is executed even if condition is not
satisfied. satisfied.
No brackets froa single statement Brackets are essential even when a single statement
exists.
It is an entry controlled loop It is an exit controlled loop.

Q1. Ask user to enter a number between 1-10. If that number is > 5, find square of that number ,
otherwise find cube of that number.
Q2. Ask user to enter height of 10 students. Find average height of students.
Q3. Sum of 1+2+3…10.
Q4. Sum of 1+1/2+1/3+1/4…..1/10.
Q5. Find remainder of first 20 numbers when divided by any number.

JUMPING STATEMENTS
C language provides us multiple statements through which we can transfer the
control anywhere in the program

There are basically 4 Jumping statements:

1. break jumping statements.


2. continue jumping statements.
Prepared By:Ms.Ankita Page 60
C PROGRAMMING: UNIT I

3. goto jumping statements.


4. Exit statement

1. break jumping statements.

 By using this jumping statement, we can terminate the further execution of the
program and transfer the control to the end of any immediate loop.
 To do all this we have to specify a break jumping statements whenever we
want to terminate from the loop.

Syntax:
break;

NOTE: This jumping statements always used with the control structure like switch
case, while, do while, for loop etc.

#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
for(i=1;i<=10;i++)
{
printf(“ \t %d ”,i);

if(i>5)
{
break;
}
}
}

2. continue jumping statements.

Prepared By:Ms.Ankita Page 61


C PROGRAMMING: UNIT I

By using this jumping statement, we can terminate the further execution of the
program and transfer the control to the beginning of any immediate loop.

To do all this we have to specify a continue jumping statements whenever we want


to terminate any particular condition and restart/continue our execution.

Syntax: continue;

NOTE: This jumping statements always used with the control structure like switch
case, while, do while, for loop etc.

Example: Program based upon continue jumping statements:

WAP to display the following output:

1 2 3 4 6 7 9 10

#include<stdio.h>
#include<conio.h>

void main()
{
int i=1;
clrscr();
for(i=1;i<=10;i++)
{
if(i==5 || i==8)
{
continue;
}
printf(" \t %d ",i);
}
getch();
}

3. goto jumping statements.

Prepared By:Ms.Ankita Page 62


C PROGRAMMING: UNIT I

· By using this jumping statements we can transfer the control from


current location to anywhere in the program.
· To do all this we have to specify a label with goto and the control will
transfer to the location where the label is specified.

Syntax: goto <label>;

NOTE:
The control will transfer to those label that are part of particular function, where
goto is specified.

All those labels will not included, that are not the part of a particular function
where the goto is specified.

Use of goto statement is highly discouraged in any programming language


because it makes difficult to trace the control flow of a program, making the
program hard to understand and hard to modify.

Example: Program based upon goto jumping statements:


void main()
{
clrscr();
printf("welcome");
goto x;
y: printf(" C ");
goto z;
x: printf(" to");
goto y;
z: printf("programming");
getch();
}

Prepared By:Ms.Ankita Page 63


C PROGRAMMING: UNIT I

exit()
Stops the execution of the entire program.

The following example shows the usage of exit() function.

#include <stdio.h>
#include <stdlib.h>

void main ()
{
printf("Start of the program....\n");

printf("Exiting the program....\n");


exit(0);

printf("End of the program....\n");

getch();
}

Let us compile and run the above program that will produce the following result:

Start of the program....


Exiting the program....

Exit v/s break


Break---- jumps control out of the loop

Exit() - Stops the execution of the entire program.

Continue-- loop takes the next iteration


Break Continue Exit
It is a keyword It is a keyword It is a function.
No header file is needed. No header file is needed. Header file stdlib.h is needed.
It stops the execution of the loop loop takes the next iteration It terminates the program.

Prepared By:Ms.Ankita Page 64

You might also like