Array's in function confusion C++ [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to write a program that is passed an array of int and its size, and with that it prints out the numbers that are above average. Can anyone help clear this question up for me? I am sitting here wondering what the heck it is asking, and I am still quite new to programming so i don't know what to do. Sorry I sound so unable, but I am just confused. Thank you to anybody who can help. This is all I have so far:
Here is the updated code, but I still can't figure out why there aren't multiple average values displaying out, or how to get the output value to be correct.
EDIT: Changed a couple int values in the average() function to floats, but there is still a problem with the total value's at the end
#include <iostream>
using namespace std;
int average(int values[],int size);
int main(){
int size;
int values[] = {1,2,3,4,5,6};
cout << "Please input the size of the array" << endl;
cin >> size;
int output = average(values, size);
if(values[size]>output){
cout << "The values above average are: " << output << endl;
}
return 0;
}
int average(int values[],int size){
float temp=0.0;
for(int i=0;i<size;i++){
temp += values[i];
}
float end=temp/size;
return end;
}

your supposed to create an array of intigers and pass it to the average function, and need to pass the size(so that you know how many times to loop). In the loop in your Average function add all the values to a temporary value, then divide by the count input-ed to the function.
//returns the average
int average(int Values[],int Size){
//perhaps declare a temporary value here
for(int i=0;i<Size;i++){
//add all the values up and store in a temporary value
}
//here divide by Size and return that as the average
}
this
if(values[size]>output){
cout << "The values above average are: " << output << endl;
}
should be replaced with something like:
for(int i=0;i<size;i++){
if(values[i]>output){
cout << "The values above average are: " << values[i] << endl;
}
}

Here is a less convoluted solution than those posted. Main feature: It actually does do what it should:
#include <iostream>
template<size_t N>
float average( const int (&value)[N] ) {
float total( 0.0f );
// Sum all values
for ( size_t index = 0; index < N; ++index )
total += value[index];
// And divide by the number of items
return ( total / N );
}
int main() {
int value[] = { 1, 2, 3, 4, 5, 6 };
// Calculate average value
float avg = average( value );
const size_t count = ( sizeof( value ) / sizeof( value[0] ) );
// Iterate over all values...
for ( size_t index = 0; index < count; ++index )
// ... and print those above average
if ( value[index] > avg )
std::cout << value[index] << std::endl;
return 0;
}
Live example at Ideone. Output:
4
5
6

Related

