Sunteți pe pagina 1din 131

UNIT-II

Dennis Ritchie

1.History of c language
ALGOL

BCPL

History of c language
project multics to develop an operating system. 1969, language B was developed by Ken Thompson. c was develop in 1972 by Dennis M. Ritchie at Bell Labs(AT&T) in USA. 1988 c language was standardized by ANSI as ANSI C ANSI- American National Standards Institute.

2. Features of C language
1. 2. Robust rich set of built in functions and operators can be used to write any complex programs. C compilers combines the capabilities of low level languages with features of high level language. Therefore it is suitable for writing the system softwar5. e, application software and most of the compilers of other languages also developed with c language. Efficient and fast- rich variety of data types and powerful operators. Portable- c program written on one computer can also run on the other computer with small or no modification. ex- c program written in windows can also run on the linux operating system. Structured programming- every program in c language is divided into small module or functions so that it makes the program much simple and debugging, maintenance of the program is easy. Ability to extend itself- A C program is basically a collection of various function supported by C library (also known as header files). We can also add our own functions to the C library. These functions can be reused in other applications or programs by passing pieces of information to the functions, you can create useful, reusable code.

3. 4.

5. 6.

3. Structure of c program

Include information about standard library

Main calls library function printf to print this message.

C program consists of functions and variables. Function contains the statements that specify computation operation to be done. Variables stores the values used during the computation. Function can be named whatever you like. However, main is the special function where the program execution starts. Very program must have a main some where.

Preprocessor commands
The preprocessor command always starts with symbol # #include<stdio.h> this is called preprocessor command. Include command tells the preprocessor that we need the information from selected libraries called header file. Header file- collection of library files. -> it tells the compiler to include the information about the standard input\ output library. -> every program must need at least one library functions which are available in the header file.

Global variables.
The variables which are declared at the starting of the program called global variable. They are visible to all the parts of the program.

C program consists of functions and variables. Function contains the statements that specify computation operation to be done. Variables stores the values used during the computation. Function can be named whatever you like. However, main is the special function where the program execution starts. Very program must have a main some where. Functions are communicate each other by passing list of values called arguments. Main is defined to be a function that expects no arguments.

Local variables
The variables which are declared in a function are called local variables to that function. These variables visible only within the function.

Local variables
The variables which are declared in a function are called local variables to that function. These variables visible only within the function.

All the statements of main are enclosed in braces. A function can be called by naming it, followed by a paranthesized list of arguments. Main calls the printf with argument hello world\n. The string \nPrintf(hello world\n);C notation for the in the string is newline character, which when printed advances the output to the left margin on next line.

printf(hello world ); C compiler prints the error message. same program can also rewrite as #include<stdio.h> main() { printf(hello); printf(world); printf(\n); return 0; }

Main function may return some integer value to the operating system So at the end of the main add the statement return 0. main() is same as the int main()- it means that the function main returns some integer value to the os. Otherwise write the main as void main()- it does not return any value to the operating system and not necessary to write the return statement. Each statement in c program must end with (;) specifies that the instruction is ended.

Comments
To make the program more readable use the comments. They may used to make the program easier to understand. Two types of comments 1. block comment 2. line comment.

1. Block comment
/* write a program for the addition of two integer numbers*/ #include<stdio.h> main() { int a=10,b=20,c; c=a+b; printf(sum of a and b=%d,c); return 0; }

1. Block comment
above two lines /* write a program for the addition of two integer numbers*/ are a comment, which explains what the program does. Any characters between /* and */ are ignored by the compiler. Comments may appear anywhere a blank or tab or newline. /* and */ is used to comment the multiple lines of code which ignored by the compiler. /*/*..*/ - nested block comments are invalid.

2. Line comment
It uses two slashes // . This is used to comment single line. // #include<stdio.h>

Character set
Characters are used to form words, numbers and expressions. Characters are categorized as 1.Letters 2.Digits 3.Special characters 4.White spaces.

Character set
Letters (upper case and lower case) ABCDEF GHI JKLM NOPQRSTUVWXYZ abcdefghijklm nopqrstuvwxyz Digits 0123456789 Special Characters " ( ) * + - / : = !&$;<>%?,. #@{}[]\| White spaces blank space horizontal space Carriage return, new line.

Key words and identifiers


C word is classified as either keywords or identifiers. Keywords have fixed meanings these meanings cannot be changed Keywords must be in lowercase. Keywords depends on compilers that must be identified from the c manuals.

