Why is only one Armstrong number being printed? - c++

This is my assignment:
An Armstrong number of three digits is an integer such that the sum of
the cubes of its digits is equal to the number itself. For example,
153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153. Write a
function named is_armstrong that takes one positive integer number as
argument and returns a boolean variable which is true if the number is
an Armstrong number and return false otherwise. Use this function
is_armstrong in your main( ) function to print all Armstrong number in
the range of 100 and 999
I have written a program, but it only prints out one number, 999. Can anyone point out my error? Many thanks.
#include <iostream>
using namespace std;
//Function name: getRaiseAndAdd
//Purpose: Calculate each digit cubed and the sum of the results.
//We are sending in the current number from the loop starting at 100 and
//counting one by one to 999.
//Parameters: &numberInput
//Return value: Result of adding 3 numbers
int getRaiseAndAdd(int &numberInput)
{
int firstNumber, secondNumber, thirdNumber;
int remainder;
int sum;
int firstPower, secondPower, thirdPower;
firstNumber = numberInput / 100;
remainder = numberInput % 100;
secondNumber = remainder / 10;
thirdNumber = remainder % 10;
firstPower = firstNumber * firstNumber * firstNumber;
secondPower = secondNumber *secondNumber * secondNumber;
thirdPower = thirdNumber * thirdNumber * thirdNumber;
return sum = firstPower + secondPower + thirdPower;
}
int main()
{
int answer;
int originalNumber;
for(int i = 100; i < 1000; i++)
{
originalNumber = i;
answer = getRaiseAndAdd(i);
}
{
//Function name: is_Armstrong
//Purpose: finding the Armstrong numbers
//Parameters: answer
//Return value: 0
bool is_Armstrong (int answer);
if(answer == originalNumber);
{
cout<<"found an Armstrong number "<<originalNumber<<endl;
}
}
return 0;
}

There are a few things wrong with your code (your armstrong function seems fine though). First, your code to check if the number is an armstrong number is done after you loop through everything. This needs to be done inside the loop so that every number is checked.
Second, you have a semicolon after your if (if (answer == originalNumber); {...}). This causes execution to fall into the next block unconditionally, which is why it prints out 999 (which is not an armstrong number by the way).
So the fixes are to move your check into the loop and remove the semicolon after the if.

First you are running this loop:
for(int i = 100; i < 1000; i++)
{
originalNumber = i;
answer = getRaiseAndAdd(i);
}
after this originalNumber will be 999 and answer will be 999, too.
Only later you are running this check:
if(answer == originalNumber);
{
cout<<"found an Armstrong number "<<originalNumber<<endl;
}
}
You should make the check a proper function, you have a forward declaration, followed by a block, and call it from within the loop.

Starting from beginning of the main method to the end, you are printing one time. If you repeat your printing in a loop you will get multiple prints.

As Kevin stated:
putting the Check within the loop would solve your problem
for(int i = 100; i < 1000; i++)
{
originalNumber = i;
answer = getRaiseAndAdd(i);
if(answer == originalNumber)
{
cout<<"found an Armstrong number "<<originalNumber<<endl;
}
}
Ran it and got the result

Related

Wrong output- trying for if the number is Armstrong

