I have an error
Jan 3, 2014 at 12:49pm UTC
I have to input n (the number of numbers),k (certain number).
The program should output number (number of numbers greater than k) and then also their sum.I wrote a code but it gives me the wrong "number of numbers greater than k".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
using namespace std;
int main ()
{
int n,k,number,sum;
sum=0;
int i;
cin >> k >> n;
for (i=1;i<=n;i++)
{
cin >> number;
if (number>k)
sum=sum+number;
if ((number-k)>0)
number=number+1;
}
cout << " " << number;
cout << " " << sum;
return 0;
}
Last edited on Jan 3, 2014 at 12:51pm UTC
Jan 3, 2014 at 1:24pm UTC
You have to make a different variable to store the no. of numbers greater than k.
cin >> number;
is replacing the value of number with the user's input every iteration of the loop so it doesn't retain its previous value.
Your code should be something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <iostream>
using namespace std;
int main()
{
int n,k,num;
int sum = 0;
int greater_k = 0;
cout << "Enter n: " ;
cin >> n;
cout << "Enter k: " ;
cin >> k;
cout << "Enter the numbers: " << endl;
for (int i = 1; i <= n; i++)
{
cin >> num;
if (num > k)
{
sum += num;
greater_k++;
}
}
cout << "\nNumber of numbers greater than k: " << greater_k << endl;
cout << "The sum of them: " << sum << endl;
return 0;
}
Last edited on Jan 3, 2014 at 1:25pm UTC
Jan 3, 2014 at 1:35pm UTC
For counting the numbers, wouldn't it be more like this?
1 2 3 4 5 6 7 8
for ( int i=0; i <= n; ++i )
{
if ( i > k )
{
++greater_k;
sum += i;
}
}
Last edited on Jan 3, 2014 at 1:35pm UTC
Jan 3, 2014 at 1:58pm UTC
@ iHutch105: No because for the sum, he should sum the user input by checking whether its greater or not..
Last edited on Jan 3, 2014 at 1:58pm UTC
Jan 3, 2014 at 2:04pm UTC
thank you so much.. :D
Jan 3, 2014 at 2:04pm UTC
Oh I see. I thought to OP was after two numbers, n and k, and wanted to know how many numbers up to n were greater than k, plus the sum. Never mind.
Topic archived. No new replies allowed.