C++ finding sum of numbers till the end of user input - c++

I have to calculate the sum of all numbers that end in either 3, 5 or 7 and output it in main(). I've done that but with the input file being:
5
35
2
3
28
16
17
I get 535030017 as output. It just doesn't sum them up but it cout's them. Here is my C++:
#include<iostream>
using namespace std;
void sumNumbers(int number){
int sum = 0;
if (number%10==3||number%10==5||number%10==7){
sum += number;
}
cout << sum;
}
int main ()
{
int x;
while(cin >> x){
sumNumbers(x);
}
}

The following should fix your issue:
#include<iostream>
using namespace std;
void sumNumbers(int& sum, int number)
{
if (number%10==3||number%10==5||number%10==7)
{
sum += number;
}
cout << sum << endl;
}
int main ()
{
int x;
int sum = 0;
while(cin >> x)
{
sumNumbers(sum, x);
}
return 0;
}

If you need sum then you should do like this.
#include<iostream>
using namespace std;
int sumNumbers(int sum, int number){
if (number%10==3||number%10==5||number%10==7){
sum += number;
}
cout << sum;
return sum;
}
int main ()
{
int sum = 0;
int x;
while(cin >> x){
sum = sumNumbers(sum, x);
}
}

Try this :-
#include<iostream>
using namespace std;
int sumNumbers(int sum, int number){
if (number%10==3||number%10==5||number%10==7){
sum += number;
}
return sum;
}
int main ()
{
int x, sum=0;
while (cin >> x){
sum = sumNumbers(sum, x);
}
cout<<"Sum of the numbers ending with 3,5 and 7 is "<<sum;
}
And i would suggest you to put a limit on the input by the user otherwise the program will keep on running till user manually breaks it.
This will work finally only when the loop breaks.

The problem is that sum is a new variable for each invocation of sumNumbers, so you start over at zero every time.
A slightly different approach, separating filtering, summing , and output:
int filterNumber(int number)
{
int ones = number % 10;
if (ones == 3 || ones == 5 || ones == 7)
{
return number;
}
else
{
return 0;
}
}
int main()
{
int sum = 0;
int x = 0;
while(cin >> x){
sum += filterNumber(x);
}
std::cout << sum << std::endl;
}

Related

C++ How to read input N and then read a series of numbers N long?

I'm working on an assignment where I need to create a program that reads a non-empty sequence of integer numbers, and tells how many of them are equal to the last one.
It should read the amount of integers the sequence has and then read the sequence itself and return the amount of times the last number repeats itself excluding the last one.
Input would be like this:
9
1 7 3 2 4 7 5 8 7
and the output should be:
2
Now, I have no problem with the functionality of the program but I'm struggling on having it read the inputs. This is what I got:
#include <iostream>
#include <vector>
#include <sstream>
int NumbersEqualToLast(int limit, std::vector<int> elements) {
int check = elements[limit], counter = 0;
for (int i = limit; i >= 0; i--) {
if (elements[i] == check) {
counter++;
}
}
return(counter);
}
int main() {
int amount, number;
std::cin >> amount;
std::string input;
getline(std::cin, input);
std::stringstream iss(input);
std::vector<int> numbers;
while ( iss >> number ) {
numbers.push_back( number );
}
std::cout << NumbersEqualToLast(amount, numbers) << std::endl;
}
The problem is after reading the amount of integers (in this case 9) I get a Segmentation fault (core dumped) error.
EDIT AFTER SOLUTION
This is what worked for me using your suggestions. Thank you.
I understand if it's not pretty or there are better more efficient ways but I'm just starting out. :)
#include <iostream>
#include <vector>
int NumbersEqualToLast(int limit, std::vector<int> elements) {
int check = elements[limit - 1], counter = 0;
for (int i = limit - 2; i >= 0; i--) {
if (elements[i] == check) {
counter++;
}
}
return(counter);
}
int main() {
int quantity;
std::cin >> quantity;
int number;
std::vector<int> numbers;
for (int i = 0; i < quantity; i++) {
std::cin>>number;
numbers.push_back(number);
}
std::cout << NumbersEqualToLast(quantity, numbers) << std::endl;
}
Just don't judge harshly, please. I suggest another way to solve this problem.
#include <iostream>
#include <vector>
using namespace std;
int special, count;
void dfs(int current, int previous, vector<int>& visited, vector<int>& input)
{
if(visited[current]==1)
{
return;
}
visited[current]=1;
if(current==(input.size()-1))
{
special=input[current];
}
for(int next=(current+1); next<input.size(); ++next)
{
if(next==previous)
{
continue;
}
dfs(next, current, visited, input);
}
if(special==input[current])
{
++count;
}
if(current==0)
{
--count;
cout<<count;
}
return;
}
void solve()
{
int quantity;
cin>>quantity;
int number;
vector<int> numbers;
for(int i=0; i<quantity; ++i)
{
cin>>number;
numbers.push_back(number);
}
vector<int> visited(quantity);
dfs(0, -1, visited, numbers);
return;
}
int main()
{
solve();
return 0;
}
Input:
9
1 7 3 2 4 7 5 8 7
Here is the result:
2

