10. CP Tutorial solutions 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

BITS PILANI, DUBAI CAMPUS

DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI


FIRST SEMESTER 2024 - 2025

COURSE : COMPUTER PROGRAMMING (CS F111)


COMPONENT : Tutorial# 10

Predict the output of the following programs

1. #include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "Hello", str2[20] = " World";
printf("%s\n", strcpy(str2, strcat(str1, str2)));
return 0;
}

Ans: Hello World

Step 1: char str1[20] = "Hello", str2[20] = " World"; The variable str1 and str2 is declared
as an array of characters and initialized with value "Hello" and " World" respectively.

Step 2: printf("%s\n", strcpy(str2, strcat(str1, str2)));

=> strcat(str1, str2)) it append the string str2 to str1. The result will be stored in str1.
Therefore str1 contains "Hello World".

=> strcpy(str2, "Hello World") it copies the "Hello World" to the variable str2.

2. #include <stdio.h>
#include <string.h>
int main()
{
int val=0;
char str[]="Computer";

val=strcmp(str,"computer");
printf("%d",val);
return 0;
}

Ans: Strings are not equal, hence strcmp will return -32.

CS F111 COMPUTER PROGRAMMING Page 1


3. #include <stdio.h>
#include <string.h>
int main()
{
char str1[]="computer programming",str2[]=".Com";
printf("%s",str1+strlen(str2));
return 0;
}

Ans: uter programming

Look the expression str1+strlen(str2)=> str1+4, since str1 is a character array, and str1+4 will
point 4th index of str1, then uter programming will print.

4. #include <stdio.h>
int main()
{
int i;
char str[]="Programming";
for(i=0;str[i]!='\0';i++)
{
putchar(str[i]);
putchar('*');
}
return 0;
}

Ans: P*r*o*g*r*a*m*m*i*n*g*

5. #include <stdio.h>
#include <string.h>
int main()
{
if( printf("Hello") == strlen("Hello") )
printf("...Friends");
else
printf("...Enemies");
return 0;
}

Ans: Hello...Friends
Statement printf("Hello") will print "Hello" and return 5, and statement strlen("Hello") will
return total number of characters (5) , hence condition is true.

6. #include<stdio.h>
#include<string.h>
CS F111 COMPUTER PROGRAMMING Page 1
int main()
{
char str1[5], str2[5];
int i;
gets(str1);
gets(str2);
i = strcmp(str1, str2);
printf("%d\n", i);
return 0;
}
Ans: Unpredictable integer value

gets() gets collects a string of characters terminated by a new line from the standard input stream
stdin.

The gets(str1) read the input string from user and store in variable str1.

The gets(str2) read the input string from user and store in variable str2.

The code i = strcmp(str1, str2); The strcmp not only returns -1, 0 and +1, but also other negative or
positive values. So the value of i is "unpredictable integer value".

printf("%d\n", i); It prints the value of variable i.

7. char p[20];
char *s = "string";
int length = strlen(s);
int i;
for (i = 0; i < length; i++)
p[i] = s[length — i];
printf("%s",p);

Ans: In the given code, p[20] is declared as a character array and s is a pointer pointing to a string.
The length will be initialized to 6. In the first iteration of for loop (i = 0),

CS F111 COMPUTER PROGRAMMING Page 1


p[i] = s[6-0] and s[6] is ‘\0’
Therefore, p[0] becomes ‘\0’. As discussed, ‘\0’ means end of string. Therefore, nothing is printed as
first character of string is ‘\0’.

8. char c[] = "GATE2011";


char *p =c;
printf("%s", p + p[3] - p[1]) ;

Ans: As given in the question, p points to character array c[] which can be represented as:

As p is a pointer of type character, using pointer arithmetic,


p + p[3] - p[1] = p + 69 - 65 (Using Ascii values of A and E) = p + 4

Now, p + 4 will point to 2, the string starting from 2 till ‘\0’ will be printed which is 2011.

CS F111 COMPUTER PROGRAMMING Page 1


BITS PILANI, DUBAI CAMPUS
DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI
FIRST SEMESTER 2024 - 2025

COURSE : COMPUTER PROGRAMMING (CS F111)


