Simple Array Sum in c++ - c++

I'm beginner in C++, and I've got a question about a simple sum code in c++.
Here is my code :
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
int sum;
int arr_i = 0;
cin >> n;
vector<int> arr(n);
while (arr_i != n)
{
cin >> arr[arr_i];
sum += arr[arr_i];
//cout << sum << endl;
if (arr_i == n - 1)
cout << sum;
arr_i++;
}
return 0;
}
The output doesn't print the correct answer without "cout << sum" before the if condition.
How can I solve this problem ?

You forget to initialize sum to 0.
int sum = 0;

As the previous post mentioned, sum was not initialized to 0. In terms of good practices and styles its a good idea to initialize any variables that are modified within a loop right before the loop body so that someone reading the code can easily grasp the context of your variables.
int main()
{
int n;
int sum;
int arr_i;
cin >> n;
vector<int> arr(n);
sum = 0;
arr_i = 0;
while (arr_i != n)
{
cin >> arr[arr_i];
sum += arr[arr_i];
//cout << sum << endl;
if (arr_i == n - 1)
cout << sum;
arr_i++;
}
return 0;
}
or as I prefer a "for" loop...
int main()
{
int n;
int sum;
int arr_i;
cin >> n;
vector<int> arr(n);
for (sum = 0, arr_i = 0; arr_i != n; arr_i++)
{
cin >> arr[arr_i];
sum += arr[arr_i];
//cout << sum << endl;
if (arr_i == n - 1)
cout << sum;
}
return 0;
}

Related

How to show only the last value of a for loop?

I'm working on building a loop right now that only shows the end value. However, the code is showing all the integers though.
Here's my code:
#include <iostream>
using namespace std;
int sum = 0;
void findMultiples(int n){
cout <<"Enter a positive integer:"<<endl;
for(int i = 0; i <= n; i++)
if (i % 3 == 0)
cout << "Sum: "<<(sum =sum+i)<<endl;
}
int main() {
int num;
cin>>num;
findMultiples(num);
return 0;
}
You are using for then if then showing output. The for and if scope area is one line without { }, so you are printing and summing at the same time and it is each time in the scope of if statement.
#include<iostream>
using namespace std;
int sum = 0;
void findMultiples(int n){
cout <<"Enter a positive integer:"<<endl;
for(int i = 0; i <= n; i++)
if (i % 3 == 0)
sum =sum+i;
cout << "Sum: "<<sum<<endl;
}
int main() {
int num;
cin>>num;
findMultiples(num);
return 0;
}
Your cout statements are in the wrong places. Try this instead:
#include <iostream>
using namespace std;
int findMultiples(int n){
int sum = 0;
for(int i = 0; i <= n; i++){
if (i % 3 == 0)
sum += i;
}
return sum;
}
int main() {
cout << "Enter a positive integer:" << endl;
int num;
cin >> num;
cout << "Sum: " << findMultiples(num) << endl;
return 0;
}

Change nested for loops into a do-while loop

How do I change this into a do-while loop? I am trying to have the exact the same output as the code posted here, but I want to use do-while loop instead of for loop
#include <iostream>
using namespace std;
int main()
{
int side;
cout << "Enter a number: ";
cin >> side;
for (int i = 0; i < side; i++)
{
for (int j = i; j >= 0; j--)
{
cout << "#";
}
cout << "\n";
}
}
#include <iostream>
using namespace std;
int main(){
int side;
cout << "Enter a number: ";
cin >> side;
int i = 0;
do {
int j = i;
while(j >= 0){
std::cout << "#";
j--;
}
std::cout << "\n";
i++;
}
while(i < side);
}
Is this what you meant? - Do While Loop

Why does my for loop not work in my void function

