week-4_ws-sol c programming

21
Birla Institute of Technology & Science, Pilani Second Semester 2015-2016, Computer Programming [CS F111] Week #4 Tutorial Sheet #1 Date:___/_____/________ Name: ______________ _____________ID: ______________________ Lec Sec/Lab Sec:______/_____ Section 1 Concept of Loops: Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied, i.e., loops are used in performing repetitive work in programming. Suppose you want to execute some code/s 10 times. Without loops you will end up writing the same code repeatedly. Let’s understand the meaning of it. Example 1: Write a program to print integers starting from -3 to 3. #include <stdio.h> /* Program to print integers between -5 and 5 */ int main(){ int i = -3; printf("%d ", i); i = i + 1; printf("%d ", i); i = i + 1; printf("%d ", i); i = i + 1; printf("%d ", i); i = i + 1; printf("%d ", i); i = i + 1;

Upload: hemanth

Post on 13-Jul-2016

215 views

Category:

Documents


0 download

DESCRIPTION

This file makes you understand a sub topic of c language

TRANSCRIPT

Page 1: Week-4_ws-sol c programming

Birla Institute of Technology & Science, PilaniSecond Semester 2015-2016, Computer Programming [CS F111]

Week #4 Tutorial Sheet #1 Date:___/_____/________

Name: ______________ _____________ID: ______________________ Lec Sec/Lab Sec:______/_____

Section 1 Concept of Loops:

Loops causes program to execute the certain block of code repeatedly until some conditions are satisfied, i.e., loops are used in performing repetitive work in programming.

Suppose you want to execute some code/s 10 times. Without loops you will end up writing the same code repeatedly. Let’s understand the meaning of it.

Example 1: Write a program to print integers starting from -3 to 3.

#include <stdio.h>/* Program to print integers between -5 and 5 */int main(){ int i = -3; printf("%d ", i); i = i + 1; printf("%d ", i); i = i + 1; printf("%d ", i); i = i + 1; printf("%d ", i); i = i + 1; printf("%d ", i); i = i + 1; printf("%d ", i); i = i + 1; printf("%d ", i); return 0;}

Page 2: Week-4_ws-sol c programming

Now imagine if you have to print integers from -1000 to 1000. Is it possible to code in the above fashion? Obviously no!

Hence loops are control structures using which you can perform the same computation by writing that code/s only one time and repeat the execution 7 times.

In C there are three different kinds of loops. They are1. While loop2. For loop3. Do-while loop

Section 2 While Loop

The flowchart of while loop will look as follows:

The while loop checks whether the test expression (often called condition of the loop) is true or not. If it is true, code/s inside the body of while loop is executed, that is, code/s inside the braces { } are executed. Then again the test expression is checked whether test expression is true or not. This process continues until the test expression becomes false.

The corresponding syntax in C language is as follows

while(test expression){

statement1;statement2;…

}

So let’s rewrite the code of the above program and appreciate that how it can help us saving the effort to type same computation repeatedly.

Page 3: Week-4_ws-sol c programming

Example 2: Write a program to print integers starting from -3 to 3.

#include <stdio.h>/* Program to print integers between -5 and 5 */int main(){ int i = -3; while(i != 4){ printf("%d ", i); i = i + 1; } return 0;}

Let’s try few more examples:

Example 3: Design the flowchart to print all the positive integers starting from 0 to a user provided positive integer N.

Page 4: Week-4_ws-sol c programming

Exercise 1: Write the C code for the example 3.

#include <stdio.h>/* Program to print integers between 0 and N */int main(){ int i = 0, N; printf(“ Please enter the value of N “); scanf(“%d”,&N); while(i <= N){ printf("%d ", i); i = i + 1; } return 0;}

Example 4 Write the flow chart to print the following pattern

***********************************

Page 5: Week-4_ws-sol c programming

Example 5: Write the code for the example 4.

#include <stdio.h>/* Program to print patterns*/int main(){ int i = 0; while(i < 5){ printf("******\n"); i = i + 1; } return 0;}

Let’s look into another example, where you have to compute the following expression

1 + 3 + 5 + 7 + ……. +(2n-1)

Now note that you can solve it mathematically and reduce it to a simpler expression of n. For a fixed value of n we can get our desired answer. But we want to actually compute this summation without using the mathematically computed expression.

Example 6. Write the flowchart to find the following summation. S = 1 + 3 + 5 + 7 + …+ (2n-1)

Page 6: Week-4_ws-sol c programming

Example 7 Write a program to compute the summation