COMPONENT : Tutorial# 9 (SOLUTIONS)

Q1. WACP for the following


a) To find the sum of all the elements of a 2D array (m x n), row-wise and column-
wise and store the same into two 1D arrays rowSum[m], colSum[n].
#define MAX_ROWS 10
#define MAX_COLS 10
main()
{
int a[MAX_ROWS][MAX_COLS] = { { 1, 0, -2, 3, 4 },
{ 2, 6, 8, -5, 10},
{ 5, 7, 9, 2, 1},
{ 3, 2, 1, -6, 3}
};
int rowSum[MAX_ROWS]={0}, colSum[MAX_COLS]={0};
int i, j, nRows=4, nCols=5;

for(i=0; i<nRows; i++) {


for(j=0;j<nCols;j++) {
rowSum[i] += a[i][j];
colSum[j] += a[i][j];
}
}

for(i=0;i<nRows;i++)
printf("%d:", rowSum[i]);
printf("\n");
for(j=0;j<nCols;j++)
printf("%d:", colSum[j]);
printf("\n");
}

b) There are n cities and the cost of travel between the cities are stored in a 2D array
(i.e cost[i][j] cost[j][i] = cost of travel from city i to city j. The program asks the
user for order in which cities are to be visited. Print the total cost of visiting the
cities. For eg if the inp is (2, 4, 5, 1, 3), it means that the user wants to visit the
cities starting from 2 and ending in 3, visiting, 4, 5, & 1 in the order.

CS F111 COMPUTER PROGRAMMING Page 1 of 2


So, total cost = cost[2][4] + cost[4][5] + cost[5][1] + cost[1][3]
#define MAX_CITIES 10
main()
{

CS F111 COMPUTER PROGRAMMING Page 2 of 2


int numCities = 5, i, j;
int cost[MAX_CITIES][MAX_CITIES] =
{ { 0, 2, 5, 6, 1 },
{ 2, 0, 4, 3, 1 },
{ 5, 4, 0, 5, 8 },
{ 6, 3, 5, 0, 7 },
{ 1, 1, 8, 7, 0 }
};
int travelOrder[] = {2, 4, 0, 1, 3}, numCitiesToTravel=5;
int totalCost = 0;

for(i=0; i < numCitiesToTravel-1; i++) {


int a = travelOrder[i];
int b = travelOrder[i+1];
totalCost += cost[a][b];
}

printf("Total Cost = %d\n", totalCost);


}

Q2. WACP for the following using appropriate functions, and the main() function
to test the program.

a) An integer n is divisible by 9, if the sum of the digits is divisible by 9. Write


two function int sumOfDigits (int n); which computes the sum of the digits of n,
and another function int isDivisibleBy9(int n), which checks if the input n is divisible
by 9, using the function sumOfDigits(n).

#include <stdio.h> int isDivisibleby9(int main()


n)
{
{
int sumOfDigits(int int n, flag;
n) int s;
scanf("%d", &n);
{ s =
sumOfDigits(n); flag = isDivisibleby9(n);
int sum=0;
printf("s=%d\n", if (flag)
while(n>0){ s);
printf("n=%d is divisible by 9\n", n);
sum += n%10; if (s%9 == 0)
else
n /= 10; return 1;
printf("n=%d is not divisible by 9\n",
} else n);

return sum; return 0; }

} }

CS F111 COMPUTER PROGRAMMING Page 3 of 2


b) Write a function to void printBin(int n), which prints the binary equivalent of n, eg.
printBin(100) should print 1100100.

void printBin(int n) main()

{ {

int bits[32], count = 0; int n;

while (n){ scanf("%d", &n);

bits[count++] = n%2; printBin(n);

n /= 2; }

for (--count; count >= 0; count--) $ a.out

printf("%d",bits[count]); 10

printf("\n"); 1010

$ a.out

100

1100100

c) Write a function double calc_sqrt(double n); which calculates sqrt by repeatedly


applying the formula NG = 0.5(LG+ N/LG), where LG is the last guess, NG is the
next guess. Assume initial value of LG = 1 and the fuction shoud terminate if
difference between LG and NG is < 0.005.

#include <stdio.h> main()

#include <math.h> {

double a;

double mysqrt(double n) a = mysqrt(4.0);

CS F111 COMPUTER PROGRAMMING Page 4 of 2


{ printf("%f\n",a );

double lg = 1, ng, err; a = mysqrt(10.0);

do { printf("%f\n",a );

ng = 0.5 * (lg + n/lg); a = mysqrt(200.0);

err = fabs(lg-ng); printf("%f\n",a );

lg = ng; }

} while ( err > 0.005);

return ng;

***END***

CS F111 COMPUTER PROGRAMMING Page 5 of 2


BITS PILANI, DUBAI CAMPUS
DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI
FIRST SEMESTER 2024 - 2025

COURSE : COMPUTER PROGRAMMING (CS F111)


COMPONENT : Tutorial# 11 (Solutions)

Q1. Write a C function which performs a linear search of an element in an array


of n elements. If the element is found, it retunes the position of where the
element is found else it returns -1.
int linearsearch(int a[], int n, int e) int linearsearch(int a[], int n, int e)
{ {
int i; int *ap, *aEnd = a + n;

for ( i=0; i<n; i++) for ( ap=a; ap<aEnd; ap++)


if (a[i] == e) return i; if (*ap == e) return ap - a;
return -1; return -1;
} }

Q2. Write a C function which takes an integer array a, and n (no of elements in
array A and finds the maximum and minimum of all the elements in the array
(all of which are passed as parameters to the function).
void minmax(int a[], int n, void minmax(int a[], int n,
int *max, int *min) int *max, int *min)
{ {
int i, m1, m2; int i, m1, m2, *ap, *aEnd = a + n;
m1 = m2 = a[0]; m1 = m2 = *a;
for ( i=0; i<n; i++) { for ( ap=a; ap<aEnd; ap++)
if (a[i] < m1) m1 = a[i]; if (*ap < m1) m1 = *ap;
if (a[i] > m2) m2 = a[i]; if (*ap > m2) m2 = *ap;
} }
*min = m1; *max = m2; *min = m1; *max = m2;
} }

int main()
{
int a[]={2,5,6,1,4};
int max,min;
minmax(a, 5, &max, &min);
printf("\n Max = %d",max);
printf("\n Min = %d",min);

return 0;
}

Q3. Write a C function which takes an integer array a (containing odd & even
nos), and n (no of elements in array A. it separates the odd and even
elements into two new arrays which are also passed as parameters to the
function).
void oddevan(int a[], int n, int main()
int o[], int *nOdd,
int e[], int *nEven) {
{

CS F111 COMPUTER PROGRAMMING Page 1 of 2


int o, no=0, ne=0; int a[]={2,5,6,1,4};
for ( i=0; i<n; i++) {
if (a[i] % 2) o[no++] = a[i]; int od[10],ev[10],i;
else e[ne++] = a[i];
} int nodd,neven;
*nOdd = no; *nEven = ne; oddevan(a, 5, od,&nodd, ev,&neven);
}
printf("\n printing all odds...\n
");

for(i=0;i<nodd;i++)

printf("\t %d",od[i]);

printf("\n printing all evens...\n


");

for(i=0;i<neven;i++)

printf("\t %d",ev[i]);

return 0;

Note: For all of the about write appropriate main program which reads the inputs
and calls the function with appropriate parameters.

Q4. What will be the output of the following code segment?

1. main() 2. main()
{ {
char a[] = { 'A', 'B', 'C', 'D', 'E', 'F'}; int a[5]={58,43,69,76,62};
char *b = a + 4; int i,sum=0;
printf( "%c\n", *(b+1) ); for(i=0; i<5; i++)
printf( "%c\n", b[-2]); sum+=a[i];
printf( "%d\n", a-b ); printf("%d\n",sum/5);
printf( "%c\n", a[*++b - 'A'] ); (70-65) }
} Ans: 61
Ans: Sum of all elements = 308
F Printf is outside for loop, 308/5 = 61 (int div)
C
-4
F
3. #include<stdio.h>
main()
{
int a[5]={5, 1, 15, 20, 25};
int i, j, k=1, m;
i=++a[1];
j=a[1]++;
m=a[i++];
printf("%d %d %d", i, j, m);

CS F111 COMPUTER PROGRAMMING Page 2 of 2


}
Ans: 3 2 15

-------
i = ++a[1]
=> a[1] = 1 So ++a[1] = 2
i =2

a[5]={5, 2, 15, 20, 25};

j = a[1]++
j = a[1] => j = 2
a[1] = a[i] + 1 => a[1] = 3

a[5]={5, 3, 15, 20, 25};

m=a[i++];
m =a[i] => m = a[2] = 13
i = i + 1 => i = 3

So final o/p is

3 2 15

***END***

CS F111 COMPUTER PROGRAMMING Page 3 of 2


BITS PILANI, DUBAI CAMPUS
DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI
FIRST SEMESTER 2024 - 2025

COURSE : COMPUTER PROGRAMMING (CS F111)


COMPONENT : Tutorial# 12 (Solutions)

Q1. What will be the output of the following code segment?

1. 2. int main()
int main() { // Assume address of x is 500 and integer is 4 bytes
{ =
int i = 6, *j, k; int x = 20, *y, *z;
j = &i;
printf("%d\n", i * *j * i + *j); y = &x; z = y; (*y)++; ++(*z); x++;
return 0; *y++; *++z;
} printf("x = %d, y = %d, z = %d \n", x, y, z);
Ans: 222 return 0;
Explanation: }
i * *j * i + *j y=
6 * 6 * 6 + 6 = 216 + 6 = 222 z ? y 500 x 20
&x;
z=y z 500 y 500 x 20
(*y)+
z 500 y 500 x 21
+
++(*z) z 500 y 500 x 22
x++; z 500 y 500 x 23
*y++ z 500 y 504 x 23
*++z z 504 y 504 x 23

x =23, y = 504, z = 504


#include<stdio.h> int main() /* Assume addr(a) = 1000 */
int main() { /* addr(b) = 1001*/
{ char a = 30, b = 5;
int *ptr, b; char *p = &a, *q = &b;
b = sizeof(ptr); printf("%d", p - q);
printf("%d" , b); return 0;
return 0; }
} p 1000 Q 1001 a 30 b 5
Ans: 8 (on linux machine in 333)
(sizeof pointer depends on the processor p-q = (1000 – 1001)/sizeof(char) = (1000-1001)/1
type/compiler options) = -1
int fun(int x)
int main() {
{ x = 30;
int y = 20, x = 10; return x;
x += fun(y); printf("%d %d\n", x, y); }
y += fun(x); printf("%d %d\n", x, y);
fun(int x) x 20
return 0;
}
x = 30 x 30
y= x=10 y 20 x 10

CS F111 COMPUTER PROGRAMMING Page 1 of 2


20
return x x 30
x += fun(y);
x = x + fun(y) y 20 x 40
x=10 + 30
y += fun(x); fun(int x) x 40
y = y + fun(x) y 50 x 40
y=20 + 30 x = 30 x 30

return x x 30

Q2. What will be the output of the following code segment?

1. main()
{
int *x, y = 5;
x = func(&y);
printf("y=%d,*x=%d\n", x,y)
}
int *func(int *a)
{
*a += 10;
return a;
}

Ans: y = 1000, *x = 15

Explanation:
In main()
y = 5 . x = ??

(Assume addr(x) = 1000)


x = func(&y); => func(1000)

(After the func returns)


y = 15 , x = 1000
---------------------

In func()
int *func(int *a) => a = 1000
*a += 10 => *a = *a + 10
=> = *(1000) +
10
=> = 5 + 10
=> = 15
So *a = *(1000) = y (in main)
= 15
return a => return 1000

***END***
CS F111 COMPUTER PROGRAMMING Page 2 of 2
BITS PILANI, DUBAI CAMPUS
DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI
FIRST SEMESTER 2024 - 2025

COURSE : COMPUTER PROGRAMMING (CS F111)


COMPONENT : Tutorial# 7 (SOLUTIONS)

Q1. Draw the flowchart to Read 3 numbers (A, B, C) and check whether the input numbers are
Pythagorean Triplets. Output “TRUE” if they are Pythagorean Triplets, else output “FALSE”. A, B, C
are Pythagorean Triplets, if A2 + B2 = C2.
Eg. A=3, B=4 and C=5, then 32 + 42 = 9 + 16 = 25 = 52, So the answer is “TRUE”.

3+2𝑎
Q2. Draw the flowchart for to compute the sum of series given by the ∑𝑛𝑎=0 −1𝑎 2𝑎

1
Q3. Draw a flowchart to reverse a number

***END***
2
BITS PILANI, DUBAI CAMPUS
DUBAI INTERNATIONAL ACADEMIC CITY, DUBAI
FIRST SEMESTER 2024 - 2025

COURSE : COMPUTER PROGRAMMING (CS F111)


COMPONENT : Tutorial# 4 (SOLUTION)

Answer 1. Answer 2.
main() main()
{ {
char color; int age;
printf("Enter color:");
scanf("%c",&color); printf("Enter age:");
switch(color) scanf("%d",&age);
{
case 'r': if (age > 18)
case 'R': printf("\n RED"); break; printf("MAJOR");
case 'g': else
case 'G': printf("\n Green"); break; printf("MINOR");
case 'b': }
case 'B': printf("\n BLUE"); break;
default: printf("BLACK\n"); /* switch
} switch(age>=18)
{
// if else ladder case 1: printf("\n Major"); break;
/*if(color=='r'|| color=='R') printf("\n Red");case 0: printf("\n Minor"); break;
else if(color=='g'|| color=='G') printf("\n Green");
}*/
else if (color=='b'|| color=='B') printf("\n Blue");
else printf("\n Invalid");*/

Answer 3.
ANS 1: 0 21 ANS 2: 0 ANS 3: x=5 ANS 4: 1
ANS 5: 5 7 ANS 6: c=31 ANS 7: -1 8 ANS 8: 1.500000 1.000000
ANS 9: 10 != 10 ANS 10: c=c

Answer 4. Evaluate whether the following logical expressions will be TRUE or


FLASE?
int a =5,b =0, c = -4, d = 3, e = 8, f =-10;
1
a) a + f > 0 b) c + d == a + b % 3;
c) b d) b || (a + c) && (e - f)
e) d > (a + e++) || (d == c + f) && !(a < c) f) b>1
g) b++ > 1 h) ++b > 1
#include <stdio.h>

main()
{
int a = 5, b = 0, c = -4, d = 3, e = 8, f =-10;

a) a + f > 0;
rel op have lesser precedence to + , so this is treated as (a + f) > 0 )
5 + -10 = -5
-5 > 0 is FALSE

b) c + d == a + b % 3;
c + d = -4 + 3 = 7
a+b%3=5+0%3=5+0=5
7 == 5 is FALSE

c) b;
b is FALSE. ( zero is treated as FALSE )

d) b || (a + c) && (e - f);
This expression is treated as b || ( (a+c) && (e-f) ) as && has higher precedence to ||.
b
b is FALSE. ( zero is treated as FALSE )
( (a+c) && (e-f) ) is evaluated as
i) (a + c) = 5 + -4 = -1 (TRUE)
ii) (e – f) = 8 - -10 = 18 (TRUE)
so ( (a+c) && (e-f) ) is TRUE
finally, FALSE || TRUE is TRUE

e) d > (a + e++) || (d == c + f) && !(a < c);


This expression is treated as
(d > (a + e++) ) || ( (d== (c+f)) && !(a<c) )
i) (d > (a + e++) ) is 3 > (5 + 8) is FALSE (value of e used is 8 and then
incremented to 9)
2
ii) ( (d== (c+f)) && !(a<c) ) is evaluated as
i) (d== (c+f)) is 3 == -4 + -10 is FALSE
ii) !(a<c) is not evaluated (because for && if one operand is FALSE entire
expression is
FALSE)
so overall FALSE || FALSE is FALSE

f) b > 1;
0 > 1 is FALSE

g) b++ > 1;
0 > 1 is FALSE (value of b used is 0 and then incremented to 1)

h)++b > 1;
1 > 1 is FALSE (value of b used is incremented to 1 and then used )
}

Answer 5. a)14 b)18

***END***

You might also like