0% found this document useful (0 votes)
105 views28 pages

Fallsem2013-14 CP3212 TB02 Cse101 Unit-2 PDF

The document provides an introduction to the C programming language. It discusses the chronological development of C from languages like ALGOL 60 and BCPL. It also covers the basic elements of C including keywords, data types, variables, operators, expressions and more. Key points include C being a powerful and portable structured programming language, and that learning C involves understanding its lexical elements and following a sequential process.

Uploaded by

Sijoy Syriac
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views28 pages

Fallsem2013-14 CP3212 TB02 Cse101 Unit-2 PDF

The document provides an introduction to the C programming language. It discusses the chronological development of C from languages like ALGOL 60 and BCPL. It also covers the basic elements of C including keywords, data types, variables, operators, expressions and more. Key points include C being a powerful and portable structured programming language, and that learning C involves understanding its lexical elements and following a sequential process.

Uploaded by

Sijoy Syriac
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT II BASIC ELEMENTS OF C: Introduction of C The C language was developed by Dennis Ritchie in the year 1972 at AT & T Bell

l Laboratories. Chronological Development in the Development of C: ALGOL 60 Algorithmic Language, International committee,1960

CPL Combined Programming Language Developed in Cambridge Univ, London, 1963

BCPL Basic Combined Language, Developed by Martin Richards, 1967

B Developed by Ken Thompson, Bell Labs, 1970 C Developed by Dennis Ritchie, Bell Labs, 1972 Types of C and Its Compilers: 1. TURBO C 2. BORLAND C 3. ANSI C 4. MICROSOFT C 5. QUICK C Features of C: Middle Level language General-Purpose Language C is a Powerful structure oriented language. Function oriented and modular programming language. Except some keywords all the statements should be written in lowercase. All the statements are terminated by semicolon except for header file inclusions, Macro definitions, function definitions, looping and conditions. C provides enriched pointer handling properties. C is rich in inbuilt functions and data types. C is highly robust and portable.

Steps In Learning C: Learning C follows the sequential steps: Character Set Keywords and Identifiers Variables Constants Data types Operators Expressions Instructions C Program

LEXICAL ELEMENTS OF C: The basic elements used to construct C statements: 1. Character Set 2. Keywords 3. Identifiers 4. Data types 5. Constants 6. Variables 7. Declarations Character Set The set of characters used in a language to write the program words, expressions and statements is known as its character set. The C character set consists of upper and lowercase alphabets, digits, special characters and white spaces. The alphabets and digits are together called the alphanumeric characters. 1. Alphabets: A, B, C Z / a, b, c z 2. Digits : 0,1,2, 9 3. Special Characters 4. White Space characters: blank space, new line, form feed, horizontal/vertical tab. Keywords These are certain reserved words that are standard, predefined meanings in C. All keywords have fixed meanings and their meanings cannot be changed. These cannot be used as programmer defined identifiers. Auto double int struct Break else long switch Case enum register typedef Char extern return union

Identifiers Identifiers are the names defined by the programmer for various program elements such as variables, constants and functions. Identifiers consist of sequence of letters and digits. Rules to declare an identifier: 1. First character must be a letter followed by letter or digit. 2. Special characters not allowed except underscore. 3. Length of the identifier is significant up to certain digits depends on the compiler. 4. Identifiers are case sensitive. Valid Identifiers: Count, Area, a123 Invalid Identifiers: Char, ten$, 2book, Car no Data Types Data types refers to the kind of data used in a program. C is rich in data types. Its type of data which can be processed by the programming language. C is rich in data types which are represented differently within computer memory. It is classified into two types: Primary, Derived. Primary Data types: C compiler supports the following four fundamental data types. Char Character int Integer float single precision floating point value double double precision floating point value Qualifier can be added to primary data types to provide some control over the range of values and storage space. Two types of qualifiers: 1) Size qualifier 2) Sign qualifier Size Qualifier: Size Qualifier alter the size of the basic data type. There are two size qualifier can be applied to integers. Short and long. Sign Qualifier: Two types of sign qualifier: Signed and Unsigned. Derived Data types: Derived from the collections of primary data types. C supports Arrays, Functions, pointers, structures, unions.