I am new to coding and just starting with the c++ language, here I am trying to find the number given as input if it is Armstrong or not.
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153.
But even if I give not an armstrong number, it still prints that number is armstrong.
Below is my code.
#include <cmath>
#include <iostream>
using namespace std;
bool ifarmstrong(int n, int p) {
int sum = 0;
int num = n;
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
if(sum==n){
return true;
}else{
return false;
}
}
int main() {
int n;
cin >> n;
int i, p = 0;
for (i = 0; n > 0; i++) {
n = n / 10;
}
cout << i<<endl;
if (ifarmstrong(n, i)) {
cout << "Yes it is armstorng" << endl;
} else {
cout << "No it is not" << endl;
}
return 0;
}
A solution to my problem and explantation to what's wrong
This code
for (i = 0; n > 0; i++) {
n = n / 10;
}
will set n to zero after the loop has executed. But here
if (ifarmstrong(n, i)) {
you use n as if it still had the original value.
Additionally you have a error in your ifarmstrong function, this code
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
result in num being zero from the second iteration onwards. Presumably you meant to write this
while(num>0){
sum=sum+pow(num%10,p);
num=num/10;
}
Finally using pow on integers is unreliable. Because it's a floating point function and it (presumably) uses logarithms to do it's calculations, it may not return the exact integer result that you are expecting. It's better to use integers if you are doing exact integer calculations.
All these issues (and maybe more) will very quickly be discovered by using a debugger. much better than staring at code and scratching your head.

Kickstart 2022 interesting numbers

The question is to find the number of interesting numbers lying between two numbers. By the interesting number, they mean that the product of its digits is divisible by the sum of its digits.
For example: 459 => product = 4 * 5 * 9 = 180, and sum = 4 + 5 + 9 = 18; 180 % 18 == 0, hence it is an interesting number.
My solution for this problem is having run time error and time complexity of O(n2).
#include<iostream>
using namespace std;
int main(){
int x,y,p=1,s=0,count=0,r;
cout<<"enter two numbers"<<endl;
cin>>x>>y;
for(int i=x;i<=y;i++)
{
r=0;
while(i>1)
{
r=i%10;
s+=r;
p*=r;
i/=10;
}
if(p%s==0)
{
count++;
}
}
cout<<"count of interesting numbers are"<<count<<endl;
return 0;
}
If s is zero then if(p%s==0) will produce a divide by zero error.
Inside your for loop you modify the value of i to 0 or 1, this will mean the for loop never completes and will continuously check 1 and 2.
You also don't reinitialise p and s for each iteration of the for loop so will produce the wrong answer anyway. In general limit the scope of variables to where they are actually needed as this helps to avoid this type of bug.
Something like this should fix these problems:
#include <iostream>
int main()
{
std::cout << "enter two numbers\n";
int begin;
int end;
std::cin >> begin >> end;
int count = 0;
for (int number = begin; number <= end; number++) {
int sum = 0;
int product = 1;
int value = number;
while (value != 0) {
int digit = value % 10;
sum += digit;
product *= digit;
value /= 10;
}
if (sum != 0 && product % sum == 0) {
count++;
}
}
std::cout << "count of interesting numbers are " << count << "\n";
return 0;
}
I'd guess the contest is trying to get you to do something more efficient than this, for example after calculating the sum and product for 1234 to find the sum for 1235 you just need to add one and for the product you can divide by 4 then multiply by 5.

Finding Armstrong Number using C++

I'm writing a program for finding whether a given number is an Armstrong Number:
int main()
{
int n,rem,sum=0;
cout<<"Enter the Number for checking"<<endl;
cin>>n;
while(n!=0)
{
rem=n%10;
sum=sum+(rem*rem*rem);
n=n/10;
}
if(sum==n)
{
cout<<"Armstrong Number"<<endl;
}
else
{
cout<<"It's not a armstrong number";
}
return 0;
}
When I run it, it always reports "It's not a armstrong number", regardless of input.
I changed the code as follows, and got the correct result. But I don't understand why I need to assign input to n1 and do the operation - why can't I directly do the operation with n?
int main()
{
int n,rem,sum=0,n1;
cout<<"Enter the Number for checking"<<endl;
cin>>n;
n1=n;
while(n1!=0)
{
rem=n1%10;
sum=sum+(rem*rem*rem);
n1=n1/10;
}
if(sum==n)
{
cout<<"Armstrong Number"<<endl;
}
else
{
cout<<"It's not a armstrong number";
}
return 0;
}
In the line if (sum==n) your program compares sum and n. In the second program n is initial number entered by user. But in the first program n==0 (see the loop above it).
So, in the first program the check if (sum==n) works as if (sum==0). But value of sum is never 0 (except user entered 0). So, first program always returns "It's not a armstrong number".
And about style: It is much better to use functions instead of putting the whole logic into one main() function. For instance, you can create a function for calculation of the intermediate sum for cheching of Armstrong Number:
int getSumOfCubesOfDigits(int n)
{
int sum = 0;
while (n)
{
const int rem = n % 10;
sum += rem * rem * rem;
n = n / 10;
}
}
In this case your program will be much simpler and it will be hard to make the mistake you have in the first program of your question:
int main()
{
int n;
cout << "Enter the Number for checking" << endl;
cin >> n;
if(getSumOfCubesOfDigits(n) == n)
cout<<"Armstrong Number"<<endl;
else
cout<<"It's not a armstrong number";
return 0;
}
In the first program, the original number is entered into 'n'. The only problem in your logic is, you forgot that by the time you exit from the while loop, 'n' will no longer be your original number since you are repeatedly doing n=n/10, and hence 'sum==n' never satisfies even for an Armstrong number.
So before you enter the while loop, save the original number into another variable, say n1 (as done in the second program you provided), and only use n1 for operations, ie, n1=n1/10. Leave n alone so that, in the end 'n' will still contain the original number, which you can finally compare with 'sum' to find your answer.
Which number do you compare ? , in first program in while loop , n value is changed ( in this variable you get the input) and finally check with sum == n , so it always get condition fail.
So temp (n1) variable is required , to compare the final result
Your code is different in the second code block, you are still testing if sum=n.
In the second code block, if you tested if(sum=n1), I would suspect it would work the same.
I got this solution for finding an Armstrong Numbers
int main() {
for (int i=10; i<=9999; i++) {
int k = i,z = 1, s = 0, n = i;
while ((k/=10) > 0) z++;
for (int t = z; t; t--, n/=10) {
s += pow(n % 10, z);
}
if (i == s) cout << i << endl;
}
return 0;
}

How to make sum in a single digit?

I'm making a program to sum a digits, Have a look into this program:
#include<iostream>
using namespace std;
int main(){
int i, j;
int sum=1;
cout<<"Enter your sum: "<<endl;
cin>>i;
while(i>0){
j=i%10;
sum=sum+j;
i=i/10;
}
cout<<"Sum: "<<sum;
cout<<endl;
}
So, as I type into output as 25 it'll give me as an output 7.
But I want to make it in a single digit of every sum, let's say as I type 147. It gives me an output 10 but I want 1 as an output.
I know it could be done as:
while(i>0){
j=i%10;
sum=sum+j;
i=i/10;
}
cout<<"Sum: "<<sum/10;
and surely it'll give me an output as 1.
But as I type a number 185 it gives me an output 1.. But I want the whole sum of digit.
I want that program into which if i type 185
Output must suppose to be as
1+8+5=14
1+4=5
And output must be 5.. So please help me to resolve this kind of issue.
What you describe is called a digital root. Interestingly enough, it can be computed by simply determining the remainder when dividing by 9 - whereas 0 is substituted by 9.
unsigned digitalRoot(unsigned i)
{
return 1 + (i-1)%9; // if i%9==0, (i-1)%9==8 and adding 1 yields 9
}
digitalRoot(185) is 5 since 185 = 9*20 + 5.
as I type into output as 25 it'll give me as an output 7.
No, it is actually 8 (demo). The problem is that you initialize sum to 1 instead of 0.
As far as making the sum a single digit goes, add another loop to your program:
for (;;) { // Loop until the break is reached
while(i>0){
j=i%10;
sum=sum+j;
i=i/10;
}
if (sum < 10) break; // It's single digit
i = sum;
sum = 0;
}
You can try this:
while(i>0){
j=i%10;
sum=sum+j;
i=i/10;
if (i == 0 && sum >= 10) // if all the digits of previous number is processed and sum is not a single digit
{
i = sum;
sum = 0;
}
}
Note that there is no nested loop!
Do not forget to initialize sum to 0 instead of 1.
import java.util.*;
public class SingleDigit
{
public static void main(String[] args)
{
int number = 0, temp = 0, result = 0;
Scanner inp = new Scanner(System.in);
System.out.print("Enter the Number :");
number = inp.nextInt();
temp = number;
while(temp>0)
{
result = result + (temp%10);
temp = temp/10;
if(result > 9)
result = (result % 10)+(result / 10);
}
System.out.println("Single Digit Number for the Number "+number+" is :" result);
System.out.println("Thank You KING....");
}
}

Code for Armstrong numbers not working

Alright please go easy. Just learning C++ and first also question here. I've written a program to list all Armstrong numbers below 1000. While I have read the Wikipedia article on narcissistic numbers, I'm only looking for 3-digit ones. Which means I only care for the sum of the cubes of the digits.
It works by executing a for loop for 1 to 1000, checking whether the indexing variable is armstrong or not using a user defined function and printing it if it is. The user defined function works simply by using a while loop to isolate digits and matching the sum of the cubes to the original number. If it is true, then returns 1 otherwise return 0.
The problem is, I'm getting abolutely no numbers in the output. Only the cout statement in void main() appears and the rest is blank. Tried to debug as much as I could. Complier is Turbo C++. Code-
#include<iostream.h>
#include<conio.h>
int chk_as(int);//check_armstrong
void main()
{
clrscr();
cout<<"All Armstrong numbers below 1000 are:\n";
for(int i=1;i<=1000;i++)
{
if (chk_as(i)==1)
cout<<i<<endl;
}
getch();
}
int chk_as (int n)
{
int dgt;
int sum=0,det=0;//determinant
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
{det=1;}
else
{det=0;}
return det;
}
The problem is that you are dynamically changing the value of n in your method, but you need its original value to check the result.
Add in a temporary variable, say, t.
int t = n;
while (t!=0)
{
dgt=t%10;
t=t/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
// ... etc.
EDIT: Nevermind... this was wrong
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
This runs forever as n never reaches 0.
The problem is, that in the end of the loop
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
n is 0, so the condition if (sum==n) is never true.
Try something like :
int chk_as (int n)
{
int copy = n;
int dgt;
int sum=0,det=0;//determinant
while (copy!=0)
{
dgt=copy%10;
copy=copy/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
{det=1;}
else
{det=0;}
return det;
}
I have given here the program for finding armstrong number of a three digits number.
The condition for armstrong number is,
Sum of the cubes of its digits must equal to the number itself.
For example, 407 is given as input.
4 * 4 * 4 + 0 * 0 * 0 + 7 * 7 * 7 = 407 is an armstrong number.
#include <stdio.h>
int main()
{
int i, a, b, c, d;
printf("List of Armstrong Numbers between (100 - 999):\n");
for(i = 100; i <= 999; i++)
{
a = i / 100;
b = (i - a * 100) / 10;
c = (i - a * 100 - b * 10);
d = a*a*a + b*b*b + c*c*c;
if(i == d)
{
printf("%d\n", i);
}
}
return 0;
}
List of Armstrong Numbers between (100 - 999):
153
370
371
407
Reference: http://www.softwareandfinance.com/Turbo_C/Find_Armstrong_Number.html