Sie sind auf Seite 1von 134

Operators

An operator is a symbol that specifies arithmetic , logical or

relational operation to be performed. The data items that operators act upon are called operands. An expression is any computation involving variables and operators that yields a value.
operators

arithmetical unary

assignment equality Relational Logical

bitwise

ternary binary

ARITHMETIC OPERATORS
There are five arithmetic operators in C. They are

The% operator is also called as modulus operator Arithmetic operators are binary operators because they are operators act upon 2 operands

The operands acted upon by arithmetic operators

must represent numeric values


The remainder operator(%) requires that both

operands be integers and the second operand be nonzero.


the division operator(/) requires that the second

operand be nonzero.

Example a and b 2 integer variables with 14 and 4 as

values a+b=18 a-b=10 a*b=56 a/b=3(decimal part truncated) a%b=2(remainder of division)

UNARY OPERATORS
operators that act upon a single operand to produce a new value are

called unary operators. Unary minus operator


Unary operator negates the value of its operand

This operator reverses sign of the operand value


If a=5 then a will be -5

If a=-4 then a will be 4


-a doesnot change the value of a at the location where it permanently

resides in memory

unary increment and decrement operator(++,--)


Unary ++ and operators increment or decrement value of a variable by 1 These operators taking 2 forms Prefix

++var first add 1 to the variable var . then the result is assigned to the variable on the left. --var first subtract 1 from the variable var . then the result is assigned to the variable on the left.
Postfix-first assigns the value to the variable on left and then

increments/decrements value of the variable.

Example