Key words
C key words
at u o cnne ot u i eu nm i f so hr t s ic wh t vl tl o ie a ba r k e df u e l at ee xr t n it n s nd i e g t pdf yee wl h ie cs ae d o fot la ln og s ef i o z ui n n o ca hr dul ob e fr o r gt r ei e s s tc ti a us nd ni e g cnt os ee l s gt o o rt r en u sut t c r vi o d

identifiers
Identifiers are name of the variables and functions. Identifiers are user defined names means name given to the variable whatever user likes. Ex- int a;// a is identifier int sum;// sum is identifier.

variables
When you want to process some information, you can save the values temporarily in variables.
Program #include<stdio.h> main() { int a=10,b=20,c; c=a+b; printf(sum of a and b=%d\n,c); return 0; } o/p- sum of a and b=30

Note variables must be declared before they are used, usually at the beginning of the function.

Definition- variable which stores the value in the memory location, that value varies during program execution variables in the above program are a b and c .

Variables names
There are some restrictions on the variable names 1. Names are made up of letters and digits and underscore(_). 2. The first character of the name must be a letter 3. The underscore is also a legal first character, but its use is not recommended. 4. Upper case and lower case letters are distinct, so a and A are two different names. 5. C keywords can't be used as variable names 6. White space is not allowed in variable names.

The following list contains some examples of legal and illegal C variable names:
Variable Name Percent y2x5__fg7h annual_profit _1990_tax savings#account Legality Legal Legal Legal Legal but not advised Illegal: Contains the illegal character #

double
9winter

Illegal: Is a C keyword
Illegal: First character is a digit

Data types in C
Type specifies a set of values and a set of operations that can be applied on those values. The data type defines the amount of storage allocated to variables, the type of values stored in variables. There are only a few basic data types in c char a single byte, capable of holding one character in the local character set int an integer, typically reflecting the natural size of integers on the host machine float single-precision floating point double double-precision floating point

There are number of qualifiers that can be applied to the basic types The qualifiers are also used to increase the range of the values. Qualifiers are signed, unsigned, short and long. Signed, unsigned are applied to char and integers. short apply to integers. long is used for integers and double. unsigned numbers are always positive or zero, and obey the 2n, signed numbers are short int a; long int b;

the word int can omitted

The char Data Type


The shortest data type is character. It is stored in 1 byte in memory. Corresponding integer values for all characters are defined in ASCII code (American Standard Code for Information Interchange). For example: character constant a has an int value 97, b - 98, A - 65 etc. The keyword char is used to declare a variable of a character type.

char letter =A; char letter = 65;

The int Data Type An integer number (also called whole number) has no fractional part or decimal point.

-> The keyword int is used to specify an integer variable. -> it occupies 2 bytes (16 bits) or 4 bytes (32 bits), depending on the machine architecture. 16-bit integer can have values in the range of - 32768 to 32767 One bit is used for sign. For 32-bit integer the range is about from -2 to +2 billions

The sizes of the data types are machine dependent. Short is 16bits, long 32 bits and int either 16 bits or 32 bits. These sizes are chosen by the compiler for its own hardware. In 16 bit processor short 2, int- 2, long- 4 In 32 bit processor short-2, int -4, long-4. They are restricted that short is no longer than int, int is at least 16 bits , long is at least 32 bits.

Unsigned integer If you know that the variable cannot have negative values, you may declare it as unsigned. unsigned variable type occupies the same amount of computer memory as int but the actual value can be twice as large as the maximum available int, because all values are positive. To decrease the size of allocated memory for a variable which is not too large, you may use the short type which is stored in 2 bytes The float Data Type -> The data type float represents a floating point number (also called a real number or numbers with decimal ). ->The keyword float is used to declare a variable of the type float. Ex: float float_num1=1.34; -> The float type variable is usually stored in 4 bytes, which means it is at least 6 digits of precision.

The double Data Type A floating point number can also be represented by the double data type. The data type double is stored on most machines in 8 bytes which is about 15 decimal places of accuracy. To declare a variable of the type double, use the keyword double.

Types in C
type
long double double float unsigned long long unsigned int unsigned short short unsigned char char size (byte) 10 8 4 4 4 4 4 2 2 1 1 smallest number 3.4E -4932 1.7E -308 1.7E -38 0 -2147483648 0 -2147483648 0 -32768 0 --128 0 127 or largest number 1.1E+4932 1.7E+308 3.4E+38 4294967295 2147483647 4294967295 2147483647 65535 32767 255 127 or 127 255

precision
1.08E -19 2.22E -16 1.19E -7

constant
1.2345L, 1.234E -5L 1.2345, 1.234E -5 1.2345F, 1.234E -5F 123UL 123L 123U 123 123U 123 a, 123, \n a, 123, \n