nested for loop in a function array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am working on a c++ homework assignment for arrays and functions, and this is what I have so far and am not even sure if I am on the right path or not. These are the exact instructions..
Write a program to ask the user to enter a total of N numbers which you will store in main local array of Define N as a constant int and initialize it to 6. You will write the following functions:
FillArray( ) – accepts two inputs: (1) the array. (2) the array size. Returns nothing.
• Prompts the user to enter N elements (N = the array size and the variables you pass should have been defined as a constant int in main( )
• Use a for loop to enter and store the value of each element in the array
#include <iostream>
using namespace std;
int main(){
cout << "Enter 6 numbers for the array:" << endl;
FillArray();
return 0;
}
void FillArray(){
int n;
int array[6] = { 0, 0, 0, 0, 0, 0,};
void fillarray(const int n[], int size);
for (; n > 6; n++)
cin >> array[n];
cout << "Thank you\n";
}
Any suggestions or help would be appreciated.. thank you!
Write a program to ask the user to enter a total of N numbers which
you will store in main local array of Define N as a constant int and
initialize it to 6
int main()
{
const int N = 6;
int a[N];
//...
You will write the following functions: FillArray( ) – accepts two
inputs: (1) the array. (2) the array size.
//...
FillArray( a, N );
//...
void FillArray( int a[], int n )
{
cout << "Enter " << n << " numbers for the array: ";
for ( int i = 0; i < n; i++ )
{
cin >> a[i];
}
}
And the name of the function used in the program shall be declared before its using
void FillArray( int a[], int n );
int main()
{
//...

Why is this one, pointless line of code the only thing that makes this function work? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm learning C++ and decided to make a bunch of small, short functions to practice. This following bit of code will give me an incorrect answer:
float pairwiseSum(float data[], int arraySize, int naive_sum_size=8) {
if (arraySize <= naive_sum_size) {
return naiveSum(data, arraySize);
} else {
int m = arraySize / 2;
return pairwiseSum(&data[0], m) + pairwiseSum(&data[m], arraySize-m);
}
}
naiveSum in this case just iterates through an array accumulates the sum and appears to work fine. If I have an array of 64 1s, it will tell me the sum is 288.
However, this version of the code works perfectly every time:
float pairwiseSum(float data[], int arraySize, int naive_sum_size=8) {
if (arraySize <= naive_sum_size) {
cout << "";
return naiveSum(data, arraySize);
} else {
int m = arraySize / 2;
return pairwiseSum(&data[0], m) + pairwiseSum(&data[m], arraySize-m);
}
}
I'm using Fedora 21 and compiling with g++ 4.9.2
Why does one function work, but the other one fail?
Edit: the complete program as it appears in my main.cpp file is below.
#include <iostream>
#include <stdlib.h>
using namespace std;
float naiveSum(float data[], int arraySize) {
float sum;
for (int i = 0; i < arraySize; i++)
sum += data[i];
return sum;
}
// Divide-and-conquer algorithm is a little faster than the
// Kahan Summation Algorithm, but also less accurate.
float pairwiseSum(float data[], int arraySize, int naive_sum_size=8) {
if (arraySize <= naive_sum_size) {
//cout << "";
return naiveSum(data, arraySize);
} else {
int m = arraySize / 2;
return pairwiseSum(&data[0], m) + pairwiseSum(&data[m], arraySize-m);
}
}
int main() {
const int SIZE = 64;
const int rndRange = 100;
// generate random array
srand(time(NULL));
float xs[SIZE];
for (int i=0; i<SIZE; i++)
// +1 prevents division by zero
//xs[i] = rand() % rndRange / (float)(rand() % rndRange + 1);
xs[i] = 1;
// Print kahan sum of random array
//cout << "Kahan Sum: " << kahanSum(xs, SIZE) << endl << endl;
cout << endl << pairwiseSum(xs, SIZE) << endl;
return 1;
}
Edit: yes, it was indeed a problem with sum not being intialized. Thanks for your help.
sum is not initialized in naiveSum. The rest is just undefined behavior (caused by indeterminate value in sum) manifesting itself differently with or without that irrelevant cout << "" line.
There are many different ways cout << "" can cause that indeterminate initial value of sum to end up being zero and thus create an appearance of naiveSum working properly.

c++: I want to make a arithmetic progression using array, but it gives me messy code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
#include<iostream>
using namespace std;
//prototype
void fillArray(int[], int, int);
void printArray(int[], int);
int main()
{
srand(time(0)); // initialize random number generator
const int size = 5, SIZE=10;
int ar1[size], ar2[size],inc;
cout << "Enter the first value and increment for ar1: ";
cin >> ar1[0] >> inc;
cout << "Enter the first value and increment for ar2: ";
cin >> ar2[0] >> inc;
cout << "(1) ar1:\n";
fillArray(ar1, size, inc);
printArray(ar1, size);
system("pause");
return 0;
}
void fillArray(int ar[], int size, int inc)
{
for (int i = 1; i < size; i++)
{
ar[i] = ar[0] + inc;
cout << ar[size];
}
}
void printArray(int ar[], int size)
{
for (int i = 0; i < size; i++) {
cout << ar[i] << ' ';
}
cout << endl;
}
Ask the user to input ar1[0] and inc.the first one ar1[0] is settled by user input, and the rest is increased by inc.So if I enter 4 3 ,it should return 4 7 10 13 16. My outcome is like this:
I know there is something wrong with the function fillArray but I don't know how to fix it. Can anyone tell me the solution? Thanks
Yes there's something wrong with your function fillArray. It assumes that the first element is initialized (which is, indeed) but then doesn't initialize the other elements in ascending order, because you always add inc to the value of the first element. Moreover it prints out ar[size] which is out of bounds at every step (the first strange numbers in your output). You can fix with this:
void fillArray(int ar[], int size, int inc)
{
for (int i = 1; i < size; i++)
{
ar[i] = ar[i-1] + inc;
}
}
Or you can decide to pass the first value as a parameter too.
I assume you wanted to use size, even if you also declare another similar variable named SIZE with a different value. You should also consider using std::vectors instead of arrays as a safer a more practical option.
Finally, in your code you ask the user to input inc twice (overwriting it) before using it.

Project Euler task #8, code starts returning wrong answers after certain point [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am having some sort of a problem in a task from
https://projecteuler.net/problem=8, (finding highest product of 13 consecutive numbers from a 1000-number string) where up to some point the program gives me predictable results and then the function returns a number very close to the unsigned long long int range. The point where it occurs depends on the values which were read, for instance if the string of numbers consisted mostly of 8s and 9s, it would happen sooner than it would if it had only 5s and 6s. Why does it happen?
#include <iostream>
#include <fstream>
using namespace std;
int product (int res, int a, char buffer[]){
for (int i = 0; i < a; i++){
//simple char to int conversion
res*=(buffer[i] - '0');
}
return res;
}
int main () {
char check;
int res = 1;
fstream plik;
plik.open ("8.txt");
unsigned long long int high;
unsigned long long int result;
//main function in the program
if (plik.good()){
char buffer [13];
for (int i = 0; i < 13; i++){
plik >> buffer[i];
}
result = product (res, 13, buffer);
high = result;
cout << high << endl;
//the main checking loop
while (!plik.eof()){
//just an interruption to make it possible to view consecutive products
//the iteration in the buffer
for (int i = 0; i < 12; i++){
buffer[i] = buffer[i+1];
}
plik >> buffer[12];
result = product (res, 13, buffer);
//comparison between the current product and highest one
if (high < result){
high = result;
}
cin >> check;
cout << high << endl;
//again a tool for checking where the problem arises
for (int i = 0; i < 13; i++){
cout << buffer[i] << " ";
}
cout << endl;
}
plik.close();
cout << high << endl;
}
return 0;
}
The program prints out the currently highest product and all the numbers currently contained in the array.
It looks like this:
The error
Use unsigned long long int instead of int to calculate the product. The product of 13 digits can easily become larger than the largest int.

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.