My for loop works outside the void function but not inside it.
I tried not using a function and it works but I need to put this for loop inside a function because I want to use it in other code.
It works like this:
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
}
cout << "Sum = " << sum;
return 0;
}
But not like this:
#include <iostream>
using namespace std;
void somation(){
int n, sum = 0;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
}
cout << "Sum = " << sum;
}
This the error message I get in dev-cpp:
D:\Dev-Cpp\MinGW64\x86_64-w64-mingw32\lib\libmingw32.a(lib64_libmingw32_a-
crt0_c.o) In function `main':
18 C:\crossdev\src\mingw-w64-v3-git\mingw-w64-
crt\crt\crt0_c.c undefined reference to `WinMain'
D:\CPP Projects\collect2.exe [Error] ld returned 1 exit status
I believe the problem you are having is that you are trying to execute a function without calling it in a main.
If you want to use the function somation somewhere else you can just copy it, but you always have to call the function in a main or else it won't work.
void somation()
{
int n, sum = 0;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; ++i) {
sum += i;
}
cout << "Sum = " << sum;
return;
}
int main(){
somation();
return 0;
}
Your program needs to have a main function (entry point for your program).
Try this
#include <iostream>
using namespace std;
void somation()
{
int n, sum = 0;
cout << "Enter a positive integer: ";
cin >> n;
for (int i = 1; i <= n; ++i)
{
sum += i;
}
cout << "Sum = " << sum;
}
int main()
{
somation();
return 0;
}

c++ variable sized arrays from Hackerrank with vectors

