Chapter 5 - Let Us C
Write a program to print all the ASCII values and their equivalent characters using a while loop. The ASCII values vary from 0 to 255.
#include <stdio.h>
int main(){
for(int i=0;i<=255;i++){
printf("The ASCII value of %c is %d\n",i,i);
}
return 0;
}
Step 1: Include the `stdio.h` header file for standard input/output functions like `printf`.
Step 2: The `main` function is the entry point of the program.
Step 3: A `for` loop is used to iterate through ASCII values from 0 to 255 (inclusive). The loop variable `i` represents the ASCII value.
Step 4: Inside the loop, `printf` is used to print the character corresponding to the ASCII value `i` (using the `%c` format specifier) and its decimal representation (using the `%d` format specifier). The `\n` creates a new line after each character and its ASCII value are printed.
Step 5: The loop continues until `i` becomes greater than 255.
Step 6: The program returns 0, indicating successful execution.
Step 2: The `main` function is the entry point of the program.
Step 3: A `for` loop is used to iterate through ASCII values from 0 to 255 (inclusive). The loop variable `i` represents the ASCII value.
Step 4: Inside the loop, `printf` is used to print the character corresponding to the ASCII value `i` (using the `%c` format specifier) and its decimal representation (using the `%d` format specifier). The `\n` creates a new line after each character and its ASCII value are printed.
Step 5: The loop continues until `i` becomes greater than 255.
Step 6: The program returns 0, indicating successful execution.
Write a program to print out all Armstrong numbers between 1 and 500. If sum of cubes of each digit of the number is equal to the number itself, then the number is called an Armstrong number.
#include <stdio.h>
int main(){
int d1,d2,d3,sum;
printf("Armstrong numbers between 1 to 500 are :\n");
for(int i=1;i<=500;i++){
d1 = i%10;
d2 = (i/10)%10;
d3 = i/100;
sum = (d1 * d1 * d1) + (d2 * d2 * d2) + (d3 * d3 * d3);
if(sum == i){
printf("%d\n",i);
}
}
return 0;
}
Step 1: Include the `stdio.h` header file for standard input/output functions like `printf`.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `d1`, `d2`, `d3`, and `sum` to store the digits and their sum.
Step 4: Print a message indicating that the program will output Armstrong numbers between 1 and 500.
Step 5: A `for` loop iterates through numbers from 1 to 500 (inclusive). The loop variable `i` represents the current number being checked.
Step 6: Inside the loop:
Step 8: The program returns 0, indicating successful execution.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `d1`, `d2`, `d3`, and `sum` to store the digits and their sum.
Step 4: Print a message indicating that the program will output Armstrong numbers between 1 and 500.
Step 5: A `for` loop iterates through numbers from 1 to 500 (inclusive). The loop variable `i` represents the current number being checked.
Step 6: Inside the loop:
- Extract the last digit of `i` using the modulo operator (`%`) and store it in `d1`: `d1 = i % 10;`
- Extract the second digit from the right using integer division and the modulo operator, and store it in `d2`: `d2 = (i / 10) % 10;`
- Extract the leftmost digit (for 3-digit numbers) using integer division and store it in `d3`: `d3 = i / 100;`
- Calculate the sum of the cubes of the digits and store it in `sum`: `sum = (d1 * d1 * d1) + (d2 * d2 * d2) + (d3 * d3 * d3);`
- Check if `sum` is equal to the original number `i`.
- If they are equal (it's an Armstrong number), print the number `i` followed by a newline character.
Step 8: The program returns 0, indicating successful execution.
Write a program for a matchstick game being played between the
computer and a user. Your program should ensure that the
computer always wins. Rules for the game are as follows:
- There are 21 matchsticks.
- The computer asks the player to pick 1, 2, 3, or 4 matchsticks.
- After the person picks, the computer does its picking.
- Whoever is forced to pick up the last matchstick loses the game.
#include <stdio.h>
int main(){
int user,comp,matchsticks=21;
printf("Welcome to the Matchstick Game!\n");
printf("Rules: Pick 1, 2, 3, or 4 matchsticks. The one who picks the last matchstick loses.\n");
while(matchsticks>1){
printf("\nThere are %d matchsticks left. Pick 1, 2, 3, or 4: ", matchsticks);
scanf("%d", &user);
if (user < 1 || user > 4 || user > matchsticks) {
printf("Invalid move! Pick between 1 and 4 matchsticks.\n");
continue;
}
comp = 5 - user;
matchsticks -= (user + comp);
printf("Computer picks %d matchsticks.\n", comp);
}
printf("\nOnly 1 matchstick left. You have to pick it. You lose! Computer wins!\n");
return 0;
}
Step 1: Include the `stdio.h` header file for standard input/output functions like `printf` and `scanf`.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `user`, `comp`, and `matchsticks`. Initialize `matchsticks` to 21, representing the starting number of matchsticks.
Step 4: Print a welcome message and the rules of the matchstick game.
Step 5: A `while` loop continues as long as there is more than one matchstick left (`matchsticks > 1`).
Step 6: Inside the loop:
Step 8: The program returns 0, indicating successful execution.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `user`, `comp`, and `matchsticks`. Initialize `matchsticks` to 21, representing the starting number of matchsticks.
Step 4: Print a welcome message and the rules of the matchstick game.
Step 5: A `while` loop continues as long as there is more than one matchstick left (`matchsticks > 1`).
Step 6: Inside the loop:
- Print the number of remaining matchsticks and prompt the user to pick 1, 2, 3, or 4 matchsticks. Store the user's input in the `user` variable using `scanf`.
- Validate the user's input. If the input is less than 1, greater than 4, or greater than the number of remaining matchsticks, print an "Invalid move" message and use `continue` to skip the rest of the current iteration and go back to the beginning of the loop.
- Calculate the computer's move. The computer's strategy is to always pick enough matchsticks so that the sum of the user's and computer's picks is 5. This ensures that the computer will always leave a multiple of 5 plus 1 matchsticks. `comp = 5 - user;`
- Update the number of remaining matchsticks by subtracting the user's and computer's picks: `matchsticks -= (user + comp);`
- Print the number of matchsticks the computer picked.
Step 8: The program returns 0, indicating successful execution.
Write a program to enter numbers till the user wants. At the end it should display the count of positive, negative and zeros entered.
#include <stdio.h>
int main(){
int pos = 0, neg = 0, zero = 0, num;
char ch;
do {
printf("Enter an integer: ");
if (scanf("%d", &num)){
(num > 0) ? pos++ : (num == 0) ? zero++ : neg++;
} else {
printf("Invalid input! Not an integer.\n");
scanf("%*s");
continue;
}
printf("Enter 'n' to quit, otherwise press Enter to continue: ");
fflush(stdin);
scanf("%c", &ch);
} while (ch != 'n');
printf("Positive = %d\nNegative = %d\nZero = %d\n", pos, neg, zero);
return 0;
}
Step 1: Include the `stdio.h` header file for standard input/output functions like `printf` and `scanf`.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `pos`, `neg`, and `zero` to count positive, negative, and zero numbers, respectively. Initialize all to 0.
Step 4: Declare an integer variable `num` to store the user's input and a character variable `ch` to store the user's choice to continue or quit.
Step 5: A `do-while` loop continues until the user enters 'n'.
Step 6: Inside the loop:
Step 8: The program returns 0, indicating successful execution.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `pos`, `neg`, and `zero` to count positive, negative, and zero numbers, respectively. Initialize all to 0.
Step 4: Declare an integer variable `num` to store the user's input and a character variable `ch` to store the user's choice to continue or quit.
Step 5: A `do-while` loop continues until the user enters 'n'.
Step 6: Inside the loop:
- Prompt the user to enter an integer.
- Use `scanf` to read the integer and store it in the `num` variable. Crucially, the return value of `scanf` is checked. `scanf` returns the number of items successfully read. If the user enters something that's not an integer, `scanf` will return 0.
- If `scanf` successfully reads an integer (returns 1):
- Use a ternary operator to increment the appropriate counter: `(num > 0) ? pos++ : (num == 0) ? zero++ : neg++;`
- Otherwise (if `scanf` fails to read an integer):
- Print an "Invalid input" message.
- Use `scanf("%*s");` to clear the invalid input from the input buffer. The `%*s` format specifier tells `scanf` to read a string but discard it.
- Use `continue;` to skip the rest of the current iteration and go back to the beginning of the loop.
- Prompt the user to enter 'n' to quit or press Enter to continue.
- Use `fflush(stdin);` to clear the input buffer. This is important, especially on some systems, to prevent leftover characters (like a newline) from being read in the next iteration of the loop.
- Use `scanf("%c", &ch);` to read the character entered by the user.
Step 8: The program returns 0, indicating successful execution.
Write a program to receive an integer and find its octal equivalent.
#include <stdio.h>
int main(){
int num,octal = 0,place=1;
printf("Enter the number : ");
scanf("%d",&num);
while(num!=0){
octal += (num%8)*place;
num /= 8;
place *= 10;
}
printf("The equivalent octal of the given number is %d",octal);
return 0;
}
Step 1: Include the `stdio.h` header file for standard input/output functions like `printf` and `scanf`.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `num`, `octal`, and `place`. Initialize `octal` to 0 (to store the octal equivalent) and `place` to 1 (to represent the place value in the octal number).
Step 4: Prompt the user to enter a number and store it in the `num` variable using `scanf`.
Step 5: A `while` loop continues as long as `num` is not 0.
Step 6: Inside the loop:
Step 8: The program returns 0, indicating successful execution.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `num`, `octal`, and `place`. Initialize `octal` to 0 (to store the octal equivalent) and `place` to 1 (to represent the place value in the octal number).
Step 4: Prompt the user to enter a number and store it in the `num` variable using `scanf`.
Step 5: A `while` loop continues as long as `num` is not 0.
Step 6: Inside the loop:
- Calculate the last digit of `num` in base 8 using the modulo operator (`% 8`) and multiply it by the current `place` value. Add the result to `octal`: `octal += (num % 8) * place;`
- Perform integer division on `num` by 8 to remove the last digit (in base 8): `num /= 8;`
- Multiply `place` by 10 to move to the next higher place value (in the resulting octal number): `place *= 10;`
Step 8: The program returns 0, indicating successful execution.
Write a program to find the range of a set of numbers entered through the keyboard. Range is the difference between the smallest and biggest number in the list.
#include <stdio.h>
int main(){
int n, num, max, min;
printf("Enter how many numbers are there in the set : ");
scanf("%d", &n);
if(n <= 0)
{
printf("Invalid input! The set must contain at least one number.\n");
return 1;
}
printf("Enter the number: ");
scanf("%d", &num);
min = max = num;
n--;
while (n != 0)
{
printf("Enter the number : ");
scanf("%d", &num);
if (num < min)
{
min = num;
}
if (num > max)
{
max = num;
}
n--;
}
printf("Range = %d", max - min);
return 0;
}
Step 1: Include the `stdio.h` header file for standard input/output functions like `printf` and `scanf`.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `n`, `num`, `max`, and `min`.
Step 4: Prompt the user to enter the number of elements in the set and store it in `n` using `scanf`.
Step 5: Check if `n` is less than or equal to 0. If it is, print an error message and exit the program with a return value of 1 (indicating an error).
Step 6: Prompt the user to enter the first number and store it in `num` using `scanf`. Initialize both `min` and `max` with this first number, as it is initially both the smallest and largest.
Step 7: Decrement `n` by 1 since the first number has already been processed: `n--;`.
Step 8: A `while` loop continues as long as `n` is not 0 (i.e., there are more numbers to process).
Step 9: Inside the loop:
Step 11: Print the calculated range using `printf`.
Step 12: The program returns 0, indicating successful execution.
Step 2: The `main` function is the entry point of the program.
Step 3: Declare integer variables `n`, `num`, `max`, and `min`.
Step 4: Prompt the user to enter the number of elements in the set and store it in `n` using `scanf`.
Step 5: Check if `n` is less than or equal to 0. If it is, print an error message and exit the program with a return value of 1 (indicating an error).
Step 6: Prompt the user to enter the first number and store it in `num` using `scanf`. Initialize both `min` and `max` with this first number, as it is initially both the smallest and largest.
Step 7: Decrement `n` by 1 since the first number has already been processed: `n--;`.
Step 8: A `while` loop continues as long as `n` is not 0 (i.e., there are more numbers to process).
Step 9: Inside the loop:
- Prompt the user to enter the next number and store it in `num` using `scanf`.
- Check if the current number `num` is less than the current minimum `min`. If it is, update `min` with `num`.
- Check if the current number `num` is greater than the current maximum `max`. If it is, update `max` with `num`.
- Decrement `n` by 1 to keep track of the remaining numbers.
Step 11: Print the calculated range using `printf`.
Step 12: The program returns 0, indicating successful execution.
Comments