Let int i=1 printf("i = %d\n", i); printf (i= %d\n", ++i); printf("i = %d\n", i); output will be i=1 i=2 i=2 printf ("i = %d\n" i); printf("i = %d\n", i++); printf("i = %d\n", i); output will be i=1 i=1 i=2

Basic rules for using ++ and -operators


The operand must be a variable but not a constant or

an expression The operator ++ and may precede or succeed the operand

Sizeof operator
sizeof is a unary compile time operator that returns the number of

bytes the operand occupies.


General format

Sizeof var (where var is a declared variable) Or Sizeof(type) (where type is a c data type)
Example

Int a; Printf(size of variable a=%d,sizeof a);Will print size of variable a=2;

RELATIONAL OPERATORS
Relational operators are used for comparing numerical quantities. Relational operators evaluate to 1,representing true outcome or 0

representing the false


Expression containing relational operators is called relational expression

The operands of a relational operator must evaluate to a number. Characters are valid operands since they are represented by numeric

values. For ex A < F /*will give the output 1 because comparing ascii values of A and F
Relational operators should not be used for comparing strings this

will results in string addresses being compared , not string contents


For example HELLO< BYE cause the address of HELLO to be

compared to the address of BYE.


For example int i=2,j=3

i<j will return 1 J!=2 will return 1

Logical operators

Logical operators&& and || are used to combine two or more relational expressions. An expression which combines 2 or more relational expression is termed as logical expression Logical And produces 0 if one or both operands evaluate to 0.otherwise produces 1 Logical OR produce 0 if both operands evaluate to 0 otherwise it produce 1

Logical not( ! ) is a unary operator negates the logical value of its single operand .it causes an expression that is originally true to become false, and vice versa.

Examples of logical expression


i=4,j=3 (i>j)||(i==j) this will return 1 (i>j)&&(i==j) will return 0 !(i>j) will return 0;

Assignment operators
assign the value of an expression to an identifier assignment operators are used to form assignment expressions Assignment expressions are written in the form

identifier = expression identifier generally represents a variable. Expression represents a constant, a variable or a more complex expression.

Examples of assignment expressions a=3 sum = a + b


assignment operator = and the equality operator == are distinct.

assignment operator is used to assign a value to an identifier, whereas the equality operator is used to determine if two expressions have the same value

Multiple assignments of the form

identifier 1 = identifier 2 = .... = expression is permissible in C In such situations, the assignments are carried out from right to left identifier 1 = identifier 2 = expression is equivalent to identifier 1 = (identifier 2 = expression)

Example i=j=5 here 5 is first assigned to j.then value of j assigned to i

Beside = operator, C programming language supports other short hand format which acts the same assignment operator with arithmetic operators a+=b means a=a+b

Conditional(ternary) operator
C offers a conditional operator(?: that store a value depending on a

condition.
A conditional expression is written in the form

expression 1 ? expression 2 : expression 3


When evaluating a conditional expression, expression I is evaluated

first. If expression 1 is true then expression 2 is evaluated and this becomes the value of the conditional expression.
if expression 1 is false , then expression 3 is evaluated and this

becomes the value of the conditional expression.


For example z = (a > b) ? a : b;

Comma operator
The comma operator can be used to link related expressions together. A comma-linked list of expressions are evaluated left to right and value of right most expression is accepted as final result The general form of an expression using comma operator is Expression M=(expression1,expression2,..............expressionN); Since comma has the lowest precedence in operators the parenthesis is necessary.

Examples of comma operator


int m=1; int n; n = (m=m+3 , m%3); Here m =m+3 evaluated first and will assign 4,then m%3 evaluated and the result 1 is assigned to n

Precedence and associativity of of operators


Precedence is used to determine the order in which different operators in a complex expression are evaluated. Associativity is used to determine the order in which operators with the same precedence are evaluated in a complex expression.

Highest priority is for () and lowest for comma. Postfix ++ and - -has higher priority than prefix ++ and - Unary operators has higher priority than binary operators Relational operators having precedence less than arithmetic and unary operators Logical AND has higher precedence than logical OR

Operator () [] . -> ++ --(postfix) ++ --(prefix) + ! ~ sizeof(type) *(indirection) &(address)

Associativity left-to-right

right-to-left

* / %
+ -

left-to-right
left-to-right

<< >> < <= > >=


== != & ^ | && || ?:

left-to-right left-to-right left-to-right left-to-right left-to-right left-to-right left-to-right left-to-right right-to-left

= right-to-left += -= *= /= %= &= ^= |= <<= >>= , left-to-right

Type conversion
Type conversion occurs when the expression has data of mixed data types. example of such expression include converting an integer value in to a float value,

or assigning the value of the expression to a variable with different data type.
In type conversion, the data type is promoted from lower to higher because

converting higher to lower involves loss of precision and value.

In c there are 2 types of type conversion


Implicit conversion Explicit conversion

Implicit conversion
It is the automatic conversion done by compiler without

programmers intervention

Rules for implicit conversion 1. If either operand is long double, convert the other to long double. 2. Otherwise, if either operand is double, convert the other to double. 3. Otherwise, if either operand is float, convert the other to float. 4. Otherwise, convert char and short to int. 5. Then, if either operand is long, convert the other to long.

I integer variable with value 7 F float variable with 5.5 C char variable with value w I+F will have value 12.5 I+C will have value 126

Explicit conversion
Explicit conversion is user defined that forces an expression to be of

specific type Explicit conversion of an operand to a specific type is called type casting General form of casting is (data type) expression The expression is converted to the data type specified in parenthesis The data type associated with the expression itself is not changed by a cast. Rather, it is the value of the expression that undergoes type conversion

For example i is an integer variable whose value is 7, and


f is a floating-point variable whose value is 8.5. ((int) (i + f)) % 4

For ex int a=100,b=40 float c; c=a/b will result 2.000000 but actual value required is 2.5 for that we have to use c=(float)a/b

Library functions
The C language is accompanied by a number of library functions

that carry out various commonly used operations or calculations


Library functions that are functionally similar are usually grouped

together as (compiled) object programs in separate library files. These library files are supplied as a part of each C compiler.
A library function is accessed simply by writing the function name,

followed by a list of arguments that represent information being passed to the function. The arguments must be enclosed in

parentheses and separated by commas.

In order to use a library function it may be necessary to include certain

specific information within the main portion of the program.


This information is generally stored in special files which are supplied

with the compiler. Thus, the required information can be obtained simply by accessing these special files. This is accomplished with the preprocessor statement #include; i.e., #include <filename> where filename represents the name of a special file. For example #include<math.h> contains library functions for mathematical operations

library functions for input /output


These library functions are defined in stdio.h header file . getchar() Enter a character from the standard input device. Send a character to the standard output device Send data items to the standard output device Enter data items from the standard input device

putchar() Printf

Scanf

Library functions for string operations


These library functions defined in string.h strcat(s,t) strcmp(s,t) Concatenate t to end of s return negative, zero, or positive fors < t, s == t, s > t

strcpy(s,t)
strlen(s)

Copy t to s
return length of s

Mathematical Functions
These functions defined in math.h
sin(x) cos(x) exp(x) log(x) sqrt(x) abs(i) pow(x,y) sine of x, x in radians cosine ofx, x in radians exponential function ex natural logarithm of x square root ofx (x>0) absolute value of integer variable xy

Character Class Testing and Conversion


isalpha(c) isupper(c) islower(c) isdigit(c) isalnum(c) toupper(c) tolower(c) non-zero if c is alphabetic, 0 if not non-zero if c is upper case, 0 if not non-zero if c is lower case, 0 if not non-zero if c is digit, 0 if not non-zero if isalpha(c) or isdigit(c), 0 if not Return c converted to upper case Return c converted to lower case

Data input and output

Console i/o functions


The screen and keyboard together are called a console.
Console i/o functions classified to two categories Formatted

Unformatted

Console input/output fuctions

Formatted functions Type char int float string Input Scanf() Scanf() Scanf() Scanf() Output Printf() Printf() Printf() Printf() Type char

unformatted functions Input Getch() Getche() Getchar() Output Putch() Putchar()

int
float string Gets() Puts()

getch() and getche()


Getch() function will read a single character the instant it is typed by

programmer without waiting for the Enter Key to be hit. The typed character is not echoed on screen.
Getche() function will also read a single character the instant it is

typed by programmer without waiting for the Enter key to be hit, just like getch() function. Getche() echoes the character on screen that you

typed.

#include<stdio.h> #include<conio.h> Void Main() { char ch; printf(Press any key to continue"); getch(); //will not echo the character printf(Type any character:"); ch=getche();

putch()
putch() writes a character to the screen.

#include<conio.h> Void Main() { Char ch=A; Putch(ch); }

Single character input getchar function


Getchar() is an input function that reads a single character from

standard input device.


The getchar function is a part of the standard C I/O library. This function does not require any arguments , but still have to use

empty parenthesis.
The getchar has the following form.

Char_variable = getchar();
Char_variable must be previously declared character variable.

On end of file the value of EOF is returned. Usually EOF will be assigned the value -1, though this may vary from

one compiler to another. #include<stdio.h> main() { char C;

printf("Type one character:");


C=getchar(); printf(" The character you typed is = %c",C);

SINGLE CHARACTER OUTPUT -putchar FUNCTION

Single characters can be displayed using the C library

function putchar. It transmits a single character to a standard output device


The general form is

putchar (char_variable ); Char_variable must be previously declared character variable

#include<stdio.h> main() { char in; printf(" enter one character "); in=getchar(); Printf(entered character is ); putchar(in); }

Formatted input and output functions


When input and output is required in specified format

the standard library functions scanf and printf are used.

scanf ()
Scanf() allows to enter data from the keyboard that will be formatted

in a certain way.
The function returns the number of data items that have been entered

successfully.
General form of scanf

scanf(control string,arg1,arg2.......argn);
Control string is a string that can consist of format specifiers.it

indicates the format and type of data to be read from standard input device.
Argl,arg2, . . . argn are arguments that represent the individual input

data items.
These arguments are preceded with the address-of operator to

indicate the address of data item in memory

There is no need to use & for strings stored in arrays because array name is already a pointer

Format specifiers in scanf()


Conversion Character d i o u Datatype Signed decimal integer decimal, hexadecimal or octal integer octal integer unsigned decimal integer

x c
s e f g %lf

hexadecimal integer single character


string Float or double Float or double Float or double double

the size qualifier conversion characters may be preceded with certain conversion characters

main( )

{
char item[20]; i n t partno; f l o a t cost; ..... scanf("%s %d %f",item, &partno, &cost); ..... }
%s, indicates that the first argument (item) represents a string. %d, indicates that the second argument (&partno) represents a decimal

integer value
%f,indicates that the third argument (&cost) represents a floating-point

value

More on scanf
The format specifier %% is used for single % character in the input stream.

Inputting integer numbers


While Inputting Integer numbers we can also specify the field width of a number.general format is %wd w integer specifies the field width of the number to be read d - integer Examples Scanf(%2d %5d,&num1,&num2);

Data inputted 25 12345 then 25 assigned to num1 and 12345 to num2


Suppose data inputted is 12345 25 then 12 will be assigned to num1 and 345 to num2

We can use following conversion specifications for strings

%[characters] %[^characters]
The specification %[characters] means that only the character

specified with in the brackets are permissible in the input string.if input string contains any other character string will be terminated at the first

encounter of such character.


With the help of %[] scanf can be used to read string with blank

spaces.
The specification %[^characters] means the characters specified

after the circumflex(^) are not permitted in the input string. The reading of string will be terminated at the encounter of one of these character

Example of %[]
main() { char address[80]; printf("Enter address\n"); scanf("%[a-z]", address); printf(%-80s,address); } Output Enter address new york 122345 new york

Example of %[^]
main() { char address[80]; printf("Enter address\n"); scanf("%[^\n]", address); printf("%-80s", address); } Output Enter address New Delhi 110 002 New Delhi 110 002

Scanf will stop reading a value of a variable in

following cases A white space character found in numeric specification Maximum number of characters have been read An error detected The end of file is reached

Printf()
O/P data can be written from the computer onto a standard O/P

device using the library function printf General form is printf(control string,arg1,arg2.....argn); where control string refers to a string that contains formatting information, and arg1, arg2, . . . , argn are arguments that represent the individual output data items. Control string contain 3 types of items characters that are simply printed as they are conversion specification that begin with a % sign escape sequence that begin with a \sign

Format specifiers for printf()


Conversion Character d i o u Datatype

Signed decimal integer decimal, hexadecimal or octal integer octal integer unsigned decimal integer

the size qualifier conversion characters may be preceded with certain conversion characters .size qualifier characters are h for short,l for long and L for long double

x c
s e f g %lf

hexadecimal integer single character


string Float or double Float or double Float or double double

More on printf()
Outputting integer numbers
While outputting a integer number we can also specify minimum field

width for the output. General format is %wd w-minimum field width for output. if number grater than specified field width it will be printed in full overriding minimum specification d-value to be printed is a integer The number is written right justified in the given field width

Examples
Format
Printf(%d,1234); Printf(%6d,1234);

output
1 2 1 3 2 3 4 4

Printf(%-6d,1234) 1

2 2

3 3

4 4

Printf(%2d,1234);

Outputting real numbers


For outputting real numbers we can specify number of digits after

decimal point and minimum number of positions that are to be used for display
General format is

%w.pf w-minimum field width specification p- specifies no.of digits to be displayed after decimal
We can also use

point(precision)

printf(%*.*f,width,precision,number); here width and precision


supplied at runtime. For example printf(*.*f,7,2,number); is equivalent to printf(%7.2f,number);

examples
To print Float y=98.7654 Format Printf(%7.4f,y) Printf(%7.2f,y)
Printf(%-7.2f,y)
9 8

output

9 .

8 7

. 7

Printf( %f,y) Printf(%10.2e,y)

8
9 .

8 8 e + 0 1

Outputting strings
A single character can be displayed in desired position

using %wc The character will be displayed right justified in field of w columns Format specification for outputting string is %w.ps where w specifies the field width for display and p specifies only first p characters of the string are to be displayed

examples
For outputting strings NEW DELHI 110001 specification output %s N E W D E L H I 1 1 0 0 %20s N E W D E L H I
%20.10s %5s %.5s
%-20.10s N E W N E W N E W N E W D E L H I D D E L H I 0 1 1 1 0 0 0 1 D E L H I

1 1 0 0 0 1

We can also include flags , which affects the appearance of the output in printf Flags are used immediately after % sign Commonly used flags and their meaning given below
flag + 0 #

meaning left justifies the field; default is right justification.


always prefixes a signed value with a sign (+ or -). pads numeric values with leading zeros. If both 0 and appear as flags, the 0 flag is ignored. prefixes octal values with 0 and hexadecimal values with 0x or 0X. For floating point values, this forces the decimal point to be displayed, even if no characters follow it.

Printf(%07.2f,y) Printf(%-+6.1f,5.5)

0 +

0 5 .

9 5

String input and output:gets and puts


The gets function receives the string from standard input device.

A string is an array or set of characters. string may include whitespace


characters. The standard form of the gets function is

gets (str)
Here str is a string variable It will reads characters into str from keyboard until newline character is encountered and will append a null character to the string

puts outputs the string to the standard output device. The standard form for the puts function is puts (str) where str is a string variable.

The puts function displays the contents stored in its parameter on the screen. In puts() function,we cannot pass more than one argument.So it can display one string at a time.

#include<stdio.h> Void main() { char s[80]; printf("Type a string less than 80 characters:"); gets(s); Puts( The string types is: ); puts(s); }

Control statements
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 statements which specify the order of execution

of statements are called control statements

Program control statements

Selection/branching
Conditional type
Unconditional type

Iteration/looping
for while Do-while

if Ifelse

If-elseif

switch break goto continue

Control statements in broadly divided to two


Branching Looping

Branching is deciding what actions to take and looping

is deciding how many times to take a certain action.

If statement
The simplest form of the control statement is the If statement. It is very frequently used in decision making and allowing the flow

of program execution.
Syntax if (Test expression) statement; The test expression inside if should not end with a semicolon

If test expression evaluates to true, corresponding statement is


executed. If test expression evaluates to false control goes to next executable statement. The statement can be either simple or compound.

Sample program for if construct


#include<stdio.h> main() { int number; printf("Type a number:"); scanf("%d",&number); if (number < 0) number = -number; printf("The absolute value is %d \n", number);

Type a number:11 The absolute value is 11

Type a number:-5 The absolute value is 5

If-else
If...else is an extension of simple if statement. General form is

if(test expression)
Statement1 Else Statement 2
if the test expression evaluates to true, then program statement 1 is

executed, otherwise program statement 2 will be executed.

Flowchart of if else construct

#include<stdio.h> void main() { int a,b; printf("Enter 2 number"); scanf("%d%d",&a,&b); if (a>b) printf("%d is greater",a); else printf("%d is greater",b); }

Nesting of if..else statements


When series of decisions are involved we may have to

use more than if else statement in nested form.

A nested if is a statement that has another if in its

body or in it else's body.


Nested if else having 3 formats if(test expression 1) {
if(testexpression 2) statement 1; [else statement 2;] } else body of else;

II

if(test expression 1) body-of-if; else { if(testexpression 2) statement 1; [else statement 2;] }

III

if(test expression 1 ) {

if(test expression 2) statement 1 ; [else statement 2;] } else {

if(test expression 3) statement3; [else statement4;]

/*sample code using nested if-else */ if(a>b) { if(a>c) printf("%d is larger",a); } else if(b>c) printf("%d is larger",b); else printf("%d is larger",c); }