format specifier %Lf, %Le, %Lg %lf, %le, %lg %f, %e, %g %lu %ld, %li %u %d, %i %hu %hd, %hi %c %c

Formatted input/ output


The data is to be arranged in a particular format. The data is input to and out put from a stream. A stream is a source or destination of the data. it is associated with a physical device, such as terminals (keyboard, monitor). C has two forms of streams- text stream and binary stream. Text stream consists of sequence of characters. Binary stream consists of a sequence of data in 0s and 1s.

FIGURE Stream Physical Devices

The data is formatted using the printf and scanf functions. Scanf() converts the text stream coming from the keyboard to data values (char, int,ect) and stores them in the program variables. Printf() converts the data stored in variables into the text stream for output the keyboard.

printf() takes the set of data values and converts them to text stream using formatting instructions contained in a format control string. Fomat control specifiers are used to format the text stream.

FIGURE Output Formatting Concept

Format specifier specifies the data values type, size and display position. Printf statement takes two arguments 1. control string and 2.data values( variables) Control string contains the format specifiers and some text. syntax printf(control string,var1,var2,..varn); Exint a=10, b=20; printf(a=%d b=%d, a,b);

GURE Output Stream Formatting Example

scanf(control string,&var1,&var2.. &varn); control string includes format specifiers and specifies the field width.

GURE Formatting Text from an Input Stream

int a=12,b=23145; scanf(%2d %5d,&a,&b);

Each variable must be declared and defined before used in the program. Variable declaration1. tells the compiler what is the name of the variable. 2. specifies what type of data values the variable can hold. variable definition- reserves the memory for the declared variable and store some value is called garbage value.
-> variable declaration and variable definition done at the same time.

Variable declaration

int a;
Variable declaration and definition

a
23456

Variable name

Garbage value

1000 Address of the variable

Variable initialization
While declaring the variable assign initial value is called variable initialization.
Data type identifier= initial value;

ex

int a=10; float b=2.1; float pi=3.14; char ch=A;

constants
Constants- fixed values those cannot be changed during the program execution. Several types of constants are used 1.Character constants 1.1 single character constants 1.2 string constants. 2. Numeric constants. 2.1 integer constant 2.2 real constants.

Type qualifier const


One way to use the constant is with memory constants. Memory constants use a c type qualifier; const. This indicates that the data cannot be changed. const type identifier= value; const float pi=3.14;

Ex#include<stdio.h> void main() { float area,radius=3.0; const float pi=3.14; area=pi*radius*radius; printf(area of a circle= %f,area); }

1. Character constants
A single character constants are enclosed in single quotes. Ex- 1 X % Character constants have integer values called ASCII values. char ch=A; printf(%d,ch); ->65 similarly printf(%c,65)-> A

String constants- string a collection of characters or sequence of characters enclosed in double quotes. The characters may be letters, numbers, special characters and blank space. Ex- snist 2011 A.

Backslash characters are used in output functions. These backslash characters are preceded with the \ symbol. Constant
\a
\b \f \n \r \v \t \ \ \? \\ \0

Backslash \escape characters


meaning
Alert(bell)
Back space Form feed New line Carriage return Vertical tab Horizontal tab Single quote Double quotes Question mark Backslash null

Numeric constants
1. integer constant- sequence of digits like 0to 9. Ex- 123 -678 0 +78. Rules 1. Integer constant have at least one digit 2. No decimal points 3. No commas or blanks are allowed. 4. The allowable range for integer constant is -32768 to 32767.

To store the larger integer constants on 16 bit machine use the qualifiers such as U,L,UL. Type int
int

Representation +245
-678

Value 245
678 65342 99999 999999

unsigned integer 65342u/65342U unsigned long int 99999UL long integer 999999L

2. Real constants- the numbers containing fractional parts like 3.14. 1.9099 -0.89 +3.14 Real constants are also expressed in exponential notation.
Mantissa e exponent The part appearing before e is called mantissa this may be the fractional number or integer number and part following e is called exponent . Ex 215.65 may be written as 2.1565e2.

Examples of real constants


Type double
double float long double

Representation 0.
0.0 -2.0f

Value 0.0
.0 -2.0

3.14159276544L 3.14159276544

#include<stdio.h> void main() { const int a=10; int b=20; a=a+1; b=b+1; printf(a=%d b=%d,a,b); }

operators
C language is robust because it has rich set of operators. Operator a symbol used to perform a mathematical or logical manipulations. Operands- data values\variables are called operands. Operators must be applied on the operands. Expression- combination of operands and operators, which evaluated to one value i.e either true or false. expression . Operators- =, + X=Y+Z Operands- x,y,z

