Why is this not printing the final output of sum? - c++

Given an array of N integers. My task is to print the sum of all of the integers.
Input:
First line of input file contains a single integer T which denotes the number of test cases. For each test case, there will be two lines. First line contains N which denotes number of elements in an array, and second line contains N space seperated integers.
Output:
Corresponding to each test case, print the sum of array in a new line.
Constraints:
1 <= T <= 100
1 <= N <= 1000
0 <= Arr[i] <= 200
#include <iostream>
using namespace std;
int main()
{
int n, no_of_elem_array;
int arr[50], sum[50];
cin >> n;
int j = 0;
while (n--) {
cin >> no_of_elem_array;
for (int i = 0; i < no_of_elem_array; i++) {
cin >> arr[i];
}
for (int i = 0; i < no_of_elem_array; i++) {
sum[j] = sum[j] + arr[i];
}
j++;
}
for (int i = 0; i < n; i++) {
cout << sum[i] << endl;
}
return 0;
}
Output
2
4
1 2 3 4
6
5 8 3 10 22 45

There is n in your final loop
for(int i=0; i<n; i++){
cout<<sum[i]<<endl;
}
which is become 0 in
while(n--)
that is why it is not print anything

That is not how one adds arrays in C++:
This is the code I propose:
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> vec_of_ints;
std::cout << "Enter the size of the array: ";
unsigned size = 0;
std::cin >> size;
vec_of_ints.resize(size);
for(auto& integer : vec_of_ints) {
std::cin >> integer;
}
std::cout << std::accumulate(vec_of_ints.begin(), vec_of_ints.end(), 0);
return 0;
}
Also, as #Alan Birtles has suggested, there is another (and better) alternative:
you do not need to store the input at all:
int main() {
unsigned size = 0;
std::cin >> size;
long sum = 0;
for (int i = 0; i < size; i++) {
int num = 0;
std::cin >> num;
sum += num;
}
std::cout << sum << "\n";
return 0;
}

Two issues:
Your arrays are not big enough, so there will be invalid access, which is undefined behaviour.
Array sum is local variable, so the value is uninitialized (i.e. It contains arbitrary values when allocated), you need to set them to zero by yourself.

Related

How can I create a square 2d array of size NxN where N is supplied by the user and populated with random numbers at a certain range?

My goal is for the user to input a number from the range 3 to 8 and it will a create matrices based on that size and then fill it with random numbers from the range of -12 to 8.
for example if the user enters 3
it should display :
9 1 -4
4 2 -6
-11 5 8
I think I've got the concept right but the variable length array confuses me cause I know it's not possible to create an array that isn't constant unless you use std:vector but I dont know how to implement that in this code.
I keep getting the error "subscript requires array or pointer type"
#include<iostream>
#include <random>
#include<time.h>
#include<iomanip>
#include <vector>
#include <map>
using namespace std;
void array_gen(int* array, int arraysize) // void function to generate the array with random numbers
{
int i;
for (i = 0;i < arraysize;i++)
{
array[i] = rand() % -12 + 8; // used to generate numbers from 0 to 10
}
}
void arraydis(int* array, int arraysize) // function to sort array
{
int i;
for (i = 0;i < arraysize;i++)
{
for (int j = 0; j < arraysize;j++)
{
std:cout << array[i][j];
}
}
}
int main()
{
int arraysize = 0, i;
cout << "Enter array in the range of 50 <= size <= 200: "; // records the users input
cin >> arraysize;
int* array = new int[arraysize], freq[10];
array_gen(array, arraysize);
cout << "unSorted array is:"; // shows the unsorted array
arraydis(array, arraysize);
}
You probably should use a vector of vector of ints, using std::vector.
#include<iostream>
#include <random>
#include<time.h>
#include<iomanip>
#include <vector>
#include <map>
using namespace std;
// generate the array with random numbers
void array_gen(vector<vector<int>> & array, size_t arraysize)
{
array.resize(arraysize);
for (auto& line : array)
line.resize(arraysize);
for (size_t i = 0; i < arraysize; i++)
{
for (size_t j = 0; j < arraysize; j++)
{
array[i][j] = rand() % -12 + 8; // generate numbers from 0 to 10
}
}
}
void arraydis(const vector<vector<int>> & array)
{
for (size_t i = 0; i < array.size(); i++)
{
for (size_t j = 0; j < array.size(); j++)
{
cout << array[i][j] << " ";
}
cout << "\n";
}
}
int main()
{
int arraysize = 0, i;
cout << "Enter array in the range of 50 <= size <= 200: "; // records the users input
cin >> arraysize;
vector<vector<int>> array;
array_gen(array, arraysize);
cout << "unSorted array is:\n"; // shows the unsorted array
arraydis(array);
}

How can I read specific lines of a text file into an array of type int in C++?

I need to read text files into an array. The text files are formatted so that the first line contains the array size and the following lines are the elements of the array:
6
5
3
2
1
6
4
Where the array size equals 6. The files need to be read in this format:
a.exe < testfiles/input
Here's what I have so far:
int main(){
int arraySize = 0;
cin >> arraySize;
int array[arraySize];
for(i = 1; i < arraySize; i++){
cin >> array[i];
}
for(j = 0; j < arraySize-1; j++){
//insertion sort here
}
}
The array remains all zeros but is the correct size. Can anyone see my error?
EDIT: I've fixed the array to be dynamically allocated. The program now executes without an error, but now the entire array is full of the second entry of the text file, in this case, 5.
Since this question reads like a homework assignment, I'm guessing you are not allowed to use std. On the off chance you are, however, here is a much safer way to accomplish what you are attempting:
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> nums;
int arraySize;
cin >> arraySize;
for(int i = 0; i < arraySize; i++){
int value;
cin >> value;
nums.push_back(value);
}
for (auto num : nums)
cout << num << " ";
return 0;
}
In a C++ array declaration, array size must be an integral const expression. Simplest change is to use a dynamic array:.
int main(){
using namespace std;
int arraySize = 0;
cin >> arraySize;
int * array = new int[arraySize];
for(int i = 1; i < arraySize; i++){
cin >> array[i];
}
for(int j = 0; j < arraySize-1; j++){
//insertion sort here
}
delete [] array;
}

