Ok, I also need to calculate and display each height after a 5% increase using a separate 10-element array. Any ideas? Sorry about all this. This is my first time using arrays.
#include <iostream>
using namespace std;
int main()
{
int MINheight = 0;
double height[10];
for (int x = 0; x < 10; x = x + 1)
{
height[x] = 0.0;
}
cout << "You are asked to enter heights of 10 students. "<< endl;
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter height of a student: ";
cin >> height[x];
}
system("pause");
return 0;
}
Simply loop like this:
MINheight = height[0];
for (int x = 1; x < 10; x++)
{
if (height[x] < MINheight)
{
MINheight = height[x];
}
}
std::cout << "minimum height " << MINheight <<std::endl;
Side Note: you should not name a local variable starting with Capital letter, using x as array index is also kind of strange, though they both work fine, but not good style.
You may also use std::min_element as follows:
std::cout << *std::min_element(height,height+10) << std::endl;
//^^using default comparison
To put elements in separate array with increased heights and display them, do the following:
float increasedHeights[10] = {0.0};
for (int i = 0; i < 10; ++i)
{
increasedHeights[i] = height[i] * 1.05;
}
//output increased heights
for (int i = 0; i < 10; ++i)
{
std::cout << increasedHeights[i] << std::endl;
}
Essentially, you can keep track of the minimum value as it is being entered, so:
cout << "You are asked to enter heights of 10 students. "<< endl;
MINheight = numerical_limits<int>::max
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter height of a student: ";
cin >> height[x];
if(height[x] < MINheight)MINheight = height[x];
}
cout << "Minimum value was: " << MINheight << "\n";
What this does is create a variable with its value the maximum possible value, then when ever a new value is entered by the user, check if it less than current minimum, if so store it. Then print out the current minimum at the end.
Related
#include <iostream>
using namespace std;
int main()
{
int n, a, b,min,max, Prod = 1, Sum = 0;
cout << "Initialize an array n: ";
cin >> n;
do
{
cout << "Input the start value: ";
cin >> a;
cout << "Input the end value: ";
cin >> b;
if (!(a < b))
{
cout << "a is bigger than b, please enter new values " << endl;
continue;
}
} while (!(a < b));
int* lpi_arr;
lpi_arr = new int[n];
srand(time(NULL));
cout << "Int numbers from " << a << " to " << b << endl;
for (int i = 0; i < n; i++)
{
lpi_arr[i] = rand() % (b - a) + a;
cout << lpi_arr[i] << " ";
}
max = lpi_arr[0];
for (int i = 0; i < n; i++)
{
if (max < lpi_arr[i])
max = lpi_arr[i];
}
min = lpi_arr[0];
for (int i = 0; i < n; i++)
{
if (min > lpi_arr[i])
min = lpi_arr[i];
}
cout << "\nmin element is = " << min << endl;
cout << "\nmax element is = " << max << endl;
for (int i = max + 1; i < min; i++)
Prod *= lpi_arr[i];
for (int i = 0; lpi_arr[i] < 0 && i < n; i++)
Sum += lpi_arr[i];
cout << "Summ =" << Sum << endl << "Prod = " << Prod << endl;
delete[] lpi_arr;
}
The main purpose of this code is to calculate the sum of negative numbers of an array, and multiplication of elements located between the maximum and minimum elements of an array.
The problem is that the code implements only 1(one) as an answer, and I don't know how to change it. Every other part of the code works well, but if you have any recommendations I'd also like to read it. Waiting for your help.
Your issue is that you're confusing array indexes with array values.
Here you're assigning max (and same with min) to an array value.
max = lpi_arr[i];
Here you're treating max (and same with min) as an array index.
for (int i = max + 1; i < min; i++)
Prod *= lpi_arr[i];
I am learning C++ and would like some help with functionality for my code below.
Quick summary/usage of my code: Program is to display randomized (x,y) coordinates and then print out the coordinates in a grid.
I got everything to work regarding randomizing (x,y) coordinates and then displaying their grid location.
The problem I am having is my code displays a separate grid for each coordinate instead of showing ALL coordinates on the same grid. [I attached a picture of my current output below].
I know this is a functionality issue.. but I am having trouble thinking of how to manipulate my loops so that the coordinates can be displayed first, followed by ONE grid with all the coordinates on it... I hope this makes sense.
Snippet of my code:
//Note: value of n and k is given by user earlier in the code
vector<vector<int> > vec( n , vector<int> (n));
cout << "\nGrid with city locations:\n";
for(i=0; i<k; i++) {
//random select int coordinates (x,y) for each K(cities)
x = rand() % n + 0;
y = rand() % n + 0;
arrCity[i] = i;
//display coordinates for city 1..city2.. etc
cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;
//display cities on grid
for (int rows=0; rows < n; rows++) {
for (int columns=0; columns < n; columns++) {
if ((rows == y) && (columns == x)) {
cout << "|" << (i);
} else {
cout << "|_";
}
}
cout << "\n";
}
cout << "\n";
}
Current Output:
As you can see there's a separate grid for each 'city coordinate'
You need to store all city coordinates in order to display them on a single grid print.
In the code below I changed a few things in order to hopefully address your problem.
I have moved all city-related data into a structure
Then all cities are initialized before the grid output
When printing the grid, we have to search all cities if their coordinates match the current position, if so, we print the corresponding index.
Live Demo
#include <vector>
#include <iostream>
struct City
{
int index;
int x, y;
City(int index_, int x_, int y_)
: index(index_), x(x_), y(y_)
{ }
};
int main()
{
int n = 10;
int k = 6;
std::vector<City> arrCity;
arrCity.reserve(k);
for(int i = 0; i < k; i++)
arrCity.emplace_back(i, rand() % n, rand() % n);
std::cout << "\nGrid with city locations:\n";
for (int k = 0; k < arrCity.size(); k++)
std::cout << "City " << arrCity[k].index << ": (" << arrCity[k].x << "," << arrCity[k].y << ")" << std::endl;
//display cities on grid
for (int i=0; i < n; i++) {
for (int j=0; j < n; j++) {
int w = -1;
for (int k = 0; k < arrCity.size(); k++)
if ((i == arrCity[k].y) && (j == arrCity[k].x))
w = k;
if (w >= 0)
std::cout << "|" << arrCity[w].index;
else
std::cout << "|_";
}
std::cout << "\n";
}
return 0;
}
You need to track which cells already has been visited. That's why you need to take another array which stores the cells that are already visited and by which value.
int vis[n][n];
memset(vis, -1, sizeof vis);
for(i=0; i<k; i++) {
//random select int coordinates (x,y) for each K(cities)
x = rand() % n + 0;
y = rand() % n + 0;
arrCity[i] = i;
vis[x][y] = i;
//display coordinates for city 1..city2.. etc
cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;
//display cities on grid
for (int rows=0; rows < n; rows++) {
for (int columns=0; columns < n; columns++) {
if (vis[rows][columns] != -1) {
cout << "|" << (vis[rows][columns]);
} else {
cout << "|_";
}
}
cout << "\n";
}
cout << "\n";
}
Output:
So I need to create a function to find the sum of rows in my 2D array. Array is fixed, matrix[5][5], and user inputs 25 integers.
I know how to find the sum of my rows using the following code:
//for sake of ease lets say user inputs numbers 1-25
for (r = 0; r < 5; r++)
{
for (c = 0; c < 5; c++)
{
sum = sum + matrix[r][c]
}
cout << "\n" << sum;
sum = 0;
}
//the code above will display the sum of each row as follows:
15
40
65
90
115
I want to display the totals for each row as
Row 1:
Sum =
Row 2:
Sum =
etc...
How do I pass the array to a function in order to find the sum of each row and how do I separate the individual sum of rows to display like I want?
I have read a chapter on passing multidimensional arrays to functions like 4 times over in a c++ beginners book, I have read and looked at many different forums online and maybe it is because I have been starring at it for too long I am not seeing the answer but I have given myself a headache. I really just want to understand how to pass it. I have tried to modify the passing of an array to a function to find the sum of all the integers in the array but I could not get it to work for what I needed.
ETA(10/7/2017 1535 PCT):
So I am trying the following to try and pass my 2D array to a function and calculate the sum...
void total(int matrix[][5], int n, int m)
{ // I am getting an error here though that states "expected a ';' "
for (r = 0; r < n; r++)
{
int sum = 0;
for (c = 0; c < m; c++)
sum += matrix[r][c];
}
cout << "Row " << r << " = " << sum << endl;
}
Is this even how you create a function with a 2D array?
ETA (10/7/2017 2100 PCT)
So I think I figured out how to pass the array, but I cannot seem to get it to do the proper math, meaning this does not sum up the rows....
#include "stdafx.h"
#include "iostream"
using namespace std;
int total( const int [][5], int, int);
int main()
{
int c, r, matrix[5][5];
cout << "Please input any 25 numbers you'd like, seperated by a space, then press enter:" << endl;
for (r = 0; r < 5; r++)
{
for (c = 0; c < 5; c++)
{
cin >> matrix[r][c];
}
}
getchar();
cout << endl << "Matrix: " << endl;
for (r = 0; r < 5; r++)
{
cout << endl;
for (c = 0; c < 5; c++)
{
cout << matrix[r][c] << "\t";
}
cout << endl;
}
cout << "Please press the enter key to get the sums of each row << endl;
getchar();
cout << "Sum = " << total << endl; //this displays "Sum = 013513F2"
system("PAUSE");
}
int total(const int matrix[][5], int R, int C)
{
int sum = 0;
for (int r = 0; r < R; r++)
{
for (int c = 0; c < C; c++)
{
sum = sum + matrix[r][c];
}
}
return sum;
}
Passing an array of any dimension can be done by using the syntax: type (&name)[numElements] by reference. Or by pointer you would replace the & with a *. Below is a basic example that compiles, which passes the array by reference to the pass2Darray function. Alternatively, you could simply use a regular array with size [5 * 5] to ensure that it's entirely contiguous. Since a 2D array is not natively something that exists in C++. And then, since you're working with matrices, you can access it in column major by [row * i + col] or in row major by [col * j + row].
#include <iostream>
// Reference to multiArray
// int (&someName)[num][num]
// Pointer to multiArray
// int (*someName)[num][num]
void pass2Darray(int (&passed)[1][1]) {
std::cout << passed[0][0];
}
int main() {
int arr[1][1] = { {1} };
pass2Darray(arr);
return 0;
}
Just to help the future readers this is what I came up with. Took a lot of research and a million different trial and errors but here it is:
int math(int a[5]) //The function the array has been passed to
{
//Declaring the variables in the function
int sum = 0;
double average = 0;
int min = 0;
int max = 0;
min = a[0]; //setting the minimum value to compare to
for (int C = 0; C < 5; C++) //Creates the loop to go through the row elements
{
sum = sum + a[C]; // calculates the sum of each row
if (a[C] < min) min = a[C]; //assigns the element of lowest value from row
if (a[C] > max) max = a[C]; //assigns the element of highest value from row
}
average = sum / 5; //calculates the average of each row
cout << "Sum = " << sum << endl; //Outputs sum
cout << "Average = " << average << endl; //Outputs average
cout << "Min = " << min << endl; //Outputs min
cout << "Max = " << max << endl; //Oututs max
cout << endl;
return 0; //return value for function
}
Down the line that calls the function and displays the output I was looking for:
for (r = 0; r < 5; r++) //sets up row loop for display
{
cout << "Row " << r+1 << ":" << endl;
math(matrix[r]); //displays calculations done in math function
cout << endl;
}
Hope this helps someone down the road...
I'm kind of new to C++ so last night I thought of something. I want to print out numbers from 1-100 but with 10 numbers per line. I'm aware my code is below is wrong as it just prints 1-100 vertically. If anyone can shed some light to my question, it would be greatly appreciated. Thanks for reading :)
#include <iostream>
using namespace std;
int main() {
for(int x = 1; x <= 100; x++) {
cout << x << endl;
}
}
So you want to print 10 numbers, then a carriage return, and then 10 numbers, then a carriage return, and so on, correct?
If so, how about something like:
for(int x = 1; x <= 100; x++) {
cout << x << " ";
if ((x%10)==0) cout << endl;
}
Use the modulo operator % to determine if a number is a multiple of another:
for(int x = 1; x <= 100; x++) {
if( x % 10 == 0 ) cout << endl;
cout << x << " ";
}
How about
int main() {
for(int x = 1; x <= 100; x++) {
cout << x << " " ; //Add a space
if ( x % 10 == 0 ) {
cout << endl //Put out a new line after every 10th entry?
}
}
}
Print new line when it can be device by 10.
for(int x = 1; x <= 100; x++) {
cout << x << ",";
if ((x % 10) == 0) {
cout << endl;
}
}
for(int i=1; i<=100; i++) {
i%10==0 ? cout << i<<endl : cout<<i<<" ";
}
I'm trying to get the program to display the current height of the child and the estimated height of the child.
I have it displaying the before and after for the first child but can't get it to display the estimated height for the rest of the children.
I would be very grateful if anyone could help me figure this out. Thanks!
Here is the code that I have:
#include <iostream>
using namespace std;
int main()
{
double height [10];
double chgHeight [10];
for (int x = 0; x < 10; x = x + 1)
{
height[x] = 0.0;
chgHeight[x] = 0.0;
}
cout << "You will be asked to enter the heights of ten children."<< endl;
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter height of child " << endl;
cin >> height[x];
}
chgHeight[0] = height[0] * .05 + height[0];
for (int x = 0; x < 10; x = x + 1)
{
cout << "Child " << x+1 << ": Current " << height[x] << " Expected "<< chgHeight[x] << endl;
}
system("pause");
return 0;
}
chgHeight[0] = height[0] * .05 + height[0];
You're only ever setting the first child's chgHeight.
Edit:
For your output, you're going through the array or heights, which is indexed by the child number (x):
for (int x = 0; x < 10; x = x + 1)
{
cout << "Child " << x+1 << ": Current " << height[x]
<< " Expected "<< chgHeight[x] << endl;
}
Your estimated height is calculated from the child's current height, which you have in this loop ( height[x] ). So, you have everything you need right there to output the estimated height.
If you have no need to save the calculation for later, there's really no need to create a second chgHeight[] array in your code; just calculate and output the estimated height in that loop for each child.
You are not setting the estimated height for the rest of the children, only the first:
chgHeight[0] = height[0] * .05 + height[0];
Put that in a loop.
chgHeight[0] = height[0] * .05 + height[0];
This line only calculates the estimated height of the first child. You'll need to put this in a loop as well (changing the indices to your loop variable) to calculate all 10.