Sum in loop not displaying actual result? - c++

I am suppossed to sum the squares of the all the natural numbers until it reaches some input, but the result becomes larger than it should. As I set 3 as input, the outcome becomes 3*10⁹ or so, could you please tell if I am missing a mistake with data types or operations?
BTW, when does using functions become more efficient than writing whatever in the main code? I have quite a few doubts on when I should or should not use them.
Thanks to whomever might read it.
#include <iostream>
using namespace std;
int main(){
int input, sum;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}

You should initialize the variable sum with 0 and then the program will be run successfully. When you use sum without initializing it, the behaviour of your program is undefined.
Also you can use below formula instead of the for loop:
sum = n * (n + 1) * (2 * n + 1) / 6

You never initialize sum, so there is no guarantee that the value starts at 0. In fact, it's initial value is essentially undefined. You should simply add the line sum = 0; before your for loop.
#include <iostream>
using namespace std;
int main(){
int input, sum;
sum = 0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
"BTW, when does using functions become more efficient than writing whatever in the main code"
It isn't necessarily more efficient, but for larger projects it is easier to read code when common functionality has been grouped into reusable functions. As a general rule of thumb, if you are writing the same code/algorithm more than once, you should write a function for that code/algorithm.
NOTE - As pointed out by others there happens to be a formula for calculating the sum of squares without a loop.
sum = n * (n + 1) * (2 * n + 1) / 6
This is what is known as an order of 1, or O(1), solution because a single atomic operation can be performed to achieve the results you are looking for. On the other hand, the loop solution is considered order of n, or O(n), since n iterations of the loop must be performed to achieve the results of the routine. The O(1) solution is considered optimal. If you use large values as your input then you will see why. However, if you are new to programming then your teachers will not expect you to know much about algorithm analysis and the original solution above should be fine.

There are two approaches to resolve your problem.
The first one is to place the declaration of the variable sum before main. For example
#include <iostream>
using namespace std;
int sum;
int main(){
int input;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
In this case the variable will have the static storage duration and will be initislized by the compiler with 0.
Otherwise the variable have the automatic storage duration and must be initialized explicitly like
#include <iostream>
using namespace std;
int main(){
int input, sum = 0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += i*i;
}
cout << sum << endl;
}
Pay attention to that it is better to declare the variable as having the type long long int because the sum of squares can be too big and will not fit into an object of the type int. For example
#include <iostream>
using namespace std;
int main(){
int input;
long long int sum =0;
cin >> input;
for(int i = 1; i <= input; i++){
sum += ( long long int )i*i;
}
cout << sum << endl;
}

You do not initialize sum. So whenever you do sum += i * i, you are adding numbers to a trash value.
This is the reason you get incorrect results.
To fix this, simply replace int input, sum; with int input, sum(0);.

Related

wrong output in vscode and codeblocks

This code snippet is supposed to return the reverse of the given integer and in the Sololearn compiler it works but in VSCode and Code::Blocks the output is different.
For 543 it returns -93835951 in VSCode and 694653940 in Code::Blocks.
Does anybody know why?
#include <iostream>
using namespace std;
int main()
{
int n, sum, a;
a = 0;
sum = 0;
cin >> n;
while (n>0)
{
a = n % 10;
sum = sum * 10 + a;
n = n / 10;
}
cout << sum;
return 0;
}
Here is the working version with a bit of refactoring but still keeping it very similar to your snippet:
#include <iostream>
int main( )
{
std::cout << "Enter a number: ";
int num { };
std::cin >> num;
int sum { };
while ( num > 0 )
{
const int remainder { num % 10 };
sum = sum * 10 + remainder;
num = num / 10;
}
std::cout << "The reversed number: " << sum << '\n';
}
A few general things to keep in mind:
Do not use using namespace std;. That's a bad practice. See Why is "using namespace std;" considered bad practice?.
Do not declare multiple variables in a single statement. That can lead to various issues.
Make sure to initialize your variables before using them if their initial values will be read and used in some operation. If the initial value is not used by anyone, then do not initialize the variable since it would be a waste of computing power.
Try to shrink the scope of variables as much as appropriate to reduce the risk of them being used accidentally by another statement that is not supposed to access those variables. In the above example, I declared remainder inside the scope of the while loop because it was not being used outside the loop.
And last but not least, avoid ambiguous identifiers like int a, int n, etc. These are not meaningful and purposeful names in this context. Use names that MAKE sense.
int n,sum,a=0;
the above expression only initializes the last variable 'a', leaving 'n' and 'sum' uninitialized.
although n is assigned a value in
cin >> n;
the variable 'sum' is likely to have a garbage value. That explains the different results.

What is the problem with the logic of the code?

I have been trying to solve this simple problem in C++ but every time I submit, it says wrong answer. I am pretty sure I have got the logic right. Any help is appreciated.
Question: Find the sum of distances between the inputted numbers.
Ex. Input: 2 5 8 2 1
Distance=2+2+5+0
=9, (1 < n < 1000000)
PS: Input can't have the same number consecutively.
PSS: Subtask two is giving Wrong Answer
Code:
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t,a[100000],n,sum=0;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>n;
for(int j=0;j<n;j++)
{
cin>>a[j];
}
for(int j=0;j<n-1;j++)
{
if(a[j]!=a[j+1])
{
sum = sum + abs(a[j]-a[j+1])-1;
}
}
cout<<sum<<endl;
sum=0;
}
}
The problem with your code is that you are using int type for sum whose maximum value (1E11) can exceed the upper limit of int(if it's 32-bit or less). Use long long(atleast 64-bit) instead to store your sum.
Well, you can also optimize the code because you don't exactly need an array of 100000 integers and store the values in it. You can do so using only two variables.
Here is a modified implementation of your logic:
#include <iostream>
int main() {
int t, n, first, second;
long long sum; // or better use std::int_fast64_t sum;
std::cin >> t;
while (t--) {
sum = 0;
std::cin >> n >> first;
for (int i = 0; i < n - 1; ++i) {
std::cin >> second;
sum += std::abs(first - second) - 1;
first = second;
}
std::cout << sum << std::endl;
}
}
PS: In competitive coding checking the provided constraints like if(a[j]!=a[j+1]) is useless. The problem statement simply guarantees it that it will never be false.

Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers

Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.
I know how to do that without using a function ,for example for any n numbers I have the following program:
#include<stdio.h>
int main()
{
int n, i;
float sum = 0, x;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("\n\n\nEnter %d elements\n\n", n);
for(i = 0; i < n; i++)
{
scanf("%f", &x);
sum += x;
}
printf("\n\n\nAverage of the entered numbers is = %f", (sum/n));
return 0;
}
Or this one which do that using arrays:
#include <iostream>
using namespace std;
int main()
{
int n, i;
float num[100], sum=0.0, average;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 100 || n <= 0)
{
cout << "Error! number should in range of (1 to 100)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
cout << "Average = " << average;
return 0;
}
But is it possible to use functions?if yes then how? thank you so much for helping.
As an alternative to using fundamental types to store your values C++ provides std::vector to handle numeric storage (with automatic memory management) instead of plain old arrays, and it provides many tools, like std::accumulate. Using what C++ provides can substantially reduce your function to:
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
In fact a complete example can require only a dozen or so additional lines, e.g.
#include <iostream>
#include <vector>
#include <numeric>
double avg (std::vector<int>& i)
{
/* return sum of elements divided by the number of elements */
return std::accumulate (i.begin(), i.end(), 0) / static_cast<double>(i.size());
}
int main (void) {
int n; /* temporary integer */
std::vector<int> v {}; /* vector of int */
while (std::cin >> n) /* while good integer read */
v.push_back(n); /* add to vector */
std::cout << "\naverage: " << avg(v) << '\n'; /* output result */
}
Above, input is taken from stdin and it will handle as many integers as you would like to enter (or redirect from a file as input). The std::accumulate simply sums the stored integers in the vector and then to complete the average, you simply divide by the number of elements (with a cast to double to prevent integer-division).
Example Use/Output
$ ./bin/accumulate_vect
10
20
34
done
average: 21.3333
(note: you can enter any non-integer (or manual EOF) to end input of values, "done" was simply used above, but it could just as well be 'q' or "gorilla" -- any non-integer)
It is good to work both with plain-old array (because there is a lot of legacy code out there that uses them), but equally good to know that new code written can take advantage of the nice containers and numeric routines C++ now provides (and has for a decade or so).
So, I created two options for you, one use vector and that's really comfortable because you can find out the size with a function-member and the other with array
#include <iostream>
#include <vector>
float average(std::vector<int> vec)
{
float sum = 0;
for (int i = 0; i < vec.size(); ++i)
{
sum += vec[i];
}
sum /= vec.size();
return sum;
}
float average(int arr[],const int n)
{
float sum = 0;
for (int i = 0; i < n; ++i)
{
sum += arr[i];
}
sum /= n;
return sum;
}
int main() {
std::vector<int> vec = { 1,2,3,4,5,6,99};
int arr[7] = { 1,2,3,4,5,6,99 };
std::cout << average(vec) << " " << average(arr, 7);
}
This is an example meant to give you an idea about what needs to be done. You can do this the following way:
// we pass an array "a" that has N elements
double average(int a[], const int N)
{
int sum = 0;
// we go through each element and we sum them up
for(int i = 0; i < N; ++i)
{
sum+=a[i];
}
// we divide the sum by the number of elements
// but we first have to multiply the number of elements by 1.0
// in order to prevent integer division from happening
return sum/(N*1.0);
}
int main()
{
const int N = 3;
int a[N];
cin >> a[0] >> a[1] >> a[2];
cout << average(a, N) << endl;
return 0;
}
how to do that without using a function
Quite simple. Just put your code in a function, let's call it calculateAverage and return the average value from it. What should this function take as input?
The list of numbers (array of numbers)
Total numbers (n)
So let's first get the input from the user and put it into the array, you have already done it:
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
}
Now, lets make a small function i.e., calculateAverage():
int calculateAverage(int numbers[], int total)
{
int sum = 0; // always initialize your variables
for(int i = 0; i < total; ++i)
{
sum += numbers[i];
}
const int average = sum / total; // it is constant and should never change
// so we qualify it as 'const'
//return this value
return average
}
There are a few important points to note here.
When you pass an array into a function, you will loose size information i.e, how many elements it contains or it can contain. This is because it decays into a pointer. So how do we fix this? There are a couple of ways,
pass the size information in the function, like we passed total
Use an std::vector (when you don't know how many elements the user will enter). std::vector is a dynamic array, it will grow as required. If you know the number of elements beforehand, you can use std::array
A few problems with your code:
using namespace std;
Don't do this. Instead if you want something out of std, for e.g., cout you can do:
using std::cout
using std::cin
...
or you can just write std::cout everytime.
int n, i;
float num[100], sum=0.0, average;
Always initialize your variables before you use them. If you don't know the value they should be initialized to, just default initialize using {};
int n{}, i{};
float num[100]{}, sum=0.0, average{};
It is not mandatory, but good practice to declare variables on separate lines. This makes your code more readable.

How can I fix the code so it prints out the sum of each pair?

N pairs of numbers are given. Print the sum of each pair.
The first line of the standard input is N (1≤N≤100000). The following N lines contain exactly two integers, separated by a space whose absolute values are less than 1,000,000,000.
INPUT
2
1 1
-1 0
OUTPUT:
2
-1
I've written this:
#include<iostream>
using namespace std;
int main()
{
unsigned short int n;
long int n2,n3, rez;
rez=0;
//Uneseno broj linija:
cin>>n;
for(int i=0;i<n;i++)
{
if(rez==0)
{
cin>>n2>>n3;
rez=n2+n3;
cout<<rez<<endl;
}
rez=0;
}
return 0;
}
Now this would be perfectly fine, but I don't get required output.
I can't think of the other idea, because I don't know how many exactly of N's will be there, so I can't predict numbers of variables that I should create, which will store result of two numbers entered.
Your program is almost working. All you need to do is make n larger. An unsigned short caps out at 65,535. Bump it up to an unsigned int so it can handle values up to 100,000.
Aside from that, the rez variable isn't needed. You can delete it.
Also, there's no need to store all the numbers first and then calculate the sums afterwards. Calculating them as you go will work just fine. cin and cout are independent streams of data and it's fine to interlace reads and writes. Avoid storing them in a vector or an array as that just chews up a lot of memory for no benefit.
#include <iostream>
int main()
{
unsigned n;
std::cin >> n;
for (unsigned i = 0; i < n; i++)
{
long n2, n3;
std::cin >> n2 >> n3;
std::cout << (n2 + n3) << std::endl;
}
return 0;
}
Style notes:
Avoid using namespace std;. It's better to write out std:: everywhere.
I moved n2 and n3 inside the loop. Try to declare variables as late as possible to limit their scope rather than declaring them all at the top of the function. It makes it obvious that they're only used inside the loop and that their values don't persist across iterations.
Add some whitespace around operators. Cramming everything together is hard to read.
I have changed some of the numeric types you've used. Does this work?
int main()
{
vector<long long int> results;
unsigned long int n;
long long int n2, n3, rez;
cin >> n;
for (unsigned long int i = 0; i < n; i++)
{
cin >> n2 >> n3;
rez = n2 + n3;
results.push_back(rez);
rez = 0;
}
for (auto result: results)
{
cout << result << endl;
}
return 0;
}

C++ Array, average value (Beginner)

I need some help creating an array with 10 number that the user can pick. Had a post about this yesterday but misstook arrays for vectors..
Need to calculate the average value of the numbers, need pseudocode for it as well.
Any help would be awesome, I do have a school book but the array examples in it will just not work (as you can se in the code I'll add).
This is what I got sofar:
#include <iostream>
#include <array>
using namespace std;
int main()
{
int n[10];
for (int i = 0; i < 10; i++)
{
cout << "Please enter number " << i + 1 << ": ";
cin >> n[i];
}
float average(int v[], int n)
{
float sum = 0;
for (int i = 0; i < n; i++)
{
sum += v[i]; //sum all the numbers in the vector v
}
return sum / n;
}
system("pause");
}
the part to calculate the average I got help with from the last post I had. But everything else won't work "/ So basicly I need help to make a array with 10 user input numbers. Cheers
The only thing that you wrote correctly is function average. I would add qualifier const to the parameter of the function
#include <iostream>
#include <cstdlib>
using namespace std;
float average( const int v[], int n )
{
float sum = 0.0f;
for ( int i = 0; i < n; i++ )
{
sum += v[i]; //sum all the numbers in the vector v
}
return sum / n;
}
Or statmenet
return sum / n;
could be substituted for
return ( n == 0 ? 0.0f : sum / n );
Take into account that functions shall be defined outside any other functions and a function declaration shall appear before usage of the function.
You need not header <array> because it is not used. But you need to include header <cstdlib> because you use function system.
As it is written in your assigment you need enter arbitrary values for the array
int main()
{
const int N = 10;
int a[N];
cout << "Enter " << N << " integer values: ";
for ( int i = 0; i < N; i++ ) cin >> a[i];
cout << "Average of the numbers is equal to " << average( a, N ) << endl;
system( "pause" );
return 0;
}
int n[10]; - n is an array of ints, not strings, so why are you doing n[0] = "Number 1: ";? You should instead loop and ask for an input from the user.
After you do this, you should place average function outsude the main function and call it from the main.
I advise you to go through a basic tutorial.
Function definition should always be outside main.
int n[10] mean n is array of integers of size 10. They are not array of pointers of type char * to hold strings
There isn't a caller for function average. Subroutines work like, callers will call callee passing arguments to perform operations on them and return them back - pass by reference.