Constants Constants are fixed values and they remain unchanged during the execution of the program. Constants

Numeric

Character

String

Integer

Real

Decimal Octal Integer Constants:

Float Double

It consists of a sequence of digits without any decimal point. It can be written in three different number systems. 1. Decimal 2. Octal 3. Hexadecimal Decimal Integer: A decimal integer constant consists of nay combination of digits from 0 to 9. Valid decimal integer constants are 0, 1, -123, 456, 789, 300001, etc. Invalid decimal integer constants are 1,000 , 10.0 , 672 67 , 044 , 128-22289, etc. Octal Integer: An octal integer consists of any combinations of digits taken from 0 to 7, with leading 0. Valid octal integers are 0, 01, 033, 0435, 0777, etc. Invalid octal integers are 712, 1192, 05.33, etc. Hexadecimal Integer: A hexadecimal integer constants can consists of any combination of digits taken from the sets 0 through 9 and a to f, leading with 0x or 0X. Valid hexadecimal integer are 0X, 0XAAA, 0XABCD, 0X11123, 0Xfff, etc. Invalid hexadecimal integer are 0123, 0X2A.23, 0XABH, etc. Floating Point Constants: It is a decimal number that contains either a decimal point or an exponent or both.

Valid floating point constants are 1.0, 0.123, 701.112, 0.123E-5, 1.124E+4,etc . Invalid floating point constants are 50, 1.2E+5.1, 1.4E 10, etc. Character constants: Single character enclosed in single quotation marks. Character constants have integer values that are determined by the character set. Single character must be an alphabet/digit/ spl char enclosed within single quotes. Length of a single char constant is one. Character constants and its equivalent Ascii Values: Constants D Z 0 9 d = String Constants: It is a sequence of characters enclosed in double quotes. It may contains any combination of digits, letters, escape sequence, whitespaces., Example: Hello, 044-256 , $9.95, The area= , hello \n world. Variables: Variables are identifiers whose value gets changed during the execution of the program. Variables must be started with an alphabet / underscore and not with a number or any other special characters. Variable name refers to the memory area in which a particular value is stored. These memory locations can contain integer, real, single char or string constant. The variable names used by the programmer must be meaningful so as to reflect its use or function or nature in the program. All the variables used must be declared before all executable statements. General format for variable declarations: datatype var1, var2, ., where, Datatype : May be any data type. Var1, Var2: Variables separated by comma. Variables are of two types: 1. Local variables: Variables declared / defined inside the function Eg) function( ) { int i, j=0; i=i+j; Value 68 90 48 57 100 61

} 2. Global variables: Variables declared outside the main function or other functions. Eg) int a=2, b; main( ) { int i; i=a+b; } OPERATORS AND EXPRESSIONS An Operators is a symbol or a special character that tells the computer to perform certain mathematical or logical operations which is applied to operands to give a result. Operators are used to manipulate data. The data on which operators acts are called operands. The operators combine constants and variables to form an expression. Most operators require two or more operands while others act upon single operand. Unary Operator: The operator that uses one operand. Binary Operator: The operator that uses two operands. Classification of Operators: 1. 2. 3. 4. 5. 6. 7. 8. Arithmetic Relational Logical Assignment Increment and Decrement Bitwise Conditional Comma

9 Arithmetic Operators:
C language has all the basic arithmetic operators. Operators Meaning + Addition Subtraction * Multiplication / Division % Modulo Operands that act upon arithmetic operator must represent numeric values. Operands must be integer/ floating point. These operators are called Binary operators because they require two operands.

When both the operands used are declared as integers then it is called as Integer arithmetic. If two operands are float, it is called as floating point arithmetic. If one operand is integer and other is real, it is called as mixed-mode arithmetic. 125/25.00 = 5.0 Example: a=5.5, b=1.1 a + b= 5.5+1.1=6.6

9 Relational Operators: The relational operators are used in selection type programming construct,
where the programmer has to make some decision or comparison.