If-else-if ladder
When a series of many conditions have to be checked

we may use the ladder else if statement


General form of if else-if ladder is

if (test Expression 1) statement 1; else if (test Expression 2) statement2; else if (test Expression 3) statement3; . . else if (Test Expression n) statement n; else statement-F;

If expression1 is evaluated to true then statement 1 is executed.

if expression2 is true then statement 2 is executed and so on. If none of the test expression are true then statement F will be executed

Sample code for if else- if ladder { ---------If(score>=80) Grade=A; Else if(score>=70 && score<80) Grade=B; Else if(score>=60 && score<70) Grade=C; Else if(score>=50 && score<60) Grade=D Else Grade=F; }

Looping/iteration
Looping allows set of instructions to be performed repeatedly until a

certain condition is fulfilled


There are 2 types of loops Pre-test loop or entry controlled loop Post-test loop or exit controlled loop

In entry controlled loop test expression is evaluated before entering

the loop.
In a exit controlled loop test expression is evaluated before exiting

from the loop

Test expression

false

Body of loop

True
Body of loop True Test expression false Pre-test loop Post-test loop

In pretest loop ,loop body may not be executed where as in post-test loop loop body will be executed at least once

C having 3 looping statements


For While

Do while
for and while are pretest/entry controlled loops and do while is exit controlled/post test loops

