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.
Related
I want a program that asks the number of rows and columns of the multidimensional array and then using For loop iterate values in the array.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n, m, x;
int a[n][m];
cin>>n>>m;
for(int i; i<n ; i++)
{
for(int j; j<m ; j++)
{
cout<<"Enter the values";
cin>>x;
a[i][j] = x;
}
}
return 0;
}
here it gets error:
main.cpp|6|warning: 'm' is used uninitialized in this function [-Wuninitialized]|
main.cpp|6|warning: 'n' is used uninitialized in this function [-Wuninitialized]|
You can't declare the array unknown size. You must do it dynamically.
#include <iostream>
using namespace std;
int main()
{
int n = 0, m = 0;
//. Get the matrix's size
while (true)
{
cout << "Input the row count: "; cin >> n;
cout << "Input the column count: "; cin >> m;
if (n < 1 || m < 1)
{
cout << "Invalid values. Please retry." << endl;
continue;
}
break;
}
//. Allocate multi-dimensional array dynamically.
int ** mat = new int *[n];
for (int i = 0; i < n; i++)
{
mat[i] = new int[m];
}
//. Receive the elements.
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << "Input the element of (" << i + 1 << "," << j + 1 << "): ";
cin >> mat[i][j];
}
}
//. Print matrix.
cout << endl << "Your matrix:" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << mat[i][j] << "\t";
}
cout << std::endl;
}
//. Free memories.
for (int i = 0; i < n; i++)
{
delete[] mat[i];
}
delete[] mat;
return 0;
}
If you like to use stl, it can be simple.
#include <iostream>
#include <vector>
using namespace std;
using ROW = vector<int>;
using MATRIX = vector<ROW>;
int main()
{
int n = 0, m = 0;
MATRIX mat;
cin >> n >> m;
for (int i = 0; i < n; i++)
{
ROW row;
row.resize(m);
for (int j = 0; j < m; j++)
{
cin >> row[j];
}
mat.push_back(row);
}
for (auto & row : mat)
{
for (auto & iter : row)
{
cout << iter << "\t";
}
cout << endl;
}
return 0;
}
Some comments.
Please never use #include<bits/stdc++.h>. This is a none C++ compliant compiler extension
Please do not use using namespace std;. Always use fully qualified names.
For the above to statements you will find thousands of entries here on SO
In C++ you cannot use VLAs, Variable Length Array, like int a[n][m];. This is not part of the C++ language
You should not use C-Style arrays at all. Use std::array or, for your case std::vector.
Use meaningful variable names
Write comments
Always initialize all variables, before using them!!!
And, last but not least. You will not learn C++ on this nonesens "competition - programming" sites.
And one of many millions possible C++ solutions (advanced) could look like that:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
// Read the dimension of the 3d data
if (unsigned int numberOfRows{}, numberOfCoulmns{}; (std::cin >> numberOfRows >> numberOfCoulmns) and (numberOfRows > 0u) and (numberOfCoulmns > 0u)) {
// Define a vector with the requested size
std::vector<std::vector<int>> data(numberOfRows, std::vector<int>(numberOfCoulmns, 0));
// Read all data
std::for_each(data.begin(), data.end(), [&](std::vector<int>& col) mutable
{ auto it = col.begin(); std::copy_n(std::istream_iterator<int>(std::cin), numberOfCoulmns, it++); });
// Show debug output
std::for_each(data.begin(), data.end(), [](std::vector<int>& col)
{std::copy(col.begin(), col.end(), std::ostream_iterator<int>(std::cout, "\t")); std::cout << '\n'; });
}
else std::cerr << "\nError: Invalid input given\n\n";
return 0;
}
I have a question about the exercise from my course:
Write a program that takes array of real numbers as parameter and replaces each element that is smaller than average of the first and last element, by this average. This is my code:
#include <iostream>
#include <string>
using namespace std;
void replaverage(int arr[], int n)
{
for (int i; i < 6; i++) {
cout << "Enter the numbers" << endl;
cin >> arr[i];
}
int f = arr[0];
int l = arr[n - 1];
double av = f + l / 2;
for (int i; i < n; i++) {
if (arr[i] < av) {
arr[i] = av;
}
}
}
int main()
{
int n;
int arr[n];
replaverage(arr, n);
cout << arr << " " << endl;
return 0;
}
Code is working, however as an output, it is giving some kind of address "0x7fff2306a5c0". I'm beginner so I apologize, maybe my error is stupid but I don't know how to fix it. Thanks for helping!
#include <iostream>
#include <string>
using namespace std;
void replaverage(int arr[], int n)
{
for (int i = 0; i < n; i++) {
cout << "Enter the number: ";
cin >> arr[i];
cout << endl;
}
int f = arr[0];
int l = arr[n - 1];
double av = (f + l) / 2;
for (int i = 0; i < n; i++) {
if (arr[i] < av) {
arr[i] = av;
}
}
}
int main()
{
int n = 6; // Making 6 since you had it hardcoded
int arr[n];
replaverage(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << endl;
}
return 0;
}
First problem: Initialize your loop counters to 0;
Second problem: Initialize n in main being passed as parameter to
something
Third problem: Your average calculation is incorrect. It should be (f+l) / 2. Otherwise it will be doing l/2 + f, which is incorrect.
Fourth problem: You need to loop over your array to see all the
elements
my program is focusing on Array elements for this lab, but I am not sure on how to set my average to a specific number that is requested. Any guidance would be helpful for this post
#include "pch.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
int arr[10], n, i, max, min, avg;
cout << "Enter the size of the array: ";
cin >> n;
cout << "Enter the elements of the array: ";
for (i = 0; i < n; i++)
cin >> arr[i];
max = arr[0];
for (i = 0; i < n; i++)
{
if (max < arr[i])
max = arr[i];
}
min = arr[0];
for (i = 0; i < n; i++)
{
if (min > arr[i])
min = arr[i];
}
avg = arr[0];
for (i = 0; i < n; i++)
{
if (avg > arr[i])
avg = arr[i];
}
cout << "Largest element: " << max;
cout << "Smallest element: " << min;
cout << "Average element: " << avg;
}
I would recommend using the += operator in your for loop and then dividing by n.
float sum = 0;
float avg = 0;
for(i = 0; i < n; i++)
{
sum += arr[i];
}
avg = sum / n;
Also, I would recommend using either a float or double instead of using an int for your average because otherwise you're doing integer division which will cut off the decimal. i.e. 5 / 2 = 2
i dont know whats wrong with my code but im getting same value of "sum" on the
screen..
assume that m and n are entered equal ....enter image description here
#include<stdio.h>
#include<malloc.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int n,m;
int *ptr1, *ptr2, *sum;
cout<<" enter the size of 1st and 2nd array : "<<endl;
cin>>n>>m;
ptr1=(int*)malloc(n*sizeof(int));
ptr2=(int*)malloc(m*sizeof(int));
sum=(int*)malloc((n)*sizeof(int));
cout<<"enter 1st array element :";
for(int i=0;i<n;i++)
{
cin>>*(ptr1+i) ;
}
cout<<"enter 2st array element :";
for(int i=0;i<m;i++)
{
cin>>*(ptr2+i);
}
for(int j=0;j<m||j<n;j++)
{
*(sum+j) = (*(ptr1) + *(ptr2)) ;
}
cout<<" the sum is "<<endl;
for(int j=0;j<m||j<n;j++)
{
cout<<*(sum+j)<<endl;
}
}
First, the reason you get the same number springs from where you form the sums.
In this loop
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = (*(ptr1)+*(ptr2));
}
you find the sum of the contents of ptr1 and ptr2 over and over which never change - this is always the first two numbers.
So, we could iterate over the arrays by indexing in j along as follows
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = (*(ptr1 + j) + *(ptr2 + j));
}
BUT what happens if m!=n? You'll walk off the end of the array.
If you change the loop to
for (int j = 0; j<m && j<n; j++)
{
*(sum + j) = (*(ptr1 + j) + *(ptr2 + j));
}
then you find the sum for pairs of numbers up to the smaller of m and n.
You will have to do likewise with the display of the results
for (int j = 0; j<m && j<n; j++)
{
cout << *(sum + j) << endl;
}
However, I believe you wanted to either display n numbers, regardless of which is bigger, or perhaps assume a 0 if there is no element. Also, I notice you have malloced and not freed - perhaps using a C++ array rather than C-style arrays is better? I'll come to that in a moment.
Let's do the C appraoch and have a 0 if we go beyond the end of an array.
This will work, but can be tidied up - comments inline about some important things
#include<stdlib.h>
#include <algorithm> //for std::max
#include <iostream>
using namespace std;
int main()
{
int n, m;
int *ptr1, *ptr2, *sum;
cout << " enter the size of 1st and 2nd array : " << endl;
cin >> n >> m;
ptr1 = (int*)malloc(n * sizeof(int));
ptr2 = (int*)malloc(m * sizeof(int));
sum = (int*)malloc((std::max(n, m)) * sizeof(int));
// ^--- sum big enough for biggest "array"
// data entry as before - omitted for brevity
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = 0;
if (j < n)
*(sum + j) += *(ptr1 + j);
if (j < m)
*(sum + j) += *(ptr2 + j);
}
cout << " the sum is " << endl;
for (int j = 0; std::max(n, m); j++)//however big it is
{
cout << *(sum + j) << endl;
}
free(ptr1); //tidy up
free(ptr2);
free(sum);
}
I know you said you wanted to use malloc and perhaps this is a practise with pointers, but consider using C++ idioms (at least you won't forget to free things you have maoolced this way).
Let's nudge your code towards using a std::vector:
First the include and the input:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, m;
vector<int> data1, data2, sum;
cout << " enter the size of 1st and 2nd array : " << endl;
cin >> n >> m;
cout << "enter 1st array element :";
for (int i = 0; i<n; i++)
{
int number;
cin >> number;
data1.push_back(number); //there is a neater way, but start simple
}
cout << "enter 2st array element :";
for (int i = 0; i<m; i++)
{
int number;
cin >> number;
data2.push_back(number);
}
This post shows a way to neaten up the data entry. However, let's do something simple and get the sum:
for (int j = 0; j < std::max(m, n); j++)
{
int number = 0;
if (j < n)
number += data1[j];
if (j < m)
number += data2[j];
sum.push_back(number);
}
And now for a C++ way to do output
cout << " the sum is " << endl;
for (auto item : sum)
{
cout << item << '\n';
}
}
Finally, let's have a brief think about the sum.
If you now #include <iterator> you can use an algorithm to put your sum into sum
std::transform(data1.begin(), data1.end(),
data2.begin(), std::back_inserter(sum), std::plus<int>());
However, note this won't fill with zeros. You could either make the vectors the same size, filled with zeros first, or lookup/discover ways to zip vectors of different sizes. Or stick with ifs in a loop as I demonstrated above.
Avoid malloc in C++. Just saying.
I highly encourage you to use a modern cpp data structure like a vector for storing your data. Thus, you don't have to worry about malloc and can access them far more easyly.
But now to your question: Your summation for loop is broken. Use
for(int j=0;j<m||j<n;j++)
{
*(sum+j) = (*(ptr1+j) + *(ptr2+j)) ;
}
Best regrads, Georg
I'm just a beginner of C++ and I want to write a program which inputs and then displays a matrix of order i * j. I have written the following program but it did not work.
Kindly guide me .
I think may be the method of accessing is not right or something like that.
Here is the program:
#include <iostream>
using namespace std;
int main() {
int i = 0,j = 0;
cout << "Enter no of rows of the matrix";
cin >> i;
cout << "Enter no of columns of the matrix";
cin >> j;
float l[i][j];
int p = 0, q = 0;
while (p < i) {
while (q < j) {
cout << "Enter the" << p + 1 << "*" << q + 1 << "entry";
cin >> l[p][q];
q = q + 1;
}
p = p + 1;
q = 0;
}
cout << l;
}
you cant define an array with variable length. You need to define a dynamic arrays or std::vector
#include<vector>
std::vector<std::vector<int> > l(i, std::vector<int>(j, 0));
And cout << l will only print out the value of a int** . To print out each individual integer, you need to loop against each of them.
for(int x = 0; x < i; ++i){
for(int y = 0; y < j; ++y){
cout << l[x][y] << " "
}
cout << "\n";
}
I rewrote your code:
(instead of alloc its better to use new in c++, and use delete to free the memory)
#include "stdafx.h"
#include<iostream>
#include <conio.h>
using namespace std;
int _tmain()
{
int row,col;
cout<<"Enter no of rows of the matrix";
cin>>row;
cout<<"Enter no of columns of the matrix";
cin>>col;
float** matrix = new float*[row];
for(int i = 0; i < row; ++i)
matrix[i] = new float[col];
int p=0,q=0;
for(unsigned i=0;i<row;i++) {
for(unsigned j=0;j<col;j++) {
cout<<"Enter the"<<i+1<<"*"<<j+1<<"entry";
cin>>matrix[i][j];
}
}
for(unsigned i=0;i<row;i++) {
for(unsigned j=0;j<col;j++) {
cout<<matrix[i][j]<<"\t";
}
cout<<endl;
}
getch();
return 0;
}