The result of a comparison is a logical value that takes true(1) or false(0). Let x=10, y=15, z=A
Operators Meaning < Less than Greater than > Less than or equal to <= Greater than or equal to >= Equal to == Not equal to != The value of the relational expression is either one or zero. If the expression is false, it is represented by an integer value 0. These operators are left to right associativity. If the values of a,b,c are 10,20,30 respectively then the results and the values represented by the expressions are a<b = = True = = 1

9 Increment and Decrement:


Pre-Increment: The operand on the right hand side is first incremented by 1 and then the value is assigned to the left hand side operand. Eg) Let a=5 and X=0 X=++a; The value of a->5 is incremented to 1 and 6 is assigned to x. Result is x=6 and a=6. Post-Increment: The operand on the right hand side is first assigned a value to the left hand side operand and then incremented by 1. Let a=5, X=0 X=a++; The value of a->5 is assigned to x, and then the value of a is incremented by 1 Result is x=5, a=6

Pre-Decrement: The operand on the right hand side is first decremented by 1 and then the value is assigned to left hand side operand. Let a=5, X=0 X=--a; The value of a->5 is decremented by 1 and 4 is assigned to x. Result is x=4 and a=4. Post-Decrement: The operand on the right hand side is first assigned a value to the left hand side operand and then decremented by 1. X=a--; Let a=5, X=0; The value of a->5 is assigned to x, and then the value of a is decremented by 1. Result is x =5, a =4. 9 Logical Operators: Operators which are used to combine two or more relational operators are called as logical operators. These operators are used to test more than one condition at a time. Operators Meaning && Logical AND || Logical OR ! Logical NOT Example: A B 10 10 10 3 5 5

Expression (A>B) && (B>5) (A!=B) || (B<10) !A || (A= = B)

Result 0 (false) 1 (true) 0 (false)

9 Assignment Operators: Assigns a value to a variable or an identifier. The value can be a constant or an expression or an identifier. Format for simple assignment: Lvalue = Expression Where, Lvalue = Represents a memory location where the value an be stored and it is called a variable. Expression = may be a constant or initialized variable or combination of constants, variables and operators.

Example: x=10; x=y; x= a*a+b*b+c*c; Invalid: x+y=0 and 10=x; Consider a=a+10; can be represented as a+=10; if the variable in LHS and the first operand in RHS are the same. General format: Lvalue operator = expression Lvalue = represents a memory location Operator= represents arithmetic, shift or bitwise. Expression = may be constant, variable or combination of constants. Example: x=x+1 ; x+=1 Z=Z*(x+y) ; z * = (x+y) 9 Bitwise Operators: Bitwise operators that are used in applications, which require manipulation of individual bits within a word of memory. These operators permit the programmer to access and manipulate individual bits within a piece of data. Bitwise operators can operate only on integers and characters but not on floats and doubles. Operator Meaning ~ Ones Complement << Left shift >> Right shift & Bitwise AND | Bitwise OR ^ Bitwise XOR The one s complement operator ( ~ ) is an unary operator which causes the bits of the operands to be inserted. Example : ~ 110011 = 001100 The left shift operator ( << ) shifts each bit of the operand to its left. The general form of the left shift operator is Variable < < no. of bit positions Eg) If x=7 y=x << 1 is 14 The right shift operator shifts each bit of the operand to its right. The general form of the right shift operator is Variable > > no. of bit positions Eg) If x=7 y=x >>1 is 3

Bitwise

Binary

Unary

Bitwise

Logical

Shift

Ones Complement

AND

OR

XOR

Left

Right

Bitwise AND Operator( &) It returns 1 if both the operands are one, otherwise it returns zero. A 0 0 1 1 B 0 1 0 1 A&B 0 0 0 1

Example: 11001101 10001100 10001100 Bitwise Inclusive OR( | ) It returns 1 if one or more bits have a value of 1, otherwise it returns zero. A 0 0 1 1 Example: 00001010 00000101 00001111 Bitwise Exclusive OR ( ^) It returns 1 if one of the operand is 1 and the other is zero, otherwise it returns zero. A B A^B 0 0 0 B 0 1 0 1 A|B 0 1 1 1