Types of operators
Following are the c operators. 1.Arithmetic operators 2.Relational operators. 3.Logical operators. 4.Assignment operators. 5.Increment and decrement operators. 6.Conditional operators. 7.Bitwise operators. 8.Special operators.

1. Arithmetic operators

Arithmetic operators + * / %

Meaning Addition or unary operator Subtraction or unary operator Multiplication Division- gives only coefficient. Modulo division- gives remainder.

c= a+b; z= x-y;

2.Relational operators.
Relational operators are used to compare the relationship between two operands.
Relational Meaning operators
< > <= >= == != Is less than Is greater than Less than or equal to Greater than or equal to Equal to Not equal to Relational operators are used if and else, while, for statements. The value of a relational Expression is either one or zero. It is one if the Specified relation is true and zero if the relation is false .

3. Logical operators.
Logical operators used to test more than one condition and make decision. Yields a value either one or zero
Logical operator &&
Ex- x<y&&x= = 8 logical expression

meaning Logical AND


Logical OR Logical NOT

|| !

AND OR truth table

Op1
0 0 1 1

Op2
0 1 0 1

AND
0 0 0 1

OR
0 1 1 1

4. Assignment operators
The value of an expression assigned to a variable. Assignment operator is =
variable = expression; a= a+1; x= x-1; x=x*(y-1); x=x/(y-1); x=x%y; =>a+=1; => x-=1; =>x*=y-1; => x/=y-1; =>x%=y;

5. Increment and decrement operators.


Increment operator- ++ Decrement operator - -++- add one(1) value to the operand -- - subtracts one value to the operand.
++x; equal to x=x+1;or x+=1; --y; equal to y=y-1;or y-=1;

6. Conditional operators ?:
Another name is ternary operator
Syntax Exp1?exp2:exp3;

?:

where exp1, exp2,exp3 are expressions. Exp1 evaluated first if it is non zero (true), then the exp2 is evaluated and becomes the value of the expression. if exp1 is zero(0), then exp3 is evaluated and become the value of the expression. This is like if(a<b) ex- a=1; x=a; b=2; else x= (a<b)?a:b; x=b;

7. Bitwise operators.
Manipulates the data which is in binary form.
Bitwise operators & | ^ << >> ~ Meaning

Bitwise AND Bitwise OR Exclusive OR Shift left Shift right Ones compliment

/ Examples: & Bitwise AND 0110 & 0011 0010 | Bitwise OR 0110 | 0011 0111 ^ Bitwise XOR 0110 ^ 0011 0101 << Left shift 01101110 << 2 10111000 >> Right shift 01101110 >> 3 00001101 ~ One's complement ~0011 1100 Notice: << and >> multiply/divide by 2n Don't confuse bitwise & | with logical && ||

8. Special operators
Special operators- *, -> ., , sizeof()
Sizeof()- unary operator (operates on a single value) Produces a result that represent the size in bytes or the data specified Format sizeof data e.g. int a = 5; sizeof(a); //produces 4 Or sizeof (data type) e.g. sizeof (char); //produces 1

Unary operators- operators used on a single operand - -, +, ++, --. Binary operators - operators used to apply in between two operands- +, -, /, %.

FIGURE Expression Categories

Primary expression An expression as only one operand no operator is called primary expression. It may be name of the variable, constant, or a parenthesized expression. a, snist,1.56, (x=10*2). Post fix expression- expression contains operand followed by one operator.

ex- a++; musta- -; variable in post fix expression. Operand be the

1. Value of the variable a is assigned to x 2. Value of the a is incremented by 1.

expression

FIGURE Result of Postfix a++

Example on post fix expression


#include<stdio.h> void main() { a=10; x=a++; printf(x=%d, a=%d,x,a); } out put- x=10, a=11

Prefix expression- operator followed by the operand.

ex- ++a;

FIGURE Prefix Expression

FIGURE Result of Prefix ++a

Example on pre fix expression


#include<stdio.h> void main() { a=10; x=++a; printf(x=%d, a=%d,x,a); } out put- x=11, a=11

Unary expression- unary operator followed by the operand

FIGURE Unary Expressions

Table

Examples of Unary Plus And Minus Expressions

Binary expressions- operator must be placed in between the two operands.

1 Operand must be integral data type( int, float) Ex- a+b a-c
FIGURE Binary Expressions

Precedence and association rules among operators


Precedence- the order in which expression is evaluated. Every operator has a special precedence. The operators which has higher precedence in the expression is evaluated first. example- a=8+4*2; a=? Associativity- Operators on the same line in the chart have the same precedence, and the "Associativity" column on the right gives their evaluation order.