Squaring numbers in array, finding the sum and the biggest number

I have a task to square all the elements of array, separate them with ",", then find a sum of the squared array and find the biggest number of it. I managed to square them and find the sum, but I can't find the biggest number and the program is also printing "," at the end of new array.
This is my code:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10];
int n,sum=0,kiek=0,max=a[0];;
cin>>n;
for(int i=0;i<n;i++)
{cin>>a[i];
a[i]*=a[i];
sum=sum+a[i];
}
for (int i = 0 ; i < n ; i++)
{ cout <<a[i] << ","; }
cout<<endl ;
cout<<"suma " <<sum;
cout<<endl;
for(int i=0;i<10;i++)
{if(max<a[i])
{
max = a[i];
}
}
cout<<"max "<<max;
return 0;
}
This is the screenshot of my program result when I run it
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10];
int n, sum = 0; // Remove some unused variables
// Input //
cin >> n;
for(int i = 0; i < n; i++){
cin >> a[i];
a[i] *= a[i];
sum += a[i];
}
// List a[] and sum //
for (int i = 0 ; i < n - 1 ; i++) {
cout << a[i] << ", ";
}
cout << a[n - 1] << endl; // Just for a little beauty
cout << "suma " << sum << endl;
// Find Max //
int max = a[0]; // max should be declared there,
// because a[0] has not entered data at the first
for(int i = 0; i < n; i++) { // use n, not 10
if(a[i] > max){
max = a[i];
}
}
cout << "max " << max;
return 0;
}
Unchecked.
Please add indents, spaces and comment, this is a good habit.
Comment : If you are going to get the size of the array at run-time, it is better to use STL containers or pointers. Your issue lies here :
---> for(int i=0;i<10;i++)
{if(max<a[i])
Good luck.

How to print the smallest value of 10 numbers entered by the user in C++

This program reads from the user 10 integers and prints the smallest number.
so here is an example of my code:
#include <iostream>
using namespace std;
int main () {
int n,min=1;
for (int i = 0 ; i<10 ; i++){
cin>>n;
if (n<min)
min = n;
}
cout <<min;
}
so here is my question: Why do I get "1" printed if I enter from 2 to 11 you will probably say because of the if condition nothing will be executed so it will print the "1" which is initialized so Is there another way to code this?
To calculate a min from the values, you shouldn't initialize the variable. Assume the first value you have is the min, before starting the loop.
cin>>n;
min=n;
To be consistent with the fact that we want the min value of 10 numbers, we need to iterate one less time.
To do that, simply change
for (int i = 0 ; i<10 ; i++)
to
for (int i = 0 ; i<9 ; i++)
You are outputting 1 because that is the value you initialize min as, and the loop never updates min if all the values you enter are greater than 1.
You need to initialize min to the first value entered:
#include <iostream>
int main () {
int n, min;
for (int i = 0; i < 10; i++) {
std::cin >> n;
if ((n < min) || (i == 0))
min = n;
}
std::cout << min;
return 0;
}
Or:
#include <iostream>
int main () {
int n, min;
cin >> min;
for (int i = 1; i < 10 ; i++) {
std::cin >> n;
if (n < min)
min = n;
}
std::cout << min;
return 0;
}
Alternatively, put the values in an array and use std::min_element():
#include <iostream>
#include <algorithm>
int main () {
int arr[10];
for (int i = 0; i < 10; i++) {
std::cin >> arr[i];
}
std::cout << *std::min_element(arr, arr+10);
return 0;
}

For loops and addition

So I'm trying to use a for loop to fill the array with the numbers 1-8. Then add:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + numb = x
And then save it to an variable called x. I've done filling the array, but I don't know how to calculate the summary of the array + the number you enter. Would appreciate some help a lot.
#include <iostream>
using namespace std;
int main()
{
int array[8];
int numb;
int x; // x = summary of array + numb;
cin >> numb; // insert an number
for (int i = 0; i <= 8; i++)
{
array[i]=i+1;
}
for (int i = 0; i < 8; i++)
{
cout << array[i] << " + ";
}
}
Change the last part to:
x = numb;
for (int i = 0; i < 8; i++)
{
x = x + array[i];
}
cout<<x<<endl;
Realistically though, if you wanted to add the first n whole numbers, there's a formula:
(n*(n+1))/2;
so your whole program would be:
#include <iostream>
using namespace std;
int main()
{
int n = 8;
int numb;
cin >> numb; // insert an number
int x = n*(n+1)/2+numb;
cout<<x<<endl;
}
For the initial loop, remove the =:
for (int i=0; i<8; i++) { array[i]=i+1; }
For adding all the elements of an array, then adding numb:
var x=0;
for (int i=0; i<8; i++) { x += array[i]; }
x+=numb;
Then you can cout you x variable.
Unless you're required to use for loops and arrays (e.g., this is homework), you might want to consider code more like:
std::vector<int> array(8);
// fill array:
std::iota(begin(array), end(array), 1);
int numb;
std::cin >> numb;
int total = std::accumulate(begin(array), end(array), numb);
std::cout << "Result: " << total;