0 1 1 Example:

1 0 1

1 1 0

00001010 00000111 00001101 9 Conditional Operators: It is a ternary (3) operator. The general format is expression? expression1 : expression2 expression1 will be returned otherwise the value of expression2 is returned. Example : int a,b; scanf(%d, &a); b = (a>10 ? : 0); Result : b=1, if a is greater than 10 b=0, if a is smaller than 10

PRECEDENCE AND ASSOCIATIVITY OF OPERATORS An expression is a combination of constants, variables and operators. Consider the expression, a+b*c * has higher precedence. Hence (b*c) will be evaluated first. This result will then be added to a. In order to override the precedence, parentheses can be used. Associativity refers to the order in which the operators with the same precedence are evaluated in expression. It is also called as grouping. The operators in an expression are evaluated either from left-to-right or right-to-left. In case of nested parentheses, the innermost parentheses are evaluated first. Preced ence Level 1 Operator Operation Associativity

() [] . ->

Function Call Array subscript Dot Arrow

Left to right Left to right Left to right Left to right

! ~ ++ -& * Size of * / % + << >> > <= > >= == != & ^ | && || ?: < <= &= n= = += -= *= <= %= > >= ,

4 5 6

7 8 9 10 11 12 13 14

Logical NOT Ones complement Unary minus Increment Decrement Address of Indirection Cast operator Size of Multiplication Division Modulus Addition Subtraction Left shift Right shift Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Simple and Compound Assignment

Right to Left Right to left Right to left Right to left Right to Left Right to Left Right to Left Right to Left 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 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

15

Comma

Left to Right

INPUT AND OUTPUT FUNCTIONS The input functions are used to read data from input devices like keyboard, mouse, etc. The output functions are used to display data on the monitor, printer and file storage.

I/O functions

Unformatted

Formatted

CharacterOriented

String Oriented

printf( ), Scanf( )

Getchar( ) Putchar( )

gets( ) Puts( )

CHARACTER ORIENTED FUNTIONS:

GetChar( ) Reads one character and returns the ASCII value of the key pressed. The return value may be stored in a variable of type int or char. Its syntax is: Variable = getchar( ) ; The getchar( ) function, after reading a character, waits for the user to press the enter key. Example: Char C1; C1= getchar( ); PutChar( ) Putchar( ) prints one character on the screen. The syntax is Void Putchar(ascii_value); Where ascii_value is a constant or variable of type int or char. Example: 1) Char C1; C1= getchar( ); Putchar( C1); Displays a character entered by the user. 2) Putchar(70); Displays the character F 3) Putchar( \n ); Displays a new line
READING AND DISPLAYING STRINGS

Gets( ) Gets a string as an input. The gets( ) collects a string a characters terminated by a new line from the standard input stream stdin and puts it in to str. Example : Char string[10]; gets(string); - Gets a word from the input and stores it in a array string.

#include<stdio.h> main() { Char string[20]; Printf(Enter a string:); gets(string); printf(%s, string); }

Puts( ) Prints the string. The syntax is Puts(string); Example: #include<stdio.h> main() { Char str[]= This is an example; Puts(str); }
FORMATTED INPUT FUNCTIONS

Scanf( )

Scanf( ) stands for Scan Formatted. Scanf( ) is used to read values in a specified format. The general syntax is : int scanf(Control-String, argument_list); The function scanf returns the number of arguments read. Control-string represents the field format in which the data is to be entered. Argument_list represents the address of the location where the data is stored. Commas separate the arguments in the argument list. Control string contains the conversion character %, a data type character and an optional number specifying the field width. The data type character indicates the type of data assigned to the variable. The format specifiers used in scanf are: Control String % %ld %u %h %c %s %g %f %e Description Read an integer in decimal Long integer Unsigned integer Short integer Character String Double Float argument same as %f, but use exponential notation

%o %x %[..] Control string for integer numbers:

Integer in Octal Integer in hexadecimal Strings of words