I wanted to solve a challenge named "Variable sized Arrays" on Hackerrank and I wanted to do that using vectors. The Code I wrote, doesn't work properly and I tried debugging it, but I'm getting nowhere. I'll be grateful for
Here's the challenge:
Consider an n-element array,a, where each index i in the array contains a reference Kito an array of integers (where the value of Ki varies from array to array). See the Explanation section below for a diagram.
Given a, you must answer q queries. Each query is in the format i j, where i denotes an index in array and j denotes an index in the array located at a[i] . For each query, find and print the value of element j in the array at location on a[i]a new line.
Input Format
The first line contains two space-separated integers denoting the respective values of n (the number of variable-length arrays) and q (the number of queries).
Each line of the subsequent lines contains a space-separated sequence in the format k a[i]0 a[i]1 … a[i]k-1 describing the k-element array located at a[i].
Each of the q subsequent lines contains two space-separated integers describing the respective values of i (an index in array a) and j (an index in the array referenced by a[i]) for a query.
Sample Input
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Sample Output
5
9
So here's my code for this (I'll leave it with the couts for debugging):
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::endl;
int main() {
int numberOfQueries = 0;
int numberOfArrays = 0;
cout << "Enter Nr.Of Arrays followed by Nr.Of Queries:";
cin >> numberOfArrays >> numberOfQueries;
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
cout << "Nr.Of Queries: " << numberOfQueries << endl;
vector<vector<int>>multiArray;
cout << "MultiArray size: " << multiArray.size();
while (numberOfArrays != 0) {
int vsize = 0;
cout << "\nenter array starting by its size: ";
cin >> vsize;
cout << " Size entered is: " << vsize << endl;
vector<int> vec1(vsize);
cout << "Array Size is: " << vec1.size() << endl;
//int element = 0;
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
multiArray.push_back(vec1);
numberOfArrays--;
cout << "MultiArray size: " << multiArray.size();
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
};
while (numberOfQueries > 0) {
int i = 0, j = 0;
cout << "\nQuery indexes:";
cin >> i >> j;
cout << multiArray[i][j];
numberOfQueries--;
}
}
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
should be something like
for (int i = 0; i < vsize; ++i) {
int elem;
cin >> elem;
cout << "Element is: " << elem << "\n";
vec1.push_back(elem);
}
while (cin >> vsize) isn't going to stop asking for input until you get end of file or an error. But you know how many inputs to expect so code that in a for loop.
My answer.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q;
cin >> n >> q ;
vector<int> a[n];
int k;
for(int i = 0; i < n; i++)
{
cin >> k;
for (int j = 0; j < k; j++)
{
int val_a_i_j;
cin >> val_a_i_j;
a[i].push_back(val_a_i_j);
}
};
for (int i = 0; i < q; i++)
{
int a_i, j;
cin >> a_i >> j;
cout << a[a_i][j] << '\n';
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a , b;
cin >> a >> b;
vector<int> arr[a];
for(int i= 0 ; i < a ; i++)
{
int m;
cin >> m;
int o;
for(int j=0;j<m;j++)
{
cin >> o;
arr[i].push_back(o);
}
}
int r,s;
for(int k=1;k<b;k++)
{
cin>>r>>s;
cout <<a[r][s]<< endl;
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, q;
cin >> n >> q;
vector<int>* a;
a= new vector<int>[n];
int p;
int k;
for (p = 0;p < n;p++) {
cin >> k;
for (int i = 0; i < k; i++) {
int o;
cin >>o;
a[p].push_back(o);
}
}
int r, s;
for (p = 0;p < q;p++)
{
cin >> r >> s;
cout << a[r][s]<<endl;
}
return 0;
}
This problem is about handling vectors of the vector.
int main() {
int n,q;
cin>>n>>q;
vector<vector<int> > a;//creating vectors of vector
int k;
for (int i = 0; i < n; i++)
{
cin >>k;
vector <int> row; // creating vector
for (int j = 0; j < k; j++)
{
int val;
cin>> val;
row.push_back(val);
}
a.push_back(row);
}
for (int l=0; l < q; l++)
{
int i,j;
cin>>i>>j;
// checking boundary conditions
if ((i >= 0 && i < a.size() ) && (j >=0 && j < a[i].size()))
{
cout<<a[i][j]<<endl;
}
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<vector<int>> MultiArry;
vector<int> output;
int n1,n2, q;
int i,j;
cin >> n1 >> q;
MultiArry.resize(n1);
output.resize(q);
for(int i=0;i<n1;i++)
{
cin >> n2;
MultiArry[i].resize(n2);
for(int j=0;j<n2;j++)
{
cin >> MultiArry[i][j];
}
}
for(int ii=0;ii<q;ii++)
{
cin >> i >> j;
output[ii] = MultiArry[i][j];
}
for(int i=0;i<q;i++)
cout << output[i] << endl;
return 0;
}

C++ factorial program doing strange math

Very new to c++. Making this factorial program, and somehow I've scraped through the code and built something, but the value it returns is always 10 times the correct value. For example, factorial for 5 is computed at 1200 instead of 120, and factorial of 3 is computed at 60. Why the extra unit?
This is the code:
#include <iostream>
using namespace std;
int main() {
int i, j, num;
cout << "Compute factorial: " << endl;
cin >> num;
for (i=1; i<num; i++){
for (j=num; j>1; j--)
num *=(j-i);
cout << num;
}
return 0;
}
All you need is one loop. This way should be much simpler.
#include <iostream>
using namespace std;
int main() {
int i, j=1, num;
cout << "Compute factorial: " << endl;
cin >> num;
for (i=num; i>0; i--){
j *= i;
}
cout << j << endl;
}
for (i=1; i<num; i++){
num *=i;
}
This should be enough
I think you are not quite clear about for loop,and be careful with the change of num
try this piece of code, hope it will help
#include <iostream>
using namespace std;
int main() {
int i, j, num;
cout << "Compute factorial: " << endl;
cin >> num;
int output_num = 1;
for (i=1; i<=num; i++){
output_num *= i;
}
cout << output_num;
return 0;
}
Use this code :
#include<iostream>
using namespace std;
int main()
{
int num,fact=1;
cout<<" Enter the no. to find its factorial:";
cin>>num;
for(int a=1;a<=num;a++)
{
fact=fact*a;
}
cout<<"Factorial of a given Number is ="<<fact<<endl;
return 0;
}
Output :
using two loops for computing factorial is very complex..... and you do not need it.
Try this
#include <iostream>
using namespace std;
int main() {
int i,num;
cout << "Compute factorial: " << endl;
cin >> num;
for(i=num;i>1;--i)
num*=(i-1);
cout << num;
return 0;
}