why is the answer not showing up?

I am doing a code in c++ where I am supposed to be finding the series and I build the function for the series myself yet and I call the function I don't find my answer
here is my code
#include <iostream>
#include <cmath>
using namespace std;
double harmonicSeries(int n);
int main() {
int n;
cout << "Enter n" << endl;
cin >> n;
harmonicSeries(n);
}
double harmonicSeries(int n) {
for (int i = 1; i <= n; i++) {
float s;
float sum = 0.0;
s = 1 / n;
sum += s;
return sum;
}
}
I will be thankful for any help
See I have made the changes in your code,this works fine in this finding numbers and adding to get their sum.You should use return outside the function and basically harmonic series is of form 1/n which can be any float number or double number so I use s as double and i has float(which by this).
s=1/i(double=1/float,gets converted to double)
#include <iostream>
#include <cmath>
using namespace std;
double harmonicSeries(int n);
int main() {
int n;
cout << "Enter n" << endl;
cin >> n;
cout<<harmonicSeries(n);
}
double harmonicSeries(int n) {
double sum=0.00;
double s;
for (float i = 1; i <= n; i++) {
s = 1 / i;
sum += s;
}
return sum;
}
If you find anything wrong do ask for sure:)

Issue in finding power of a number using user defined functions

MY CODE along with the output
The following code is not working. It has no errors, am doing some mistake in the logic I think. I want to find power of a number using functions. How to make this code work?
The code:
#include<iostream>
using namespace std;
int pow(int);
int main()
{
int x,p,ans;
cout<<"Enter a number";
cin>>x;
cout<<"Enter the power of the number";
cin>>p;
ans=pow(x);
cout<<ans;
return 0;
}
int pow(int)
{
int a=1,i,p,x;
for(i=0;i<=p;i++)
{
a=a*x;
}
return a;
}
Here is working code:
#include<iostream>
using namespace std;
int pow(int, int);
int main()
{
int x,p,ans;
cout<<"Enter a number";
cin>>x;
cout<<"Enter the power of the number";
cin>>p;
ans=pow(x, p);
cout<<ans;
return 0;
}
int pow(int x, int p)
{
int a=1,i;
for(i=0;i<=p;i++)
{
a=a*x;
}
return a;
}
Ideone
You have to pass the local variables into the function instead of defining new ones with the same name. What you are doing should give you warnings about unused variables (x and p in main) and it also invokes undefined behavior in pow because of ininitialized reads of the variables defined there.
Also your function was wrong. You were just multiplying 1 with a value a bunch of times, which stays 1 forever.
Your function must have the parameters names specified (not just the types):
int pow(int) -> int pow(int b, int p)
You iterate once more than necessary:
for (i = 0; i <= p; i++) -> for (i = 0; i < p; i++)
You can shorten some arithmetic operations:
a=a*x -> a *= x;
The final function:
int pow(int b, int p)
{
int a = 1, i;
for (i = 0; i < p; i++)
a *= b;
return a;
}
You call it by passing the variables precedently declared:
pow(x, p)
So your final code be like:
#include <iostream>
int pow(int b, int p)
{
int a = 1, i;
for (i = 0; i < p; i++)
a *= b;
return a;
}
int main()
{
int x, p, ans;
std::cin >> x >> p;
ans = pow(x, p);
std::cout << ans << std::endl;
return 0;
}

