SKTN Solutions For C Part 2 - Online Article
Introduction
The tutorial series "SKTN Solutions for C" is continued with this tutorial. In this part 2 of the series, we will take a little bit more challenging problems are taken. I hope you will enjoy. So, let us once again delve into the ocean of C.
Problem 6: Write a program for a matchstick game being played between computer and a user. The program should ensure that the program always wins. Rules for the game:
a) There are 21 matchsticks.
b) The computer asks the player to pick 1, 2, 3 or 4 matchsticks.
c) After the person picks, the computer does its picking.
d) Whoever is forced to pick the last matchstick loses the game.
There are total 21 matchsticks to be picked and first chance is of user. Now, if for every chance, the sum of matchsticks picked by user and the computer becomes 5, then after 4 chances, only one matchstick will be left and next chance will be of user. In this case, user will lose as he has only one option of picking that one matchstick. Thus, every time the computer will win. Let us C the code now,
#include <stdio.h> #include <conio.h> void main() { int remaining = 21, user, computer; while(remaining != 0) { printf("\nPick sticks: 1, 2, 3 or 4: "); scanf("%d",&user); remaining = remaining - user; if(remaining == 0) printf("\nComputer Wins"); else { computer = 5 - user; remaining = remaining - computer; printf("Computer picks %d",computer); printf("\nSticks Remaining: %d",remaining); if(remaining == 0) printf("\nYou won"); } } getch(); }
The remaining matchsticks are taken in remaining which is initially set to 21. Number of matchsticks picked by user and computer are stored in user and computer. The while loop keeps running until all matchsticks are picked up. In the loop, user is asked to pick the matchsticks (1, 2, 3 or 4). The number of matchsticks that user has picked are then deducted from remaining matchsticks. Now if no matchstick remains, the computer wins as the user has picked the last one. Otherwise, computer picks the matchsticks using the following formula:
No. of matchsticks computer picks = 5 - matchsticks user has picked.
The number of matchsticks that computer has picked are then deducted from remaining matchsticks. Now if no matchstick remains, the user wins as the computer has picked the last one. However this never happens according to the logic explained above the code.
In this way, the computer always wins. The getch() function is optional and is used just to halt the screen until the user hits the enter key.
Problem 7: Write a program to receive an integer and find its octal equivalent without using array.
The number system we use in our daily life is decimal number system. This number system is of base 10. This means that after every 10 counting one digit increases. But the octal number system is of base 10, i.e. after every 8 counting one digit increases. To understand, see the conversion table below:
Decimal | Octal | Decimal | Octal | Decimal | Octal | ||
---|---|---|---|---|---|---|---|
0 | 0 | 8 | 10 | 16 | 20 | ||
1 | 1 | 9 | 11 | 17 | 21 | ||
2 | 2 | 10 | 12 | 18 | 22 | ||
3 | 3 | 11 | 13 | 19 | 23 | ||
4 | 4 | 12 | 14 | 20 | 24 | ||
5 | 5 | 13 | 15 | 21 | 25 | ||
6 | 6 | 14 | 16 | 22 | 26 | ||
7 | 7 | 15 | 17 | 23 | 27 |
The standard way to convert decimal to octal is to divide the decimal number by 8 and note the remainder. We continue this process until the number becomes zero. The remainders we have noted in this process are then read in opposite direction and we get the octal equivalent. See example in the accompanying figure. Here, the number 501 is in decimal which is successively divided by 8 and the remainder 5, 6 and 7 are noted. When these are read in opposite direction, it makes 765, which is the octal equivalent of 501.
To solve this problem, we will use % (modulus) operator of C. This operator divides first number by second and returns the remainder. For example, 10%3 = 1 and 15%4 = 3. Now, we will use this % (modulus) operator to obtain the remainder on dividing by 8. As we do not have any way to read in opposite direction, we will use a trick. Every remainder will be multiplied by an appropriate factor of 1, 10, 100 and 1000 and so on. This will place the digits at their appropriate place. If we do not use this, then we will get the reverse of the octal equivalent because the digits are extracted in right to left order. Let us C the code now,
#include <stdio.h> #include <conio.h> void main() { int number = 755, current_digit, octal = 0, factor = 1; while(number != 0) { current_digit = number % 8; current_digit = current_digit * factor; octal = octal + current_digit; number = number / 8; factor = factor * 10; } printf("Octal is %d",octal); getch(); }
Here, the decimal number is taken in number and octal is used for storing the octal equivalent of the number. The octal is initialized as 0. In the program, until number becomes zero, the following processes happen:
- The digit at the right-most position in the number is divided by 8 and its remainder is stored in current_digit.
- The current_digit is then multiplied by a factor. This factor is 1 at the first time, 10 at the second time, and 100 at the third time and so on.
- This current_digit is then added to octal.
- The number is divided by 8 so that its value gets reduced by a factor of 8 and next digit can be extracted.
- The factor is multiplied by 10 to achieve the fact discussed in step (b) above.
In this way, the octal equivalent digits are obtained and we get the result in octal which is shown on the screen by printf() function. The getch() function is optional and is used just to halt the screen until the user hits the enter key. To get the octal equivalent of a different number, just change the value of number.
Problem 8: Write a program to produce the following output using loop:
ABCDEFGFEDCBA
ABCDEF FEDBCA
ABCDE EDBCA
ABCD DCBA
ABC CBA
AB BA
A A
This series to be printed has three parts:
- In the left: Print letters starting from A.
- In the middle: Print spaces
- In the right: Print letters ending on A.
Also there is one another problem. In the first two lines, there is only a difference of G being replaced by a space. This makes the solution a little more complicated. We will be using two concepts here:
- When '\b' is used in a printf, it deletes the last character printed on the screen.
- char can be used as an integer for a range of -128 to +127. Thus using char in a for loop will not generate any error.
- Every alphabet (A, B, C, etc.) has an ASCII code. This code uniquely identifies an alphabet. 'A' has ASCII code 65, 'B' has 66, 'C' has 67 and so on. This makes use of char in a loop sensible. If we initialize the loop with a char having value 'A' or 65, then on incrementing we will obtain the series of alphabet B, C, D, etc.
Let us C the code now,
#include <stdio.h> #include <conio.h> void main() { char left, right, limit; int spaces = 0, middle; for(limit = 'G'; limit >= 'A'; limit--) { for(left = 'A'; left <= limit; left++) printf("%c",left); if(limit == 'G') printf("\b"); for(middle = 1; middle < spaces; middle++) printf(" "); spaces = spaces + 2; for(right = limit; right >= 'A'; right--) printf("%c",right); printf("\n"); } getch(); }
Now, we have taken three char, left for running the loop for left part of the series, right for running the loop for right part of the series. Middle and spaces are used for running the middle part of the series and limit is used for running the main loop in which all other loops are contained.
The main loop runs 7 times. It starts from 'G' and keeps on running until limit becomes less than 'A'. Each time the value of limit is decremented by one. So, the loops runs as, 'G' then 'F' then 'E' then 'D' then 'C' then 'B' then 'A'. At every time this loop runs, the left, middle and right loop runs. At the end of the loop a printf is used which prints '\n' to take the cursor to the next line. This way, in total 7 lines are printed on the screen.
Now the left loop starts from 'A' and runs to the value of limit. Every time the value of left is incremented by one and is printed on the screen.
In the middle section of the main loop, if the value of limit is 'G' (i.e. the first time when the main loop runs), a '\b' is printed which deletes the last character printed. This solves the problem of G in the first two rows.
Next is the middle loop, which is quite simple. Here spaces are printed on the screen. Every time the main loop runs, the number of spaces to be printed is increased by two.
Now the right loop starts from value of limit and runs to 'A'. Every time the value of right is decremented by one and is printed on the screen.
In this way the required series is printed on the screen. The getch() function is optional and is used just to halt the screen until the user hits the enter key. To get more rows, just change the vale of limit when initializing the main loop.
Problem 9: Write a program to produce the following output:
1
2 3
4 5 6
7 8 9 10
The series to be printed has mainly two problems:
- The numbers to be printed, i.e. 1, 2, 3, 4 etc.
- The spaces to be inserted at appropriate places, i.e. between numbers and at the beginning of the line.
To solve the first problem, just analyze the series. In every line or row, the number of digits printed is equal to the number of that row from top. For example in the first line only one number (1) is printed, on second line two numbers (2, 3) are printed, on third line three numbers (4, 5, 6) are printed and so on.
Now, considering the second problem, after every number a space is given and at the beginning of the line the number of spaces to be printed can be calculated by the formula:
No. of spaces at beginning of a line = Total lines - Line number of that line
Let us C the code now,
#include <stdio.h> #include <conio.h> void main() { int rows = 4, number = 1, i, j; for(i=1; i<=rows; i++) { for(j=1; j<=rows-i; j++) printf(" "); for(j=1; j<=i; j++) { printf("%d ",number); number = number + 1; } printf("\n"); } getch(); }
The total number of rows/lines to be printed is stored in rows. The variable number contains the number that is to be printed on the screen. I and j are used to run the loops. The main for loop runs for the number of rows. Every time the main for loop runs, the following processes happen:
- Spaces are printed (rows - i) times at the beginning of each row by first loop of j inside the main loop.
- In the second j loop, the current value of number is printed with a space. This j loop i times. The value of number is incremented every time.
- A '\n' is used to take the cursor to the next line.
In this way, the required series is printed on the screen. The getch() function is optional and is used just to halt the screen until the user hits the enter key. To get more rows, just change the value of rows.
Problem 10: Write a program to calculate sum of first 7 terms of the following series that calculates natural logarithm:
Except the first term of this series, every term of the series uses the power of some integer. To tackle this problem we have a power function in C. This power function is found in math.h header file. The power function acts as below,
pow(number, power of the number)
So, if we write pow(3, 4) the result will be 3*3*3*3 = 81. The logic of the rest of the series is straightforward; we have to just use the formula given, calculate each term and add them to get the result. Let us C the code now,
#include <stdio.h> #include <conio.h> #include <math.h> void main() { int i; float x=5; float sum = (x-1)/x; for(i=2; i<=7; i++) sum = sum + (pow((x-1)/x,i)/2); printf("Sum of series is = %f",sum); getch(); }
In the program we have included the header file math.h for using the power function. The variable x and sum are taken as float as they will contain fractional values. The value of first term is calculated right at the time of declaration of sum. Later in the loop, that is run from 2 to 7, every time the current term of the series is calculated and is then added to the sum. At last this sum is printed using the printf function. In this way, the required series is printed on the screen. The getch() function is optional and is used just to halt the screen until the user hits the enter key. To get more terms of the series, just change the value which is compared to i in the loop from 7 to the desired value.
About the Author:
No further information.
Related Online Articles:
Comments
No comment yet. Be the first to post a comment. |