Parts of loop
Initialization expression(s)
before entering the loop, loop control variables must be initialized. this initialization of control variable take place under initialization

expression .
This part of loop is the first to be executed. Initialization expression(s) are executed only once in the beginning of the

loop
Test expression
Test expression is an expression whose truth value decides whether the

loop-body will be executed or not .


If test expression evaluates to true loop body gets executed,otherwise loop

is terminated

Update expression(s)
change value of loop control variable(s)

Update expression are executed every time through the loop before

test expression is tested Body- of- the loop The statements that are executed repeatedly form the body of the loop

While Loop
The while statement is used to carry out looping operations, in which a

group of statements is executed repeatedly, until some condition has been satisfied.
Is an entry controlled loop The general form of the while statement is

while ( test expression)


statement
The statement will be executed repeatedly, as long as the expression

is true
Statements can be simple or compound,

start

Initialization

Test expression True

false

In while loop ,initialization of loop control variable done before the loop starts. Updating must included in the body of the loop

Statement(s)

Update expressions

Flowchart of while loop

Sample program
//to print numbers 1 to 10 using while loop void main() { int i=1; while(i<=10) { printf("%d\n",i); i++; } }

For loop
It is a commonly used loop
This loop is definite loop because programmer knows exactly how

many times loop will be executed