%wd Where, w is an optional width of a number d indicates the integer mode. Example: Scanf(%5d %3d, &n1,&n2); This reads values of two integers and assigns them to n1 and n2. If the input is 10000 and 10, then n1=10000 and n2=10 If the input is 10 and 10000, then n1=10 and n2=100 The input data must be separated by blank space, tab or newline character. The scanf statement terminates, 1. When the number of characters specified by the field width is reached. 2. When a character invalid for the data value is read. Reading real numbers: The control string specification for reading real numbers is %wf Where w is an optional field width and f indicates real mode. Example: Scanf(%f %f, &f1,&f2); Scanf(%7.4f, &f1); If input is 12.3456, then f1=12.3456 Printf( ) It specifies print formatted and is used to display a message. The syntax is Printf(Control-string, argument-list); Control string consists of , Messages to be printed on the screen. Format specifiers to define the format for the values to be displayed. Escape sequence characters like \n, \t etc. Example: Printf(Welcome to the world of C \n); Output: Welcome to the world of C Printf( i is %d\n, i); Output: The string %d is replaced with the value of the variable i is (value of i)

Control String %d %ld %c %s %f %e %o %x %%

Description Integer in Decimal Long integer in decimal Character String Float or double value Same as %f Integer in Octal Integer hexadecimal Single %

CONTROL STATEMENTS The statement of C are broadly classified into three categories: 1. Sequence Statements are executed one after another. 2. Selection Selects the path of execution based on a condition. 3. Looping Permits repetitive execution of statements till a condition is satisfied. Types of Control Statements: Control Statements

Conditional

Unconditional

Selection

Looping

goto

break

Continue

If 1. Sequence:

switch

for

do-while while

In sequence construct, statements are executed one by one in the order from top to bottom. Example: Accept two numbers and find their product Algorithm: 1. Start 2. Accept two numbers 3. Find the product 4. Display the product 5. End

FlowChart: Start Accept two numbers num1, num2

Prod= num1 *num2

Print Prod

End Program: #include<stdio.h> main( ) { int num1,num2,prod; printf(Enter two numbers:); scanf(%d%d, &num1,&num2); prod=num1 * num2; printf(\nThe product of %d and %d is , num1, num2); }

2. Selection: Chooses a set of statements to be executed based on a condition. The selection construct is used for comparison or decision-making. The statements are if and switch.

IF Statement: Syntax: if ( Condition ) Statement;

FlowChart:

Cond

Statement

The statement will be executed when the condition evaluates to true. If the condition fails, the control shifts out of the loop to the consecutive statement. Example: Accept two numbers, Display the first number if greater than the second. Algorithm: 1. Start 2. Accept two numbers and store the variables in Fn and Sn. 3. If Fn > Sn, display Fn is greater than Sn. 4. End. Program: #include<stdio.h> main( ) { int fn,sn; printf(Enter two integers:); scanf(%d%d, &fn, &sn); if(fn > sn) printf(The first number %d is greater than the second number %d, fn,sn); } IF-ELSE syntax: If (condition) { Statement (s1); } Else { Statement (s2) } The use of { } is optional if only a single statement is present in a block.

False

Condn

True

Statement2

Statement 1

Example: Accept two numbers and display the smallest number.

Algorithm: 1. Start. 2. Accept two numbers and store them in variables fn and sn. 3. If fn<sn Then fn is smallest number Else display sn is smallest number 4. End. Program: #include<stdio.h> main( ) { int fn,sn; printf(Enter the two numbers: ); scanf(%d %d, &fn, &sn); if(fn<sn) printf(The first number %d is the smallest number, fn); else printf(The second number %d is the smallest number,sn); } NESTED IF statement: In if and if-else construct, a statement may contain in itself another if statement. Such a statement is referred as a nested if statement. A nested if statement is used to check more than one condition. The general syntax is : if( condition ) if(condition) statement; else statement;

if( condition ) statement; else if(condition) statement; Example Accept three numbers and display the largest number. Algorithm: i. Start ii. Accept 3 numbers and store them in fn,sn and tn. iii. If fn > sn and if fn > tn then display fn is the largest number Else if sn > tn then display sn is the largest number Else display tn is the largest number iv. End