Operator Precedence Chart


Operator Type Primary Expression Operators Operator () [] . -> expr++ expr-Associativity left-to-right

Unary Operators

* & + - ! ~ ++expr --expr (typecast) sizeof

right-to-left

Binary Operators

/ %

left-to-right

+ -

>> << < > <= >= == !=


& ^ | && ||
Ternary Operator Assignment Operators Comma

?: = += -= *= /= %= >>= <<= &= ^= |= ,

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

FIGURE 3-8 Left-to-Right Associativity


83

Type conversion- converting from one data type to another data type
Implicit Conversion If the compiler expects one type at a position, but another type is provided, then implicit conversion occurs. Compiler itself converts one type to other. Conversion during assignments: char c = 'a'; int i; i = c; /* i is assigned by the ascii of a */ Arithmetic conversion if two operands of a binary operator are not the same type, implicit conversion occurs: int i = 5 , j = 1; float x = 1.0, y; y = x / i; /* y = 1.0 / 5.0 */ y = j / i; /* y = 1 / 5 so y = 0 */

Explicit Conversion or type casting

You can override Cs default conversions by specifying your own temporary type change using the format: (data type) expression (data type) can be any valid C data type and expression is any variable, constant or a combination of both int x; x=(int)7.5;

Decision control structures


Till now we have used sequence control structure in the programs, in which the various steps are executed sequentially i.e. in the same order in which they appear in the program. In C programming the instructions are executed sequentially, by default. At times, we need a set of instructions to be executed in one situation and an another set of instructions to be executed in another situation.

In such cases we have to use decision control instructions.This can be acheived in C using;

(a)The if statement (b)The if-else statement (c)The conditional operators

1. If statement
Based on the condition execute the set of instructions otherwise skip them. C uses the key word if to implement the decision control instruction. general form of if statement if( condition\expression) { execute the statements; }

Condition following the if must be enclosed within parenthesis. If the condition is true then execute the given statement otherwise the statements not executed.

If statement
If it has single statement to execute then curly braces are optional. More than one statement curly braces are compulsory. Exint rno=2408; if(rno==2408) printf(this is ECE-C2);

if is a C reserved word

The condition must be a Valid C expression.


Enter

if ( condition ) statement;

Test If the condition is true, the statement is executed. If it is false, the statement is skipped.

Body of the IF Statement

Exit

If- else statements


if statement will execute a single statement, or a group of statements, when the expression following if evaluates to true. But it does nothing when the expression evaluates to false. In case, we want to execute one group of statements if the expression evaluates to true and another group of statements if the expression evaluates to false, we need to use the If-else statement.

The syntax of If-else statement is as follows; if (condition\expression){ The expression evaluated to true, Statement1} statement1 is executed. else { If false, statement2 is executed. statement2 } Both cases statement-x is executed. statement-x

The if-else Statement


An else clause can be added to an if statement to make an if-else

statement

Flowchart for if-else

Enter

Test

Body of the IF Statement1

Body of the ELSE Statement2

Exit

If the condition is true, statement1 is executed; if the condition is false, statement2 is executed
One or the other will be executed, but not both

Example float percentage; printf (enter the percentage); scanf (%f, &percentage); if (percentage<=50) printf(\nfailed); else printf(\npassed);

Few points to remember else must be written exactly below the if If there is only one statement in if and else block we can drop the pair of curly braces.
if( x>0) if(a>b) z=a; else z=b; if( x>0) { if(a>b) z=a; } else z=b;

Nested if else- within the if else we can include other if-else either in if block or else block F T

1. 2. 3. 4. 5.

Nested if- else Marks obtained by the student must given through keyboard. Print the result as per the following rules. Percentage is above or equal to 75- distinction. Percentage is less than 75 and equal to 60- first class. Percentage is less than 60 and equal to 50- second class. Percentage is less than 50 and equal to 40- third class. Percentage is below 40 failed.

#include<stdio.h> void main() { float m1,m2,m3,m4; float perc; printf(enter marks\n); scanf(%f%f%f%f,&m1,&m2, &m3,&m4); perc=(m1+m2+m3+m4)/4; if(perc>=75) printf(\ndistinction); else { if(per<75 && per>=60) printf(\n first class); else{ if(per<60 && per>=50) printf(\n second class); else { if(per<50 && per>=40) printf(\n third class); else printf(\nfail); }//else }//else }//else

Disadvantages care must be taken to match the corresponding pair of braces.

