Setting a Limit on loops and calculating palindromes in C programming - c

So the goal of this code is to convert a user number into a palindrome. If the number is not a palindrome, calculate the number+reversed number until it becomes a palindrome. If still not a palindrome, take the sum of the last number and it's reverse and add that together, for a maximum of 10 tries.
int main()
{
int n;
int reverse = 0; //initial value will be 0
int temp; //temporary variable
//Check if number is a palindrome===============================
printf("Enter an integer: ");
scanf_s("%d", &n);
temp = n; //Make input number have a temporary variable
while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp % 10;
temp = temp / 10;
}
//Check if number entered by user and it's reverse number is equal
if (reverse == n)
printf("%d\t1, reverse is %d\n", n, reverse); //Is a palindrome
else
printf("%d\t0, reverse is %d\n", n, reverse); //Not a palindrome
//==========================================================================
//Keep adding numbers until it reaches a palindrome
int sum;
while (n /= reverse)
{
sum = n + reverse;
n++;
}
if (reverse == sum)
printf("%d it works", sum, reverse);
else
("%d didn't work", sum, reverse);
I haven't worked on the limit yet. But my question is how would I go about adding the reverse and user's number, then doing the sum + its reverse? Also what kind of loop is best for this kind of question?

What you can do is write the while loop for generating the reverse of number(consider as loop2) in another while loop(consider as loop 1) which breaks(terminates) when the the number is a palindrome.If the given number is not palindrome then you change the number as number=number+reverse.If you want to try for 10 tries then you can add a another condition for loop 1 by taking a counter. Below is the code that I wrote.
#include<stdio.h>
int main()
{
int n;
int count=0; //taking counter for number of trials
int reverse=0; //initial value will be 0
int temp; //temporary variable
printf("Enter an integer: ");
scanf("%d", &n);
while (count<10)
//count less than 10 condition makes the max. no. of trials equal to 10
{
temp=n; //assigning a temporary variable to n
reverse=0;
//Finding the reverse of the number n===============================
while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp % 10;
temp = temp / 10;
}
//Check if number entered by user and it's reverse number is equal
if (reverse == n){
printf("\n%d\t1, reverse is %d\n", n, reverse);
//Is a palindrome
break;
/*break condition makes the loop 1 to terminate if the number 'n' is palindrome*/
}
else
printf("\n%d\t0, reverse is %d\n", n, reverse);
//Not a palindrome
//================================================================
//Keep adding numbers until it reaches a palindrome
n=n+ reverse;
count++;
}
}

Related

How can I print highest value in an array?

I have scanf in a array I need to print the highest array stored
the problem is it print 0 every print
#include <stdio.h>
int main()
{
int n; // To input how many set of number to be entered
int order_number; // To count the numbers being entered
int length; // To count how many numbers in the array to be used in the last print
int max; // max computations later in last print
float num[100], sum = 0.0, average;
printf("Enter how numbers to be counted: ");
scanf("%d", &n); // asks the user how many numbers to be entered
while (n > 100 || n < 1)
{
printf("The entered number could not handle 100 above or below 1\n"); // shows if the user enters below 1 and above 100
printf("Please enter a number again: "); // asks the user to enter a number again
scanf("%d", &n); // asks the user how many numbers to be entered
}
for (order_number = 0; order_number < n; ++order_number) // loop syntax for counting numbers being entered
{
printf("%d. Enter number: ", order_number + 1); // prints the counting number being entered
scanf("%f", &num[order_number]); // asks the user for a number then store to the array
sum += num[order_number]; // adds all the number from the array
}
average = sum / n; // computes the average by adding a group of numbers and then dividing by the count of those numbers.
printf("The average is %.2f\n", average);
// Problem start here
length = sizeof(num) / sizeof(num[0]);
max = num[100];
for (int i = 0; i < length; i++)
{
if (num[i] > max)
max = num[i];
}
printf("Largest element present in given array: %d\n", max);
return 0;
}
#include <stdio.h>
int main()
{
int n; // To input how many set of number to be entered
int order_number; // To count the numbers being entered
int length; // To count how many numbers in the array to be used in the last print
int max; // max computations later in last print
float num[100], sum = 0.0, average;
printf("Enter how numbers to be counted: ");
scanf("%d", &n); // asks the user how many numbers to be entered
while (n > 100 || n < 1)
{
printf("The entered number could not handle 100 above or below 1\n"); // shows if the user enters below 1 and above 100
printf("Please enter a number again: "); // asks the user to enter a number again
scanf("%d", &n); // asks the user how many numbers to be entered
}
for (order_number = 0; order_number < n; ++order_number) // loop syntax for counting numbers being entered
{
printf("%d. Enter number: ", order_number + 1); // prints the counting number being entered
scanf("%f", &num[order_number]); // asks the user for a number then store to the array
sum += num[order_number]; // adds all the number from the array
}
average = sum / n; // computes the average by adding a group of numbers and then dividing by the count of those numbers.
printf("The average is %.2f\n", average);
max = num[0];
for (int i = 1; i < n; i++) // computation on finding the highest number in the array using loop
{
if (num[i] > max)
max = num[i];
}
printf("The largest number in the array is %d\n", max);
return 0;
}
max = num[100]; - you are looking at the 101st element of a 100 element array, indexed from zero. If you're lucky, you don't get a segmentation fault or some other memory error, since you're looking past the end of the array, but you're still going to get something random that happened to be in that memory location.
To iterate over the array, you then use all elements of the array, since you limit the loop by length - rather than 'n', which you've set to the number of used elements in the array. So you're also including length - n elements at the end that were never initialised to a useful value.