General format is

For(initialization; test expression; update expression) statement;


Statements can be simple or compound, which is the body of loop

Flowchart of for loop

Initialization

Test expression True Update expressions statements

false

All the four parts of while loop is also present in for loop. but all are comprised in one line

for loop can written as equivalent to while loop and vice versa

For(initialization; test expression; update expression) statement;


Is equivalent to while

Initialization; while ( test expression)

{
statement ; Update expressions;

Sample program using for loop


void main() { int i; For(i=1;i<=10; i++) { printf("%d\n",i); } }

Additional features of for loop


First feature is Multiple initialization and update expressions For loop may contain multiple initialization and/or update expressions Multiple expressions are separated by commas For(i=1,sum=0;i<=n;sum+=i,++i) printf(%d,i); Second feature is Test condition may have any compound relation and we can variable other than loop control variable For(i=1;i<20&&sum<100;++i) sum=sum+i; Here loop uses a compound test condition with loop control variable i and another variable sum . if both conditions i<20 and sum<100 are true loop will be executed Third feature is initialization and update expression are optional i.e we can skip any or both expressions Semicolons separating the parts must remain int i=1,sum=0; For(;i<=n;sum+=i,++i) printf(%d,i);

Do while loop
It is a post-test loop
Test expression is evaluated after executed loop body at least once General syntax is

do { statement } while (expression); Statements will be executed until expression become false.

Initialization
statements

Update expressions

True

Test expression false

//to print numbers 1 to 10 using do-while loop void main() { int i=1; do { printf("%d\n",i); i++; }while(i<=10);
}