Else if statement
if(expression1) statement-1; else if(expression-2) statement-2; else if(expression-3) statement-3; else if (expression-n) statement-n; else statement-x; statement-y
Draw the flowchart for the else if statement.

Nested if else
#include<stdio.h> void main() { float m1,m2,m3,m4; float perc; printf(enter marks\n); scanf(%f%f%f%f,&m1,&m2, &m3,&m4); perc=(m1+m2+m3+m4)/4; if(perc>=75) printf(\ndistinction); else { if(per<75 && per>=60) printf(\n first class); else{ if(per<60 && per>=50) printf(\n second class); else { if(per<50 && per>=40) printf(\n third class); else printf(\nfail); }//else }//else }//else

else if clause
#include<stdio.h> void main() { float m1,m2,m3,m4; float perc; printf(enter marks\n); scanf(%f%f%f%f,&m1,&m2, &m3,&m4); perc=(m1+m2+m3+m4)/4; if(perc>=75) printf(\ndistinction); else if(per<75 && per>=60) printf(\n first class); else if(per<60 && per>=50) printf(\n second class); else if(per<50 && per>=40) printf(\n third class); else printf(\nfail);

Switch statement
In else if statement as the no of choice increases the program becomes difficult to read. C has a built in multi way decision statement call it as switch. The control statement that allows us to make a decision from the number of choices is called switch.

Switch statement
General form of switch
switch (expression) { case value-1: block1; break; case value-2: block2; break; case value-n: blockn; break; default: default block; }//switch statement-x;
1. The expression is any expression that must evaluates to integer value. 2. The keyword case followed by an integer or a character constant. 3. Each value in each case must be different from all the others. 4. How this program runs? First expression is evaluated. 5. This evaluated value compares against the values that follow the case statements. 6. When a match is found, executes the statements following that case and all the other cases were skipped. 7. If no match is found with any of the case statements, default block is executed. 8. Default is optional. 9. At last statement x is executed.

Break is used to exit from block