Program: #include<stdio.h> main( ) { int fn, sn, tn; printf(Enter 3 integers:); scanf(%d%d%d, &fn, &sn, &tn); if(( fn > sn ) && (fn > tn)) printf(%d\n is the largest number, fn); else { if ( sn >tn ) printf(%d is the largest number., sn); else printf(%d is the largest number., tn); } } THE SWITCH statement: Syntax: Switch (expression) { Case value-1; block-1; break; Case value-2; break-2; break; default:

default-block; break; } Statement-x; The switch statement tests the value of a given variable or expression against a list of case values and when a match is found a block of statements associated with that case is executed. The expression is an integer expression or character. Value-1, value-2 is constants or constant expressions and is known as case labels. These values should be unique within a switch statement. Block-1, block-2 are statement lists and may contain zero or more statements. Case labels end with a colon (:) When the switch is executed, the value of the expression is successively compared against the values value-1, value-2 If a case is found, whose value matches with the value of the expression, and then the block of statements that follows the case is executed. The break statement, transferring the control to the statement-x following the switch. Default is an optional case.

1. 2. 3. 4. 5. 6. 7. 8. 9.

10. Flowchart:

Switch Expression

Expression=value-2

Block-1

Expression=value-2 Block-2 ..... ..... ..... ..... Default block Statement-X

(no match) Default

Example:

Index=marks/10; Switch(index) { Case 10: Case 9: Case 8: Grade=Honours; Break; Case 7: Case 6: Grade=First Division; Break; Case 5: Grade=Second Division; Break; Case 4: Grade=Third Division; Break; Default: Grade=Fail; Break; } Printf(%s\n, grade); GOTO Statement It is an unconditional branching statement. In goto no condition is checked and hence the name unconditional branching statement. Goto statement has a label which specifies where the control is to be blocked. General Form: Goto Label; Label: Statement; Label: may be anywhere in the program. Example: #include<stdio.h> int main( ) { int n; scanf(%d,&n);

if(n%2= =0) goto even; else goto odd; even: printf(Even Number); odd : printf(Odd Number); } DECISION MAKING AND LOOPING Looping: Executing the same set of statements until some condition is met. C provides three looping constructs. a. While statement b. Do-while statement c. For statement

Decision Making: Decides whether to continue with that loop or come out of that loop. A program loop consist of two parts. 1. Body of the loop 2. Control or decision making statements. Depending on the position of the control statement in a loop, control structure may be o Entry-controlled loop o Exit controlled loop

Entry Controlled Loop In entry-controlled loop, the condition is checked first, if it is satisfied, body of the loop will be executed, otherwise it will not be executed.

Exit Controlled Loop The test is performed at the end of the loop, therefore the body is executed unconditionally for the first time.

Four steps of a Looping Process: 1. 2. 3. 4. Setting and initializing a counter. Test for a specified condition for execution of the loop. Execution of the statements in the loop Incrementing the counter.

WHILE Statement

It is entry-controlled label statement. Test condition is evaluated first, if the condition is true, then body of loop is executed. Syntax: While(condition) { Body of the loop; } This process is repeated until the test condition becomes false. If it becomes false, the control comes out of the loop. The statement immediately following the loop will be executed. Here i is the loop control variable. The loop control variable should be initialized outside the loop and incremented / decremented inside the loop. Example: int i=1,n=5; While(i<n) { printf(%d,i); i++; } DO- WHILE Statement It is an exit checked control statement. The body of the loop is executed atleast once even when the condition is not satisfied. The loop will be executed as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. Syntax: do { Body of the loop; } while(test condition); Example: To find GCD of two integers #include<stdio.h> int main( ) { int a,b,c; printf(Enter Divisor); scanf(%d,&a);