Nested control structures


Like if statement loops can also nested
Each loops having its own control variable or index Inner loop must terminate before outer loop

for(i=1;i<5;i++) { for(j=1;j<=i;j++) { printf(%d\t",j); } printf("\n"); } Here inner for loop is executed for each value of i.i takes values 1,2,3,4 Inner loop is executed once for i=1 according to condition j=i;,twice for i=2,thrice for i=3 and four times when i=4

Nesting of while int n,i=1,j=1; while(i<=n) { j=1; while(j<=i) { printf(%d\t,j); j++; } printf("\n"); i++; }

Nesting of do while Int i=1,j=1; do { j=1; do { printf("%d",j); j++; }while(j<=i); printf("\n"); i++; }while(i<=n);

Switch statement
The usage of multiple If else statement increases the complexity of the program since when the number of If else statements increase it

affects the readability of the program and makes it difficult to follow the
program. The switch statement removes these disadvantages by using a

simple and straight forward approach.


c has a built-in multiway decision statement known as a switch statement

General format of switch statement is

Switch(expression) { Case constant 1:statementlist1; break; Case constant 2:statementlist2; break; .. Default :statementlist n }

Expression is an integer or character expression. When the switch statement

is executed the expression is evaluated first and the value is compared with the
case label values in the given order. If the case label matches with the value of the expression then the control is

transferred directly to the group of statements which follow the label.


If none of the statements matches then the statement against the default is executed. The default statement is optional in switch statement in case if any default statement is not given and if none of the condition matches then no action takes place in this case the control transfers to the next statement

Break statement at the end of each statement block indicates end of


particular case and causes an exit from switch statement. Even if there are multiple statements to be executed in each case

there is no need to enclose them within a pair of braces

Sample code
switch(choice) { case 1: printf(you entered menu choice #1); break; case 2:printf(you entered menu choice #2); break; default:printf("Invalid Choice"); break; }

Once the statement list under a case is executed ,the flow of control

continues down executing all the following cases until the break is reached

Switch(number) { Case 1: Case 3: Case 5: Case 7: case 9 : printf(%d is an odd number,number); break; Case 2: Case 4: Case 6: Case 8:printf(%d is an even number,number); break; Default:printf(%d is not between or including 1 and 9,number); break; }

Rules for switch statement


Case labels must be constants or constant expression
Case labels must be unique. No two labels can have same value Break statement is optional. That is two or more case labels may

belong to the same statements The default label is optional. If present, it will be executed when the expression does not find a matching case label There can be at most one default label Default may be placed anywhere but usually placed at the end

Switch versus if-else Ladder


1.Switch can only test for equality where if can evaluate a relational or

logical expression
2.switch cannot handle floating point test. Where if can handle floating

point test also apart from integer and character test


3.Switch statement select its branches by testing value of a same

variable against set of constants whereas if else use series of expression that involve unrelated variables and complex expression
4.Switch case label value must be a constant

if 2 or more variables are to be compared use if-else

break
The break statement is used to terminate loops or to exit from a switch. It

can be used within a for, while,do -while, or switch statement.


The break statement is written simply as

break;
After a break is executed with in a loop or a case in switch execution

proceeds to the statement that follows loop or switch


When loops are nested break would only exit from the loop containing

it.i.e break will exit only a single loop

Exit from loop

While() { . If(condition) break; } For(.) { if(condition) Break; .. .. } ..

Exit from loop

Do { . If(condition) Break; . } While(..); For(.) { for(.) { if(condition) Break; . } .. }

Exit from loop

Exit from loop

Void main() { int c=1; While(c<=5) { If(c==3) Break; Printf(\t%d,c); c++; }

getch();
} Here output will be 1 2 break statement skips the rest of the loop and jumps over to the statement following loop

Break in nested loop


for(i=2;i<=n;i++) { for(j=2;j<i;j++) { if(i%j==0) break; } if(i==j) printf("%d\n",i); } Here if i% j is 0 then inner loop is terminated.i.e control will transfer to the statement if(i==j).

continue
Continue statement does not terminate the loop .it forces the next

iteration of the loop to take place, skipping any code in between.


On execution of continue statement control will goes to test

expression in while and do while statement and goes to the updating


expression in a for statement

While (test expr) { Continue; . . }

do
{ . continue; }while(testexpr); For(initialization;testexpr;updation) { Continue; . . }

void main() { . for(i=1;i<=2;i++) { for(j=1;j<=2;j++) { If(i==j) Continue; printf(%d %d,i,j); } } Output is 12 21

Difference between break and continue


break
It helps to make an earlier exit from the block where it appears

continue
It helps in avoiding the remaining statements in current iteration of the loop and continuing with the next iteration It can be used only in loop constructs

It can be used in all control statements including switch construct

GOTO statement:
The goto statement is used to alter the normal sequence of program execution by transferring control to some other part of the program. In its general form, the goto statement is written as goto label; where label is an identifier that is used to label the target statement

to which control will be transferred.

Sample code
void main() { float x,y; read: scanf(%f,&x); if(x<0) goto read; y=sqrt(x); printf(%f%f\n,x,y); }

void main() { int n,i; long int fact=1; scanf(%d,&n); if(n<0) goto end; for(i=1;i<=n;i++) fact*=i; printf(factorial is %ld,fact); end: getch(); }

Das könnte Ihnen auch gefallen