counting 7s in an integer c
To count the number of 7s in an integer in the C programming language, you can follow these steps:
Step 1: Initialize Variables
- Declare and initialize a variable
count
to keep track of the number of 7s found in the integer. - Declare and initialize a variable
num
to store the integer input.
int count = 0;
int num;
Step 2: Get User Input
- Use the
scanf
function to get an integer input from the user and store it in thenum
variable.
scanf("%d", &num);
Step 3: Count the 7s
- Use a loop to iterate through each digit of the integer.
- Extract the last digit of the integer using the modulo operator
%
and store it in a variabledigit
. - Check if
digit
is equal to 7. If it is, increment thecount
variable. - Divide the integer by 10 to remove the last digit.
- Repeat the above steps until the integer becomes 0.
while (num != 0) {
int digit = num % 10;
if (digit == 7) {
count++;
}
num /= 10;
}
Step 4: Display the Result
- Use the
printf
function to display the number of 7s found in the integer.
printf("The number of 7s in the integer is: %d\n", count);
That's it! The above steps outline a simple algorithm to count the number of 7s in an integer in the C programming language.
[[SOURCE 6]]