S = 1 + 3 + 5 + 7 + …+ (2n-1)

#include <stdio.h>/* Program to compute 1 + 3 + 5 +..+(2n-1)*/int main(){ int i = 1, sum = 0, N; printf(“ Please enter the value of N “); scanf(“%d”,&N); while(i <= (2*n-1)){ sum = sum + i; i = i + 2; } printf(“ Sum = %d”, sum); return 0;}

So we have completed few examples and it is exercise time.

Exercise 2: Write a program to play the following two players game

Player 1 will provide a number to the program which Player 2 will not see. Make sure that the provided number is between 1-10 else quit the program.Next Player 2 will keep on guessing the numbers till there is a match with the number provided by Player1. Program will output the number of attempts made by Player2.

Page 7: Week-4_ws-sol c programming

(A) Draw the flowchart for this program.

Page 8: Week-4_ws-sol c programming

(B) Write C code for the above problem.

#include <stdio.h>#include <stdlib.h>/* Program to implement the guess game between two players */int main(){ int p1,p2,count=1; printf(" Player1 please enter a value between 1-10 "); scanf("%d",&p1); //read value provided by player1 printf(" Player2 please enter a value between 1-10 to guess Player1's value "); scanf("%d",&p2); //read value provided by player2 for the first time

//compare the values entered by p1 and p2 while(p1 != p2){ printf(" Player2 please enter a value between 1-10 to guess Player1's value "); scanf("%d",&p2); //if the attempt fails, player 2 enters another value count++; //increment the number of attempts }

//print finally the number of attempts taken by player2 printf(" Player2 have taken %d attempts", count);

return 0;}

Page 9: Week-4_ws-sol c programming

Exercise 3a: Write a flowchart to print the multiplication table of a given number.

Exercise 3b: Write the C code for the above stated problem.

#include <stdio.h>/* Program to print the multiplication table of a number*/int main(){ int N, i = 1; printf(" Please enter the value of N whose multiplication table you want"); scanf("%d",&N); //read the number whose multiplication is to be printed while(i <=20){ printf("%d x %d = %d \n", N, i, N*i); i++; } return 0;}

Page 10: Week-4_ws-sol c programming

Birla Institute of Technology & Science, PilaniSecond Semester 2015-2016, Computer Programming [CS F111]

Week #4 Tutorial Sheet #2 Date:___/_____/________

Name: ______________ _____________ID: ______________________ Lec Sec/Lab Sec:______/_____

Section 2 Tracing a loop

An important aspect of programming is to be able to trace your program. By trace we mean that the state (or value) of each variable should be tracked after each C statement. A correct tracing is a great tool because it helps you to check the correctness of your program. Tracing while statement can be tricky because the details of while statements can be quite complicated. Great care is needed to make sure that unexpected results during tracing are due to a mistake in the while-statement design and not due to erroneous tracing! A systematic, though tedious way to trace while statements is to use the “cross ‘em out” technique. For each iteration of the body of the while, the values of the variables from the previous iteration are crossed out and new values recorded beside the old.

Example 8 Trace the following piece of code where variables x, y, and m are of type int.

Statements Variable valuesx = 21y = 15m = 2917

while (y != 0) {x = 21 15 6y = 15 6 3m = 2917 6 3

m = x % y;x = 21 15 6y = 15 6 3m = 6 3 0

x = y;x = 15 6 3y = 15 6 3m = 6 3 0

y = m;x = 15 6 3y = 6 3 0m = 6 3 0

}x = 3y = 0m = 0

Page 11: Week-4_ws-sol c programming

Exercise 4 Complete the tracing table for the given piece of code

Statements Variable valuesi=1;a=0;b=1;c=5672;n=4;

while (i <= n) {i=a=b=c=n=

c = a + b;i=a=b=c=n=

a = b;i=a=b=c=n=

b = c;i=a=b=c=n=

i++;i=a=b=c=n=

}i=a=b=c=n=

Page 12: Week-4_ws-sol c programming

Section 2 Some common Pitfalls

If you have only one statement after the while then you may skip putting the curly braces just like in if statements. If the loop condition is satisfied then that single statement will be executed.For exampleint x=0;while( x < 20)

x = x + 5;

If you think later that some more statements needs to be added then you may commit silly mistakes such as

int x=0, y=1;while( x < 20)

x = x + 5;y++;

whereas your intention was to write int x=0, y=1;while( x < 20){

x = x + 5;y++;

}

Perhaps as a beginner programmer it is a better idea to always put curly braces even if there is one single statement.