creating an upwards series in c++

Screenshot of my code
Hey, I have just started learning C++ and I am trying to get it to sum the series:
K+N−1∑n=K [-1^(n)/(n+1)2]
I have managed to get it to tell me the nth term previously, but now I would like to for each term in the series, starting with the kth and going in sequence to the last (k+n-1st), add this term to the running sum.
I need to use a function direct_up() which uses the function term(). I defined initially and test it in the main.
I know I am missing something and am a bit confused about how to use the functions and that I may have made a few mistakes. So I would be very grateful for some advice or help. I have attached a picture of what I have done so far, as well as typed it below.
using namespace std;
double term(int n) {
double y;
if(n%2==1) {
y = -1.0/((n+1.0)*(n+1.0));
} else {
y = 1.0/((n+1.0)*(n+1.0));
}
return y;
}
double direct_up(int k, int n) {
int startingnumber = k;
for (int i = startingnumber; i <= k+n; i++) {
cout << n << term(n) << endl;
}
return n;
}
int main() {
double n;
int k;
cout.precision(16);
cout << "enter number of terms";
cin >> n;
cout << "enter a value for k";
cin >> k;
cout << "here is the value" << direct_up(k,n);
return 0;
}
This is what you want to do:
double direct_up(int k, int n)
{
int startingnumber = k;
double sum = 0;
for (int i = startingnumber; i <= k+n; i++) {
sum += term(i);
}
return sum;
}
Here's how to do it without keeping your own running sum as you asked in your comment:
#include <vector>
#include <numeric>
double direct_up(int k, int n)
{
int startingnumber = k;
std::vector<double> terms;
for (int i = startingnumber; i <= k+n; i++) {
terms.push_back(term(i));
}
return accumulate(terms.begin(), terms.end(), 0.0);
}

print largest number out of 4 numbers optimize

#include <iostream>
using namespace std;
int main()
{
int num1,num2,num3,num4;
int x;
int y;
cin>>num1>>num2>>num3>>num4;
if (num1 > num2)
{
x=num1;
}
else
{x = num2;
}
if(num3>num4)
{y = num3;
}
else
{
y= num4;
}
if (x>y)
{cout<<"the largest number is:"<<x;
}
else
{
cout<<"the largest number is :"<<y;
}
return 0;
}
this is my code to print largest number out of 4 numbers.
the question is that i am asked to optimize or compact the solution.
i tried but could not find another way to write such program.Can any one help me to optimize the solution and make it better..
ignore syntax errors..
Could be as simple as this:
int max = std::max( std::max( num1, num2 ), std::max( num3, num4 ) );
#include<iostream>
using namespace std;
int main() {
int x, m;
cin >> x;
m = x;
for (int i = 0; i < 3; ++i) {
cin >> x;
m = m > x ? m : x;
}
cout << "The largest number is: " << m << endl;
return 0;
}
Use loops.
One approach would be to store the values in an array and iterate over it:
int num[4];
cin >> num[0] >> num[1] >> num[2] >> num[3];
int max = num[0];
for (int i = 1; i < 4; ++i) {
if (num[i] > max) {
max = num[i];
}
}
cout << "The largest number is:" << max << endl;
Since C++11, you may directly do
const int biggest = std::max({num1, num2, num3, num4});
Try this :)) in this case i do not use std library. Just use an if-else statement like below. if(a > b) then return a else b.
Other case, we can create an array and request input to the user. First we set the first element in this array is MAX value. Use a loop and check. if current element is larger than MAX then we update the MAX value to the current value.
int maxOfTwoNumber(int a, int b){ return a>b? a : b; }
int maxOfFourNumber(int a, int b, int c, int d){
return maxOfTwoNumber(maxOfTwoNumber(a, b), maxOfTwoNumber(c, d));
}