printf(Enter Dividend); scanf(%d,&b); do { c=a%b; if(a%b==0) { goto A; } a=b; b=c; } While(c!=0); A: printf(%d\n, b); } The FOR Statement It is an entry-controlled construct. Syntax : For(initialization;test-condition;increment/decrement) { Body of the loop; } Example: For(i=1;i<=n;i++ or i=i+1) 1. The control variable will be initialized in the initialization part. 2. The test condition is checked (i<n) if it is satisfied, the body of the loop will be executed. 3. When the body of the loop is executed, the control will again come back to the for statement. 4. The control variable is then incremented/decremented. 5. Then the test condition is checked, if its is true, the body will be executed again. 6. The same process will be repeated until the test condition becomes false. 7. The three sections inside for loop are separated by semicolons. Example: for(i=10;i>=1;i--) { printf(%d,i); } The BREAK Statement When a break is encounted inside any C loop, control automatically passes to the first statement after the loop.

A break is usually associated with an if . Example: main( ) { int num, i; scanf(%d, &num); i=2; while(i<=num-1) { if (num%i==0) { printf(The number %d is not a prime number, num); break; } i++; } if(i= = num) { printf(The number %d is a prime number, num); } In this, if num%i=0, then the message not prime number is printed and control breaks the while loop and the control will reach outside the while loop. Break, breaks the control only from the loop in which it is placed. int main( ) { int i=1,j=1; while(j++<=20) { If(j= = 15) break; else printf(%d%d\n,i,j); }}} In this program, when j=15, break takes the control outside the inner while only, since it is placed inside the inner while The CONTINUE Statement o When the keyword continue is encountered inside any C loop, control automatically passes to the beginning of the loop, bypassing the statements inside the loop, which have not been executed. o Continue is usually associated with an if. o Example: #include<stdio.h> main( )

{ int i,j; for(i=1;i<=2;i++) { for(j=1;j<=2;j++) { if(i= =j) continue; printf(%d%d,i,j); } } } Now, when the value of i= = j, the continue statement takes the control to the for loop by passing rest of the statements pending execution in the for loop inner.

Review Questions 1. Using the arithmetic operators provided in C write a program to that declares and assigns values to the variables a, b and c and then does the following a) b) c) d) Halves the value if a doubles b multiplies c by itself prints out the results of the preceding operations

2. Suppose you had to write a program to compute the volume of a cube. The values you need are three dimensions of a cube. Write a program which stores the three dimensions in three different variables and stores the result in a fourth variable 3. Which of the two operators, multiplication or division has the highest precedence? 4. What is the modulus operator and how does it work? 5. What are the results of the following expressions? a) b) c) d) 17%3 20%4 15%15 6%5

6. Write a program that declares an integer value called num, assigns a value to it and computes and prints out the value of the variable itself, its square and cube. 7. Given that 30.37 inches are equivalent to one meter, write a program that converts a Given number of inches to the equivalent length in centimeters

8. In a program store the five vowels (a, e, i, o, u) in five suitably declared variables. Then print the contents of the variables in a single line 9. Write a program that enables a user to input an integer. The program should state Then whether the integer is evenly divisible by 5 10. Write a program that inputs two numbers a and b and then determines whether the Product of the two numbers is greater than half of a 11. Write a program that reads in two real numbers and tells whether the product of the two numbers is equal to or greater than 100 12. Input three positive integers representing the sides of a triangle and determine whether they form a valid triangle (In a triangle the sum of two sides must be greater than the third side) 13. Write a program that repeatedly asks the user to input a negative or a positive number and then echoes it. When the value 0 is entered the program should terminate 14. Write a program containing a loop that counts from 1 to 1000 using a variable I Which is incremented each time around the loop? The program should print out the value of I every hundred iterations (the output should be 100 200 etc .) 15. Write a program that inputs pairs of integers a and b and divides the larger of the two by the smaller 16. Write a program that prints out n even numbers using a for loop 17. Write a program the reads in a number, then reads in a single digit and determines whether the first number contains the digit. If it does the program should display how many times the digit occurs in the number 18. Write a program to read in ten numbers and the program should display Program is terminating if the user enters number 0 and terminate. 19. Write a menu based program to perform the following arithmetic operations o Addition o Subtraction o Multiplication o Division The user should be given an option of performing the above mentioned operations as many number of times he wishes to and he should be able to quit the program only when he enters his choice to be 0. 20. Write a program the prints the summation of the following series up to n terms 1+4+9+16+25..

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy