Computer Programming Skills and Concepts Solutions for Tutorial 2

Shared by:
Categories
-
Stats
views:
3
posted:
3/4/2010
language:
English
pages:
2
Document Sample

```							Computer Programming: Skills and Concepts
Solutions for Tutorial 2 (week 4) — October 12-15, 2009
Here are answers in .pdf. The associated ﬁle week4sol.tar contains the actual programs
written.

Loops
Consider the following code:

int n = 5;
for(int i=0;i<2;i++) {
printf("computing %d minus %d... ",i,n);
n = i - n;
printf("n is %d\n",n);
}

What is printed on the screen?

Answer: One way to answer this is to code up the program and test it (though by week 4,
most students should be able to work out the output from the logical structure of the code).
Note in compiling, the gcc compiler will have trouble, because it is not up-to-date to allow
the declaration of a variable inside a for. So we must either
change the for(int i=0; ...) to for(i=0; ...) (having declared int i; above this)
or else we have to add the option -std=c99 to our gcc compilation, as follows:
gcc -Wall -std=c99 tutw4a.c
In the provided program tutw4a.c, I have taken the ﬁrst option.
The output you will get (ie, after compiling) is:

[fletcher]mcryan: ./a.out
computing 0 minus 5 ...n is -5
computing 1 minus -5 ...n is 6

Programming
The mathematical operation n! is deﬁned as n! = (n − 1)! ∗ n for n > 0 and 0! = 1. Write a
program that asks a user for a number n, complains if that number is negative, and computes
and outputs n! otherwise.

answer: Overleaf is the code (program is named tutw4b.c)
#include <stdio.h>
#include <stdlib.h>

int main(void) {
int n, flg;
int i = 2, fac = 1;
printf("Please input a non-negative integer: ");
flg = scanf("%d", &n);
if (flg == 1) {
if (n < 0)
printf("That was a negative integer. Bye ...\n");
else {
while(i <= n) {
fac = i*fac;
i = i+1;
}
printf("The factorial of %d is %d.\n", n, fac);
}
}
else
printf("ERROR: This was non-integer input.\n");
return EXIT_SUCCESS;
}

Programming with scanf
Write a program which takes in a series of integers from the screen and calculates the sum of
these integers. The user indicates that (s)he is ﬁnished by inputting any non-integer input.
note: You will need to examine the returned value of scanf (as discussed at the end of the
lecture on Thurs, 8th October) in order to do this.
It is tricky, but satisfying (if you work out how).

answer: here is the code (program is named tutw4c.c)

#include <stdio.h>
#include <stdlib.h>

int main(void) {
int n, flg;
int sum = 0;
printf("Please input a series of integers separated by whitespace.\n");
printf("Indicate you are finished using any non-integer value.\n");
flg = scanf("%d", &n);
while (flg ==1) {
sum = sum+n;
flg = scanf("%d", &n);
}
printf("The sum of the integers is %d.\n", sum);
return EXIT_SUCCESS;
}

2

```
Related docs