Note that there is no semicolon right after the while statement. If by mistake you put a semicolon then the compiler will understand that there is only one single statement after the while statement even though that statement is empty.

For exampleint count = 0;while(count != 10); --(1){ count = count +1;}

The semicolon in statement (1) will mean that there are no statements after the while condition is satisfied and hence the loop will run forever.

Page 13: Week-4_ws-sol c programming

One of the most common pitfalls is getting into an infinite loop. In the above given example, since the value of count (also called loop variable) is not going to change because of that semicolon in statement (1) the condition of the loop will always remain true and hence the loop will not terminate. Such non terminating loops are called infinite loops. Thus you should be always careful that the loop variable is changed inside the body of the loop such that the loop terminates.

Exercise 5: Find errors in the following code snippets.

a) Infinite loop because count wll never be equal to 10 int count = 0; while(count != 10){

count = count + 3; }

b) Mistake is using an assignment operator n while condition int a = 2;while( a = 2){

printf(“ Give a new value of a “);scan(“%d “, &a);

}

c) Semicolon after while() int m = 100, n = 0;while(n = 0);{

if (m < 10){n= 2;

} m = m – 10;

}

Exercise time!

Exercise 4a Write a flowchart to find if a given number is prime.

Page 14: Week-4_ws-sol c programming

Exercise 4b Write C code for the above stated problem

#include <stdio.h>

/* Program to check if a number is prime*/int main(){ int N, i = 2, Notprime = 0; printf(" Please enter the number"); scanf("%d",&N);

//check if any integer from 2 to N/2 divides N //then N will be marked as prime while(i <= N/2){ if(N%i == 0){ Notprime = 1; } i++; }

if(Notprime == 0 || N == 2) { printf("%d is prime", N); } else{ printf("%d is not prime", N); }

return 0;}

Page 15: Week-4_ws-sol c programming

Exercise 5 Do the following by taking N as input. First attempt each question by using the pow function provided in <math.h> library i.e. pow(2,a) will return the value of 2a. Please note that you have to use the flag –lm while compiling your program if you have used math.h library.

a) WAP to find the sum of following series.

∑a=0

N 12a

/* Author: Objective: To compute the summation (1/2^a), a going from 0 to N*/#include <stdio.h>#include<math.h>int main(){ int N=0, a=0, prod = 1, i = 0; //input and output to be stored double sum = 0.0; //read the value of N from the user printf("Please enter the value of N:"); scanf("%d",&N); //check if N >= 0 if(N < 0){ printf("\n The input N should be >= 0. Please retry."); } else{ //loop to compute sum while(a <= N){ //loop to compute 2^a

sum = sum + (1/pow(2,(double)a));a++;

} printf("\n Sum = %f", sum); } return 0;}

Page 16: Week-4_ws-sol c programming

b) Modify the above program (part a) to get the sum of following series:

∑a=0

N 3+2a2a

#include <stdio.h>#include <math.h>int main(){ int N=0, a=0, prod = 1, i = 0; //input and output to be stored double sum = 0.0; //read the value of N from the user printf("Please enter the value of N:"); scanf("%d",&N); //check if N >= 0 if(N < 0){ printf("\n The input N should be >= 0. Please retry."); } else{

//loop to compute sum while(a <= N){

sum = sum + ((3+(2*a))/pow(2,(float)a)); a++;

} printf("\n Sum = %f", sum); } return 0;}

c) Modify the above program (part b) to get the sum of following series:

Page 17: Week-4_ws-sol c programming

∑a=0

N

(−1)a 3+2a2a

#include <stdio.h>#include <math.h>int main(){ int N=0, a=0, prod = 1, i = 0; //input and output to be stored double sum = 0.0; //read the value of N from the user printf("Please enter the value of N:"); scanf("%d",&N); //check if N >= 0 if(N < 0){ printf("\n The input N should be >= 0. Please retry."); } else{ //loop to compute sum while(a <= N){

if(a%2 == 0){ sum = sum + ((3+(2*a))/pow(2.0,(float)a)); } else{ sum = sum - ((3+(2*a))/pow(2.0,(float)a)); } a++; } printf("\n Sum = %f", sum); } return 0;}

Page 18: Week-4_ws-sol c programming

Exercise 6: Write a program to print the following pattern.

******** ** ** ** ** ********

#include <stdio.h>#include <math.h>int main(){ int i=0; printf(“*******\n”) while(i < 5){

printf(“* *”); i++; } printf(“*******\n”) return 0;}