Upload
ashutosh-mohanty
View
225
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Continuing series in C programming tutorial. For more basics refer to Session 1 and Session 2.
Citation preview
APTITUDE TRAINING
(Technical Part)(Technical Part)
At 6At 6thth Semester of Graduate ProgrammeSemester of Graduate Programmein all Branches of Engineering / Technologyin all Branches of Engineering / Technology
Instructor : Dr. Somsubhra Gupta, IT Dept. JISCEInstructor : Dr. Somsubhra Gupta, IT Dept. JISCEVenue: Dr. B.C. Roy Auditorium.Venue: Dr. B.C. Roy Auditorium.
Technical Aptitude Training JISCE 2015 1
Technical Session Technical Session 33(03 02 2015(03 02 2015))(03.02.2015(03.02.2015))
(Loop)(Loop)(Loop)(Loop)
Technical Aptitude Training JISCE 2015 2
Session Objective
• To use the while repetition statement to t t t t i t dlexecute statements in a program repeatedly.
• Counter-controlled repetition and sentinel-t ll d titicontrolled repetition.
• Additional repetition control structuresf-for
-do…while
Technical Aptitude Training JISCE 2015 3
Th hil SThe while StatementRepetition structure
Programmer specifies an action to be repeated while some condition remains truePseudocode:
While there are more items on my shopping listPurchase next item and cross it off my listPurchase next item and cross it off my list
while loop repeated until condition becomes falseExample:Example:
int product = 2;
while ( product <= 1000 )d 2 * d
Technical Aptitude Training JISCE 2015 4
product = 2 * product;
Common Programming error
Not providing the body of a while statement with an p g yaction that eventually causes the condition in the while to become false. Normally, such a repetition structure will never terminate—an error called an “infinite loop.”
Spelling the keyword while with an uppercase W as in While (remember that C is a case-sensitive language). All f C’ d k d h hil if dAll of C’s reserved keywords such as while, if and else contain only lowercase letters.
Technical Aptitude Training JISCE 2015 5
Flow ChartFlow Chart
Technical Aptitude Training JISCE 2015 6
Counter Controlled RepetitionCounter Controlled Repetition
Counter-controlled repetitionCounter-controlled repetitionLoop repeated until counter reaches a certain valueDefinite repetition: number of repetitions is knownDefinite repetition: number of repetitions is known Example: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quizgrades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.q
Technical Aptitude Training JISCE 2015 7
Sample source code8 1 /* Fig. 3.6: fig03_06.c
2 Class average program with counter-controlled repetition */
3 #include <stdio.h>
4
Outline
Sample source code
4 5 /* function main begins program execution */
6 int main( void )
7 {
8 int counter; /* number of grade to be entered next */
i d / d l /
fig03_06.c
(1 of 2 ) 9 int grade; /* grade value */
10 int total; /* sum of grades input by user */ 11 int average; /* average of grades */ 12 13 /* initialization phase */
(1 of 2 )Counter to control while loop
14 total = 0; /* initialize total */ 15 counter = 1; /* initialize loop counter */ 16 17 /* processing phase */ 18 while ( counter <= 10 ) { /* loop 10 times */
Initialize counter to 1
while loop iterates as long as 18 while ( counter <= 10 ) { / loop 10 times /
19 printf( "Enter grade: " ); /* prompt for input */ 20 scanf( "%d", &grade ); /* read grade from user */ 21 total = total + grade; /* add grade to total */ 22 counter = counter + 1; /* increment counter */
} / d hil /
p gcounter <= 10
Increment the counter
Technical Aptitude Training JISCE 2015 8
23 } /* end while */
Increment the counter
Sample source code
924 25 /* termination phase */ O li
Sample source code
25 /* termination phase */ 26 average = total / 10; /* integer division */ 27 28 printf( "Class average is %d\n", average ); /* display result */ 29
Outline
fig03 06.c
Calculate the average
30 return 0; /* indicate program ended successfully */ 31 32 } /* end function main */ Enter grade: 98
fig03_06.c
(2 of 2 )
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57 Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
Technical Aptitude Training JISCE 2015 9
Repetition EssentialsRepetition EssentialsLoop
Group of instructions computer executes repeatedly whileGroup of instructions computer executes repeatedly while some condition remains true
Counter-controlled repetitionpDefinite repetition: know how many times loop will executeControl variable used to count repetitions
Sentinel-controlled repetitionIndefinite repetitionU d h b f titi t kUsed when number of repetitions not knownSentinel value indicates "end of data"
Technical Aptitude Training JISCE 2015 10
Counter Controlled repetitionCounter Controlled repetition
Counter-controlled repetition requires• The name of a control variable (or loop counter)The initial value of the control variable• An increment (or decrement) by which the control variable is modified each time through the lloop• A condition that tests for the final value of the
t l i bl (i h th l i h ldcontrol variable (i.e., whether looping should continue)
Technical Aptitude Training JISCE 2015 11
Counter Controlled repetition
Example: int counter = 1; // initialization
Counter Controlled repetition
int counter = 1; // initialization
while ( counter <= 10 ) { // repetition condition
printf( "%d\n", counter );
++counter; // increment; //
}
The statementint counter = 1;int counter 1;
Names counterDefines it to be an integerReserves space for it in memorySets it to an initial value of 1
Technical Aptitude Training JISCE 2015 12
f Sfor Statements
Technical Aptitude Training JISCE 2015 13
Using an incorrect relational operator or using an incorrect initial or final value of a loop counter in the pcondition of a while or for statement can cause off-by-one errors.
Using the final value in the condition of a while or for statement and using the <= relational operator willfor statement and using the <= relational operator will help avoid off-by-one errors. For a loop used to print the values 1 to 10, for example, the loop-continuation , p , pcondition should be counter <= 10 rather than counter < 11 or counter < 10.
Technical Aptitude Training JISCE 2015 14
for Repetition statementfor Repetition statement
Format when using for loopsfor ( initialization; loopContinuationTest; increment )
statement
E ample:Example: for( int counter = 1; counter <= 10; counter++ )
printf( "%d\n", counter );
Prints the integers from one to ten
Technical Aptitude Training JISCE 2015 15
for Repetition statementfor Repetition statementFor loops can usually be rewritten as while loops:
initialization;initialization;while ( loopContinuationTest ) {
statement;increment;increment;
} Initialization and increment
C b d liCan be comma-separated listsExample:
for (int i = 0, j = 0; j + i <= 10;for (int i 0, j 0; j + i < 10; j++, i++)
printf( "%d\n", j + i );
Technical Aptitude Training JISCE 2015 16
for Repetition statementfor Repetition statement• Arithmetic expressions
- Initialization loop-continuation and increment can containInitialization, loop continuation, and increment can contain arithmetic expressions. If x equals 2 and y equals 10
for ( j = x; j <= 4 * x * y; j += y / x)
i i l f ( j 2 j 80 j 5 )is equivalent to for ( j = 2; j <= 80; j += 5 )• Notes about the for statement:
- "Increment" may be negative (decrement)Increment may be negative (decrement)- If the loop continuation condition is initially false
The body of the for statement is not performedControl proceeds with the next statement after the forstatement
- Control variable often printed or used inside for body, but not
Technical Aptitude Training JISCE 2015 17
Control variable often printed or used inside for body, but not necessary
for Flow Chartfor Flow Chart
Technical Aptitude Training JISCE 2015 18
d hil i ido-while repetition statementThe do…while repetition statement
Si il hSimilar to the while structureCondition for repetition only tested after the body of th l i f dthe loop is performed
All actions are performed at least once
Format:Format:do {
statement; Example (letting counter = 1):do {
} while ( condition );do {
printf( "%d ", counter );
} while (++counter <= 10);
Prints the integers from 1 to 10
Technical Aptitude Training JISCE 2015 19
d hil fl hdo-while flow chart
Technical Aptitude Training JISCE 2015 20
Practice Code
• Calculate sum & average of N numbers using Array
C l l i d d d i i f N b• Calculate mean, variance, standard deviation of N numbers
• Calculate Sum of digits of a given number
• Prime numbers below 200
• Find Length of String
• Find maximum value
Technical Aptitude Training JISCE 2015 21
Assignment : Day 3
1. List all the prime numbers between two given numbers. 2. Write a program, that accepts a integer from the user and print the integer with reverse digits. For eg: rev (1234) = 4321.g g g ( )3. Find the sum of the digits of a given number. Find the digit of convergence4. Given a number, determine its absolute value.,5. Given three numbers, determine whether they can form the sides of a triangle.6. Given a number, determine whether it is a valid year and if so, whether6. Given a number, determine whether it is a valid year and if so, whether it is a leap year.7. Given two numbers, determine whether they are valid years, and if so, list all leap years between the two years (both included)
Technical Aptitude Training JISCE 2015 22
list all leap years between the two years (both included).