Tutorial 3 Solutions Tutorial 3 Solutions Explain what is wrong with the following while loops
int i = 0;
while (i < 10)
printf("%d\n", i);
i = i + 1;
Explanation of error: missing braces mean the update statement, i = i + 1, is not part of the loop regardless of the indentation, and the loop is an infinite loop.
int i = 0;
int n = 10;
while (i < n) {
printf("%d\n", i);
n = n + i;
i = i + 1;
}
Explanation of error: loop does terminate because the assignment n = n + i results in n growing faster than i. Design and write a program that reads in an integers and prints out that many asterisks, each on a new line. Implement one version using a while loop and another version using a for loop
./asterisks
Please enter an integer: 5
*
*
*
*
*
#include
int main(void) {
int i, n;
printf("Please enter an integer: ");
scanf("%d", &n);
i = 0;
while (i < n) {
printf("*\n");
i = i + 1;
}
return 0;
}
#include
int main(void) {
int i, n;
printf("Please enter an integer: ");
scanf("%d", &n);
i = 0;
for (i=0; i < n i++) {
printf("*\n");
}
return 0;
}
Consider an algorithm for the sum of squares given input integer k. The program will print the number in the first column with their squares (power of 2) in the second. Using pseudo code, write an algorithm for printing the numbers from k down to 1 together with their squares. You can assume k is 10.
//Declare and initialise counter to 10
// While i is greater than or equal to 1
// Print counter and its square
// Decrement value of counter
Translate the pseudo code you have just written into a functioning C program. Use a for or a while loop.
#include
int main(void) {
//Declare and initialise counter to 10
int i = 10;
// While i is greater than or equal to 1
while (i >= 1) {
// Print counter and its square
printf("The square of %d is %d\n", i, i * i);
// Decrement value of counter
i = i - 1;
}
return 0;
}
#include
int main(void) {
int i;
// While i is greater than or equal to 1
for (i = 10; i >= 1; i = i - 1) {
// Print counter and its square
printf("The square of %d is %d\n", i, i * i);
}
return 0;
}
Modify your C code so that your program, after printing a number and its square on a line, prints the string "Number is even" if the number (not its square) is even and otherwise prints the string "Number is odd" if the number is odd. Use the printf format strings like "%4d" to format the columns
#include
// Let's use symbolic constants this time
#define MAX 10
#define MIN 1
int main(void) {
int i;
for (i = MAX; i >= MIN; i = i - 1) {
printf("The square of %4d is %4d.", i, i * i);
if ((i % 2) == 1) {
printf(" Number is odd\n");
} else {
printf(" Number is even\n");
}
}
return 0;
}
Consider the following code
#include
int main(void) {
int number;
int row, column;
// Obtain input
printf("Enter number: ");
scanf("%d", &number);
for (row = 1; row <= number; row = row + 1) {
for (column = 1; column <= number; column = column + 1) {
printf("*");
}
printf("\n"); // Start a new line
}
return 0;
}
What is the output if the user types in the number 5?
Enter number: 5
*****
*****
*****
*****
*****
Modify the program so that it prints out a triangle that consists of number asterisks eg
Enter number: 5
*
**
***
****
*****
#include
int main(void) {
int number;
int row, column;
// Obtain input
printf("Enter number: ");
scanf("%d",&number);
row = 1;
while (row <= number) {
column = 1;
while (column <= number) {
if (column <= (number - row)) {
printf(" ");
} else {
printf("*");
}
column = column + 1;
}
printf("\n");
row = row + 1;
}
return 0;
}
What is an array? An array is a collection of elements with the same data type. Each element is accessed providing the name of the array and an index. The index range is from 0 through to N-1, where N is the number of elements in the array. This is also known as zero-based indexing. Give an expression that sums the first and third element of an array called numbers?
numbers[0] + numbers[2]
Note third element is accessed using numbers[2] since C uses zero based indexing. If an array is declared as int numbers[20]; and your program assigns a value to each element in the array, what is the problem with the statement x = numbers[20]; ? Because arrays use zero-based indexing, accessing the element indexed 20 is accessing the 21st item in the array. This will access a value that is not within the boundaries of the array. Behaviour of a program that does this is undefined and it is possible, for example, that it will cause the program to terminate. Sometimes it will retrieve the value of another variable. How can you easily detect such errors before they have mysterious effects? You can use dcc to compile your program instead of gcc to help find these errors. It shows you what lines your code goes over the array bounds as your program is running.
~rz9280/bin/dcc -o prog prog.c
How would you declare a variable squares to be an array of integers with 15 elements?
int squares[15];
Write a C code fragment to store, in each element of this array, the square of the index of that element, e.g., squares[5] would contain the value 25.
#include
#define ELEMENTS 15
int main(void) {
int squares[ELEMENTS];
int i;
// The next two lines is what the question asks you to do
for (i = 0; i < ELEMENTS; i = i + 1) {
squares[i] = i * i;
}
// Let's print the array to check
for (i = 0; i < ELEMENTS; i = i + 1) {
printf("squares[%d] has the value %d\n", i, squares[i]);
}
return 0;
}
Write a C program which reads 5 numbers then reads another number and prints how many times that number occurred in the first 5. For example:
a.out
Enter 5 numbers: 1 3 1 3 1
Enter a number: 1
1 occurred 3 times in the 5 numbers read
#include
#define N_NUMBERS 5
int main(void) {
int x[N_NUMBERS], i, j, match, count;
printf("Enter %d numbers: ", N_NUMBERS);
i = 0;
while (i < N_NUMBERS) {
scanf("%d", &x[i]);
i = i + 1;
}
count = 0;
printf("Enter a number: ");
scanf("%d", &match);
j = N_NUMBERS - 1;
while (j >= 0) {
if (x[j] == match) {
count = count + 1;
}
j = j - 1;
}
printf("%d occurred %d times in the %d numbers read\n", match, count, N_NUMBERS);
return 0;
}
Write a C program that calculates the dot-product of two vectors of integers. Reminder you calculate the dot product by multiplying corresponding elements and summing the result. For example:
./dot_product
Enter vector 1 of 5 integers: 1 3 1 3 2
Enter vector 2 of 5 integers: 2 1 2 1 2
Their dot-product is 14.
#include
#define VECTOR_LENGTH 5
int main(void) {
int vector1[VECTOR_LENGTH];
int vector2[VECTOR_LENGTH];
int i, dotProduct;
printf("Enter vector 1 of %d positive numbers: ", VECTOR_LENGTH);
for (i = 0; i < VECTOR_LENGTH; i = i + 1) {
scanf("%d", &vector1[i]);
}
printf("Enter vector 2 of %d positive numbers: ", VECTOR_LENGTH);
for (i = 0; i < VECTOR_LENGTH; i = i + 1) {
scanf("%d", &vector2[i]);
}
dotProduct = 0;
for (i = 0; i < VECTOR_LENGTH; i = i + 1) {
dotProduct = dotProduct + vector1[i] * vector2[i];
}
printf("Their dot-product is %d.\n", dotProduct);
return 0;
}
Write a C program which reads numbers until end-of-input is reached and then prints the middle number. So if 9 numbers were entered the program should print the 5th number entered. And if 27 numbers were entered the program should print the 14th number entered. If an even number of numbers is entered there are two middle numbers, print the second of them. For example if 8 numbers are entered, prints the 5th. You can assume at most 10,000 numbers will be entered.
#include
#define MAX_NUMBERS 100000
int main(void) {
int numbers[MAX_NUMBERS], howMany, returnValue, middleIndex;
howMany = 0;
returnValue = 1;
while (returnValue == 1) {
returnValue = scanf("%d", &numbers[howMany]);
howMany = howMany + 1;
}
howMany = howMany - 1;
middleIndex = howMany / 2;
printf("%d\n", numbers[middleIndex]);
return 0;
}
Extra Exercises for practice Design and write a program that reads an integer and prints the following pattern:
./diagonal
Enter an integer: 10
*
*
*
*
*
*
*
*
*
*
#include
int main(void) {
int n;
int row, column;
printf("Enter an integer:\n");
scanf("%d", &n);
row = 0;
while (row < n) {
column = 0;
while (column < row) {
printf(" ");
column = column + 1;
}
printf("*\n");
row = row + 1;
}
return 0;
}
Write a program diamond.c which lets the user enter an integer n and then prints a diamond shape with n rows and n stars in each row, like this:
$ ./diamond
Enter n ? 5
*****
*****
*****
*****
*****
/*
diamond.c
*/
#include
int main( void )
{
int r,c,n;
printf("Enter n ? ");
scanf("%d",&n );
for( r=1; r <= n; r++ ) {
// number of spaces = (row number)-1
for( c=1; c < r; c++ ) {
printf(" ");
}
// same number of stars in each row
for( c=0; c < n; c++ ) {
printf("*");
}
printf("\n");
}
return 0;
}
Design and write a program that reads two integers (height x length) and prints a rectangular, asterisk outline with the specified dimensions, for example:
./rectangle
Enter rectangle height and length: 3 5
* * * * *
* *
* * * * *
#include
int main(void) {
int height, length;
int row, column;
printf("Enter rectangle height and length: ");
scanf("%d", &height);
scanf("%d", &length);
row = 0;
while (row < height) {
column = 0;
while (column < length) {
// If the index is on one of the edges, print *.
// Otherwise, print a space.
if (row == 0 || row == height - 1 || column == 0 || column == length - 1) {
printf("*");
} else {
printf(" ");
}
column = column + 1;
}
printf("\n");
row = row + 1;
}
return 0;
}
For the program in the previous question, consider and discuss the ways in which you would test their correct behaviour. Then extend the program to include error checking for, and handling of, invalid input.
#include
int main(void) {
int height, length;
int row, column;
int valuesRead;
printf("Enter rectangle height and length: ");
valuesRead = scanf("%d%d", &height, &length);
if (valuesRead != 2) {
printf("Two integers must be supplied as input.\n");
} else if (height < 1 || length < 1) {
printf("It is impossible to draw a rectangle with the given height and length.\n");
} else {
row = 0;
while (row < height) {
column = 0;
while (column < length) {
// If the index is on one of the edges, print *.
// Otherwise, print a space.
if (row == 0 || row == height - 1 || column == 0 || column == length - 1) {
printf("*");
} else {
printf(" ");
}
column = column + 1;
}
printf("\n");
row = row + 1;
}
}
return 0;
}
Design and write a program that an integers and prints a diamond, asterisk outline with the specified side length, for example:
./diamond
Enter side length: 3
*
* *
* *
* *
*
./diamond
Enter side length: 6
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
#include
int main(void) {
int side;
int row, column;
printf("Enter side length: ");
scanf("%d", &side);
row = 0;
while (row < side * 2 - 1) {
column = 0;
while (column < side * 2 - 1) {
if (row <= (side - 1)) {
if (column == (side - 1) - row || column == (side - 1) + row) {
printf("*");
} else {
printf(" ");
}
} else {
if (column == row - (side - 1) || column == 3 * (side - 1) - row) {
printf("*");
} else {
printf(" ");
}
}
column = column + 1;
}
printf("\n");
row = row + 1;
}
return 0;
}