C program to read 'n' numbers and find out the sum of odd valued digits of each number and print them

i am new to programing, i want to know that how we can find the odd digits in a number.
the condition in this program is we should only use concept of arrays.I tried a code for this as follows:
#include <stdio.h>
int main()
{
int A[50],i,x,y,n,sum=0;
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
for(i=0;i<n;i++){
x=A[i]%10;
if(x%2!=0)
sum=sum+x;
A[i]=A[i]/10;
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
but in this the code is checking for only one digit of the first number in the loop and then next time it is going to check the digit of second number.
so, i need to write a code to check all digits in the number and then it goes to next number and check all digits and should continue the same process in the loop.So, for this how should i modify my code?
You were missing a loop that would iterate through every digit of A[i] - the inner while loop below,
#include <stdio.h>
int main()
{
int A[50], i, x, y, n, sum=0;
printf("How many numbers will you input?\n");
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0; i<n; i++) {
scanf("%d",&A[i]);
}
for(i=0; i<n; i++) {
sum = 0;
while (A[i] > 0) {
x = A[i]%10;
if(x%2 != 0) {
sum = sum + x;
}
A[i] = A[i]/10;
}
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
The exact algorithm for iterating through each digit in a nice form can be found in this post - although for a different language. Here, apart from the while loop, you also need to reset the sum each time unless you want a cumulative sum over all provided numbers.
Note that I changed the formatting a bit - more space, extra braces, and a message about what you're prompting the user to input.
int temp;
int sum = 0;
temp = number;
do {
lastDigit = temp % 10;
temp = temp / 10;
sum += (lastDigit %2 != 0) ? lastDigit : 0;
} while(temp > 0);

File Redirection Input inC

I'm creating a program that takes numbers from a separate .txt file and turns them into a factorial and then finds the amount of times each prime has occurred in the factorial.
I have been working on this code for the last few days and after many hours i keep getting stuck on the same thing, it will compile with no errors but when I try file redirection to get an input from another file it stops and acts like it is asking for input on an endless loop.
Any help would be much appreciated!
#include <stdio.h>
int Storage_array[5];
int current_prime, next_prime, factorial, prime_count, prime_number, num, factorial_current, factorial_next_num, current_number, total_number; //various variables used in program
int find_prime_count(int factorial, int prime_number); //3 functions declared below main()
int find_next_prime(int factorial, int current_prime);
int is_prime(int num);
int a, b, c; //utility varbles
main()
{
if((a=scanf("%d", &c)) == EOF) //checks to see if file is empty
{
return 0;
}
for(b=0; b<c; b++)
{
if((a=scanf("%d", &c)) == EOF) //checks to see if reached end of the file
{
break;
}
scanf("%d", &Storage_array[b]); //paces values from file into the storage array
printf("%d! = ", Storage_array[b]); //formatting the output
for(c=0;c<5;c++)
{
if(c=0) //creating a base case
{
current_prime = 2;
}
else
{
current_prime = next_prime; //updates the current prime after the base case
next_prime = find_next_prime(Storage_array[b], current_prime); //performes the outside functions that fine the next prime number within the factorial
prime_count = find_prime_count(Storage_array[b], current_prime); //performs outside function that finds the number of the current prime within the factorial
printf("(%d^%d)",current_prime ,next_prime); //prints the results in proper format
}
}
printf("\n"); //spaces between factorial numbers
}
}
int is_prime(int num) //function that determines if the input number is a prime number or not
{
for(a=2; a<num; a++) //base case knowing lowest prime is 2
{
if (num % a == 0) //determines if the number is a prime number using remainder when divided by various numbers
{
return a; //returns the number if it is prime
}
}
}
int find_prime_count (int factorial, int prime_number)
{
for(a=0;a<factorial;a++)//tests all possible prime numbers under the input factorial
{
if(a=0) //base case for lowest possible prime in factorial
{
factorial_current = 1;
factorial_next_num = 1;
}
else
{
factorial_current = (a*factorial_next_num);
}
if(factorial_current % prime_number == 0) //determines if the prime number fits into current factorial number
{
current_number = (factorial_current/prime_number); //finds number of times prime number fits in
total_number = (total_number + current_number); //adds total amount of times that prime has fit within the factorial
}
}
return total_number;
}
int find_next_prime (int factorial, int current_prime) //function that determines the next prime within the factorial
{
for(a=current_prime;a<factorial;a++) //checks all possible primes within the factorial
{
if (factorial % current_prime == 0) //determines if the number is a prime number using remainder when divided by various numbers
{
return a; //returns the number if it is next prime
}
}
}
the text file i have has the following content and is called input.txt
7
67
9
43
0

C Program to list Armstrong Numbers upto 1000

#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int i , n , sum=0, rem;
clrscr();
for(i=1;i<=1000;i++)
{
while(i!=0)
{
rem = i%10;
sum = sum + pow(rem,3);
i = i / 10;
}
if(i == sum)
printf("\n %d", i);
}
getch();
}
I tried the above code for printing Armstrong Numbers upto 1000 . The output that I got was a list of zeros. I am not able to find the error in the code. Thanks in advance :)
You should keep a copy of i, so that it could be kept for comparison with the sum variable.
As of now, you compare sum and i, at every step when i has become 0.
You should use a temp variable to store value of i(before performing i/=10).
Also, you can't keep i in the while-loop as it would always be 0, and hence post increment will have no effect on it. You should need another temporary variable, say div.
And, you should finally print temp.
Also, an Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.
So, for 1000, you need to caclculate the 4th power.
int temp,div;
for(i=1;i<=1000;i++)
{
temp = i;
div = i;
while(div!=0)
{
rem = div%10;
sum = sum + pow(rem,3);
div = div / 10;
}
if(temp == sum)
printf("\n %d", temp);
}
NOTE :- Probably you're using Turbo C compiler(check that header <conio.h>), which you shouldn't(you should avoid it). You should use GCC(on Linux system), CodeBlocks IDE(on Windows).
You can also use this code to print Armstrong number in given range.
#include<stdio.h>
int main()
{
int num,r,sum,temp;
int min,max;
printf("Enter the minimum range: ");
scanf("%d",&min);
printf("Enter the maximum range: ");
scanf("%d",&max);
printf("Armstrong numbers in given range are: ");
for(num=min;num<=max;num++)
{
temp=num;
sum = 0;
while(temp!=0)
{
r=temp%10;
temp=temp/10;
sum=sum+(r*r*r);
}
if(sum==num)
printf("%d ",num);
}
return 0;
}

Specific digit count in an integer in C

For example: if user input is 11234517 and wants to see the number of 1's in this input, output will be "number of 1's is 3. i hope you understand what i mean.
i am only able to count number of digits in an integer.
#include <stdio.h>
int main()
{
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0)
{
n/=10;
count++;
}
printf("Digits in your number: %d",count);
return 0;
}
maybe arrays are the solution. Any help would be appreciated. thank you!
You don't need array. Try something like this:
int countDigits(int number, int digitToCount)
{
// Store how many times given number occured
int counter = 0;
while(number != 0)
{
int tempDigit = number % 10;
if(tempDigit == digitToCount)
counter++;
number = number/10;
}
return counter;
}
So, you've already found that you can convert 1234 to 123 (that is, remove the least significant digit) by using number / 10.
If we wanted to acquire the least significant digit, we could use number % 10. For 1234, that would have the value of 4.
Understanding this, we can then modify your code to take this into account:
int main() {
int n, count = 0;
printf("Enter an integer number:");
scanf("%d",&n);
while (n != 0) {
if (n % 10 == 1)
count++;
n /= 10;
}
printf("Number of 1s in your number: %d", count);
return 0;
}
You may want to use convert your int to a string like this :
char str[100];
sprintf(str, "%d", n);
Then, you can just iterate on str in order to find the occurrences of your digit.

Resources