Examples on switch
Void main() Void main() { { int a; int a; scanf(%d,&a); scanf(%d,&a); switch(a) switch(a) { { case 1: case 1: printf(One); printf(One); case 2: break; printf(two); case 2: case 3: printf(two); printf(three); break; default: case 3: printf(this is default); printf(three); }//switch break; }//main default: printf(this is default); }//switch Note- there is no break in default case. }//main

Tips about the usage of switch


case values may not be in the ascending order. We can put the cases in any order.
int a; scanf(%d,&a); switch(a) { case 3: printf(One); break; case 1: printf(two); break; case 2: printf(three); break; default: printf(this is default); }//switch

we can also use char values in case and switch. char ch=x; switch(ch) { ch expression evaluated to the ascii value of x it is also an integer value case A: printf(this is A); break; case x: printf ( this is small x); break; default: printf (other letter); }//switch

can also execute a common set of statements for multiple


cases. ex- write a program to test whether the given alphabet is vowel or consonant.
Void main() { char ch; printf( enter the alphabet); scanf(%c,&ch); switch(ch) { case a: case e: case i: case o: case u: printf (\nthe alphabet is vowel); break; default: printf(\nthe alphabet is consonant); }

if there are multiple statements to be executed in the case no need to enclose them in pair of curly braces. Every statement in the switch must belong to some case or other. Even if a statement does not belong to any other case the compiler doesnt give any error. However that statement never executed. Exswitch(x) { printf(\nhai); case 1: printf(one); break; }//switch if no default case, the compiler executes the statement immediately following the close brace of switch

switch may occur within another switch called nested switch. continue statement should not used in switch. Switch statement is mainly used for the menu driven programs. value in the case must be an int constant or char constant or an expression that evaluates to one of these constants. even float is not allowed.
void main() { int x; scanf("%d",&x); switch(x) { case (x<=20): printf("\nless than 20"); break; default: printf("\nsoryy it wont work"); }//switch }

/*An institution gives grades to its students as follows: a. Grade A if he gets 80 or more marks b. Grade B if he gets between 60 and 79(both inclusive) c. Grade C if he gets between 50 and 59(both inclusive) d. Grade D if he gets between 40 and 49(both inclusive) e. Grade F otherwise.*/
void main() { float perc; int index; clrscr(); printf("\nenter the percentage marks"); scanf("%f",&perc); index=perc/10; switch(index) { case 10: case 9: case 8: printf("\n grade A"); break; case 7: case 6: printf("\n grade B"); break; case 5: printf("\ngrade C"); break; case 4: printf("\ngrade D"); break; default: printf("\n grade F"); }//switch

Repetitive control structures Program allows to perform a set of instructions repeatedly until a particular condition is being satisfied. This is called repetitive control structures or loop control structures. Loop control structures are: 1. while statement Loops in C 2. do- while statement 3. for statement

While loop
Set of instructions to be executed repeatedly until the condition is satisfied. ex- print the integer numbers from 1 to 10.
Syntax for while

Single statement while( expression)


Statement

Compound statements while( expression) { Statements }

While statement

while is a reserved word

If the condition is true, the statement is executed. while ( condition ) Then the condition is statement; evaluated again.

The statement (or a block of statements) is executed repetitively until the condition becomes false.

The expression may be relational or logical expression. ->while(i<=10&&j<=20) The statements in the loop may be single or block of statements. If single the curly braces are optional. The expression must be eventually become false, otherwise the loop would be executed forever, indefinitely.

Correct form int i=1; i=1; while(i<=10) while(i<=10) printf(%d,i); { printf(%d,i); i++; } instead of increment, we can also decrement the variable value. int i=5; while( i>=1) { printf(%d,i); i--; }

Loop variable may also be a float.

float a=1.0; while(a<=1.5) { printf(%f,a); a=a+0.1;} what would be the output of the following program? main() Output program goes into { infinite loop. int i=1; Range of the integer is -32768 to while(i<=32767) +32767. { -> it doesnt store the value 32768 printf(%d,i); so i value become -32768. i++; -> loop goes into infinite loop. }

Write a c program to find the sum of the first n natural numbers


While example #include <stdio.h> void main(void) { int n,i = 1, sum = 0; printf(\nenter n value); scanf(%d,&n); while ( i<= n) { sum = sum + i; i = i + 1; } printf(Sum of %d natural nos= %d\n,n, sum); getch(); }

The do while statement

Statements in the loop are executed first (at least once, and condition is tested last
Loop is controlled by a condition or counter Syntax do { statement; statement; } while (condition); statement;

Write a c program to find the sum of the first n natural numbers


While example #include <stdio.h> void main(void) { int n,i = 1, sum = 0; printf(\nenter n value); scanf(%d,&n); while ( i<= n) { sum = sum + i; i = i + 1; }//while printf(Sum of %d natural nos= %d\n,n, sum); getch(); }//main do-while example #include <stdio.h> void main(void) { int n,i = 1, sum = 0; printf(\nenter n value); scanf(%d,&n); do{ sum = sum + i; i = i + 1; } while ( i<= n) ; printf(Sum of %d natural nos= %d\n,n, sum); getch(); }//main

The for Loop


syntax for (expr1; expr2; expr3) statement; expr1 controls the looping action, expr2 represents a condition that ensures loop continuation, expr3 modifies the value of the control variable initially assigned by expr1

for(i=1;i<=5;i++)
When a for statement is executed for first time i=1 is initialized. Next expr2 is evaluated and tested at the beginning of each pass through the loop. if it true it executes the body of the loop. When control reaches to closed braces, control return back to expr3 ass If the loop continuation condition is initially false, the body part of the loop is not performed Any of the three parts can be omitted, but the semicolons must be kept

keyword control variable i final value of control variable for which the condition is true

for (i=1; i <= n; i = i + 1) initial value of control variable Examples Vary the control variable from 1 to 100 in increments of 1 for (i = 1; i <= 100; i++) Vary the control variable from 100 to 1 in decrements of -1 for (i = 100; i >= 1; i--) Vary the control variable from 5 to 55 in increments of 5 for (i = 5; i <= 55; i+=5) increment of control variable

loop continuation condition

Write a c program to find the sum of the first n natural numbers While example do-while example For example
#include <stdio.h> void main(void) { int n,i = 1, sum = 0; printf(\nenter n value); scanf(%d,&n); while ( i<= n) { sum = sum + i; i = i + 1; }//while printf(Sum of %d natural nos= %d\n,n, sum); getch(); }//main #include <stdio.h> void main(void) { int n,i = 1, sum = 0; printf(\nenter n value); scanf(%d,&n); do{ sum = sum + i; i = i + 1; } while ( i<= n) ; printf(Sum of %d natural nos= %d\n,n, sum); getch(); }//main #include <stdio.h> void main(void) { int n,i,sum = 0; printf(\nenter n value); scanf(%d,&n); for(i=1;i<=n;i++) sum=sum+i; printf(Sum of %d natural nos= %d\n,n, sum

Few more points to remember


expr1,expr2 and expr3 in for can be replaced by any valid expression. ex:for (scanf(%d,&i);i<=5;i++)

If for loop have single statement we can omitt the curly braces. for(i=1;i<=10;i++) printf(%d,i); for(i=0;i<=10;) Even incrementation done inside the for { loop semicolon is must in the for loop printf(%d,i); i=i+1;}

Int i=1; for(;i<=10;i++) printf(%d,i); Semicolon is compulsory

Int i=1; for(;i<=10;) { printf(%d,i); i++; } Multiple initialization and decrement/increment in for loops must be seperated with the comma operator. for(i=o,j=1;i<=n;i++,j++) but only one condition must be used.

Nested for loops


Nested means there is a loop within a loop Executed from the inside out Each loop is like a layer and has its own counter variable, its own loop expression and its own loop body In a nested loop, for each value of the outermost counter variable, the complete inner loop will be executed once General form for (loop1_exprs) { loop_body_1 for (loop2_exprs) { loop_body_2 } loop_body_1b }

Most compilers allow 15 nesting levels DONT DO IT!!

Nested for loops


int i,j,sum; for(i=1,i<=3;i++) { for(j=0;j<2;j++) { sum=i+j; printf(i=%d,j=%d,sum=%d,i,j,sum); }//inner for loop }//outer for loop

char ch=y int i; while(ch==y) { printf(\n enter the i value); scanf(%d,&i); printf(%d =%d %d,i=i*i); printf(\n do want to enter another i value); scanf(%c,&ch); }

break statement
break statement is used to exit from the loop or a block. When break statement is encountered control automatically exit from the loop and passes to the first statement after the loop. Use keyword break followed by semicolon. break;

Write a program to find whether the given number is prime or not


#include<stdio.h> void main() { int num,i; printf(\n enter the number); scanf(%d,&num); i=2; while(i<=num-1) { if(num%i==0) { printf(not a prime number); break; }//if i++; }//while if(i= = num) printf(\n its a prime number); getch(); }//main

continue statement
continue is used to take the control to the beginning of the loop, by passing the statements inside the loop which have not yet been executed. When continue is encountered in the program the control automatically goes to the beginning of the loop.

main() { int i,j; for(i=1;i<=2;i++) { for(j=1;j<=2;j++) { if(i==j) continue; printf(\n %d %d,i,j); }//for }//for }//main

Output 12 2 1

Assignment-1
1. draw the block diagram of the computer. Explain about the components of the computer. 2. explain about the system development life cycle. 3. define algorithm and flowchart. Write an algorithm and flowchart for the following problems. a. largest of three numbers. b. nature of quadratic equations. 4. explain about different data types in c language. 5. explain about the different operators in c language. 6. explain about the repetitive control structures (while, do- while, for loops). 7. write a c program to find whether the given no is prime or not. 8. write a c program to display an institution gives grades to its students as follows: a. Grade A if he gets 80 or more marks b. Grade B if he gets between 60 and 79(both inclusive) c. Grade C if he gets between 50 and 59(both inclusive) d. Grade D if he gets between 40 and 49(both inclusive) e. Grade F otherwise.*/

Last date for submission- 29/10/2011

Towers of Honoi
Recursion a function which calls itself. To develop the algorithm for the recursive method use the towers of Hanoi. Suppose three pegs, labeled A,B, and C are given, and suppose on peg A there are placed a finite number of n disks in decreasing order. The objective of the game is to move the disk from peg A to peg C using peg B as an auxiliary. The rules of this problem are as follows 1. only one disk may be moved at a time. Specifically, only the top disk on any peg may be moved to any other peg. 2. at no time can a larger disk be placed on a smaller disk.

A
1 2 3
A->C A->B C->B A->C B->A B->C A->C

f(n)= 2n-1 moves for n disks

fibonacci sequence and golden ratio


0,1,1,2,3,5,8,13.- fibonacci sequence Golden ratio a/b=1.618
C program #include<stdio.h> #include<conio.h> void main() { int n,a=0,b=1,i=3,fib; clrscr(); printf("\nenter the n value "); scanf("%d",&n); printf("%d,%d",a,b); while(i<=n) { fib=a+b; printf(",%d",fib); a=b; b=fib; i++; }//while getch(); }//main

~ algorithm for fibonacci sequence. 1. read n 2. initialize a=0,b=1,i=2. 3. print a and b. 4. while( i<=n) 4.1 compute fib= a+b 4.2 print fib 4.3 set a=b 4.4 set b=fib 4.5 increment i=i+1 5. end while

Sum of the digits of a given number

Algorithm 1. read n 2. while(n>0) 2.1 y=n%10 2.2 n=n/10 2.3 sum=sum+y 3. print sum

S-ar putea să vă placă și