I want to write a code that takes n numbers,then it finds the biggest digits of each number.And then, find sum of the biggest digits.For example:
n=3
145 625 802 (5+6+8=19) I wrote this code by using arrays and functions,but it doesn't take automatically the values from the getData function..How can I develop it in order to work?
When you divide number by powers of ten, you get its numbers.
In C++, when you divide int by int and you get a fraction, everything past dot is thrown out. So, 15/10 = 1.5 , but we ignore whatever is after dot, so 15/10 = 1 . Same goes for 19 - 19/10 = 1
And 15/100 = 0.
It looks like you did something like it, but tell me, why do you start checking array from 1 to n, when arrays have indexes form 0 to n-1?
I changed some things in the code but it says error "name look up of i changed for ISO for scoping " in the funcion biggestDigit..How can I manage to fix it?
#include <iostream>
#include <fstream>
#include <stdio.h>
usingnamespace std;
void getData (int list[], int &n)
{
ifstream fin ("input.txt");
fin >> n;
for (int i=0;i<n;i++)
fin >> list[i];
}
int biggestDigit (int list[], int n)
{
int max;
for (int i=0;i<n;i++)
max=list[i]%10;
list[i]=list[i]/10;
if (list[i]>max) max=list[i]%10;
list[i]=list[i]/10;
return max;
}
int sumofbiggestDigits (int list[], int n)
{
int sum=0;
for (int i=0;i<n;i++)
return sum+max;
}
int main ()
{
int list[1000],n;
getData(list,n);
biggestDigit(list,n);
cout << sumofbiggestDigits(list,n);
return 0;
}
First, I suggested a int biggestDigit( int number );
but you created a int biggestDigit (int list[], int n);
Do you spot the difference?
Your problem comes from the fact that:
1 2 3 4 5 6 7 8 9
for (int i=0;i<n;i++)
max=list[i]%10;
list[i]=list[i]/10;
// means same as
for (int i=0;i<n;i++)
{
max=list[i]%10;
}
list[i]=list[i]/10; // 'i' delcared in for does not exist any more
As for the sumofbiggestDigits:
sum=0
for each number in list
add biggest digit of number to sum
return sum