C++, function with changing amount of inputs (idk how to describe) - c++

The funcion HIGHEST is all good and accepts variable number of arguments. The problem is how do I do variable amount of input? (idk what terms should be use to describe it, but examples should clear things up...)
/*cout << highest(n, A[0],A[1],A[2],A[3]) <<endl;
this is what I would like to achieve,
but with a change - the number of array changes with
the input file and n defines how many of these will be.
ex.: if n = 7 it needs to be (n, A[0],A[1],A[2],A[3], A[4], A[5], A[6])
*/
Duom.txt file if needed (i am now only working with 1st number 4 under it others will follow same/similar thing as 1st row they are not important now)
4
2008 5 2000.00 400.25
2010 5 4000.00 320.25
2009 9 3385.00 254.45
2008 6 1900.00 612.59
#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <cstdarg>
using namespace std;
//Variable number of arguments in C++
int highest (int num,...) {
va_list valist;
int max = 0;
int a;
va_start(valist, num);
for (int i = 0; i < num; i++) {
a = va_arg(valist, int);
if(max < a) max = a;
else ;
}
va_end(valist);
return max;
}
int main () {
int n, A[25], B[25];
double C[25], D[25];
ifstream fd ("Duom.txt");
ofstream fr ("Rez.txt");
fd >> n;
cout << n <<endl;
for(int i = 0; i < n; i++){
fd >> A[i] >> B[i] >> C[i] >> D[i];
}
cout << highest(n, ) <<endl;
/*cout << highest(n, A[0],A[1],A[2],A[3]) <<endl;
this is what I would like to achieve,
but with a change - the number of array changes with
the input file and n defines how many of these will be.
ex.: if n = 7 it needs to be (n, A[0],A[1],A[2],A[3], A[4], A[5], A[6])
*/
return 0;
}

is there a specific reason you want the function Highest to get all array integers separately? Also - why did you choose to use an array instead of a vector?
Assuming that you want to use an array, I'd suggest to change the function's arguments as follows:
int highest (int num,int *arr);
where arr is the name of your array and in fact a pointer to the first integer of the array.
Then, inside the function, you can just access the array using subscript notation or dereferencing:
first_array_int=*(arr); //dereferencing example
second_array_int=*(arr+1); //dereferencing example
or
first_array_int=arr[0]; //subscript example
second_array_int=arr[1]; //subscript example
note that by doing that you can change the passed array within the function.
Again, I'd suggest to use a vector instead, then define the function:
int highest (int num,vector <int> *A);
if you want to pass a pointer, or:
int highest (int num,vector <int> A);
if you want to pass by value. Ofcourse, don't forget to include the vector library with
#include <vector>
I hope I understood your question well and that this is helpful.
Goodluck!
Guy

Related

Understanding how to initialize the ith element of an array parameter with the i+1th number of a harmonic series?

This is my first C++ class and I'm not really sure how to proceed in my homework, as understanding arrays has been fairly difficult for me. I've successfully completed the 1st task, but got stuck understanding the 2nd and don't really know how to start it.
The tasks are:
Define a function named harmonicNum() that finds and returns the nth harmonic number using an iteration statement where n is a positive int-typed argument provided by the caller.
Given a valid array index i, define a function named fillHarmonic() that iteratively calls harmonicNum() to initialize the ith element of an array parameter wit the i+1th number of the harmonic series. I must define this function to work on a one-dimensional array of any size.
This is the code that I have so far:
#include <iostream>
#include <cmath>
using namespace std;
double harmonicNum(int n);
int n;
int main()
{
do
{
cout << "Please input a positive integer: " << endl;
cin >> n;
} while (n < 0);
cout << harmonicNum(n) << endl;
return 0;
}
double harmonicNum(n)
{
double harmonic = 0.00
for (int i = 1; i <= n; i++)
{
harmonic = harmonic + 1.00 / i;
}
return harmonic;
}
Something like this?
Method definition:
void fillHarmonic(double &i_elem, int i){
i_elem = harmonicNum(i+1);
}
Call without error checking:
double arr [5];
//TODO init values
for(int i = 0; i < (sizeof(arr)/sizeof(double)); i++ ){
fillHarmonic(arr[i], i);
}

C++ problem where the value assigned to a variable is getting changed even though it hasn't been modified yet [duplicate]

This question already has answers here:
Uninitialized variable behaviour in C++
(4 answers)
Closed 1 year ago.
Please help me with this strange problem where the input value is given as 4 (i.e. n = 4) and after a for loop the same value is getting displayed as 2, but why? It was not used anywhere (AFAIK) and it shouldn't get changed (I have no clue about it).
The original problem on HackerRank.
MY CODE >>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n;
int arr[n];
cin >> n; // input given from stdin is 4
cout << n << "\n"; // outputs 4
for(int i=0; i<n; i++){
scanf("%d",&arr[i]);
}
cout << n << "\n"; // outputs 2 (but why?)
for(int i=n-1; i>=0; i--){
printf("%d ",arr[i]); // if it were n = 4, then i will go from 3 to 0, but it goes from 1 to 0 (as n=2, but again, why?)
}
return 0;
}
Thank you for any help!
int n;
int arr[n]; // <<<<<< I magically know what n will be after the user types it!
cin >> n; // input given from stdin is 4
First of all, that's not even legal in C++. As a gcc extension to support C style VLA's, what is the value of n when the array declaration is seen? You have not read it yet!!
Instead, use:
int n;
cin >> n;
std::vector arr(n);
Although this still is not the "C++ way" as you are pre-defining the entire collection and then assigning to each element in turn; as opposed to adding each element to the collection. This is not a big deal with an int but more generally you don't want dead unused items in a collection; rather they simply don't exist at all.
std::vector arr; // don't pre-allocate any size
for(int i=0; i<n; i++){
int val;
scanf("%d",&val); //<<< uhhhhhh. you know about `cin` why this?
arr.push_back(val);
}

Program not calculating No. of combinations on each set from an n-digit number

The problem is to take 3 inputs:
1) No. of test cases
2) No. of digits in a number
3) N space separated digit numbers
And to output :
1) No. of sets
2) No. of combinations in each set
I want to print those outputs but No of combination output is returning zero on each and every set
I've already tried troubleshooting and debugging the problem, but none of those worked....
/* Read input from STDIN. Print your output to STDOUT*/
#include<iostream>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
using namespace std;
int factorial (int count);
int main(int argc, char *a[])
{
//intialize variables
int i,T,b,S[i],N,NN[i],C[i],count=0;
cin >> T;
while(T>0) {
cin >> N;
for(i=0;i<N;i++) {
cin >> NN[i];
if(i<N-1) {
S[i] = (N-i);// S[i] is Category 02
count++;
}//end of if
}//end of for loop
for(int j=0;j<N;j++) {
C[i] = factorial(count)/(factorial(i)*factorial(count - i));//
}//end of for loop
cout <<"No. of sets =" <<count++<<endl;
for(int k=0;k<N;k++) {
cout<<"No.of combinations on each set :";
cout<<C[i]<<endl;
} // end fo for loop
}//end of while loop
return 0;
}//end of main
int factorial(int count)
{
int i;
for(i = count-1; i > 1; i--)
count *= i;
return count ;
}//end of function
THIS OUTPUT IS COMING:
"No. of combinations on set 0 : 0"
"No. of combinations on set 1 : 0"
………….
Well it's gone wrong already here
//intialize variables
int i,T,b,S[i],N,NN[i],C[i],count=0;
What's the value of i here? Answer, it doesn't have one. If i doesn't have a value then what's the size of this array NN[i]? Answer, who knows.
When you declare an array in C++, you must give it a size. The size cannot be a variable, it must be a cosntant. And it especialy cannot be a variable without a value.
Your program has undefined behaviour.
EDIT - this would be an improvement
#include <vector>
int main()
{
int T;
cin >> T;
while (T > 0)
{
int N;
cin >> N;
std::vector<int> NN(N), S(N);
for (int i = 0; i < N; i++)
{
...
First improvement is that I using a std::vector instead of an array. Unlike arrays vectors can have variable sizes. Second improvement is that I only declare variables when I need them, I don't declare all the variables at the start of the function. So I only declare NN and S when I know what the value of N is, so I know how big the vectors need to be.

Printing an array in reverse

Task
You'll be given an array of N integers and you have to print the integers in the reverse order.
Constraints
1<=N<=1000
1<=A_i<=10000, where A_i is the ith integer in the array.
Input
4
1 2 3 4
Output
4 3 2 1
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N, y; //declaring N as the length of array
cin >> N; //intakes the length as an input
if (N>=1 && N<=1000){ //checks whether the length satisfies the rules
int a[N]; // makes an array containing N elements
for (int x =1; x<N; x++){ //starts transcription on the array
cin>>y; //temporarily assigns the input on a variable
if (y>=1&&y<=10000){ //checks if the input meets rules
a[x]=y; //copies the variable on the array
}
}
for (int z = N; z>1; z--){ //runs a loop to print in reverse
cout<<a[z]<<endl;
}
}
return 0;
}
Problem
Obtained output is
-1249504352
3
2
Indicating an error in transcription.
Question
Can somebody please tell me where I am making a mistake? Secondly, is it possible to directly check whether an input is meeting requirement rather than temporarily declaring a variable for it?
Here is a solution in idiomatic c++11, using std::vector, which is a dynamically resizable container useful for applications like this.
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
int size;
std::cin >> size; // take in the length as an input
// check that the input satisfies the requirements,
// use the return code to indicate a problem
if (size < 1 || size > 1000) return 1;
std::vector<int> numbers; // initialise a vector to hold the 'array'
numbers.reserve(size); // reserve space for all the inputs
for (int i = 0; i < size; i++) {
int num;
std::cin >> num; // take in the next number as an input
if (num < 1 || num > 10000) return 1;
numbers.push_back(num);
}
std::reverse(numbers.begin(), numbers.end()); // reverse the vector
// print each number in the vector
for (auto &num : numbers) {
std::cout << num << "\n";
}
return 0;
}
A few things to note:
using namespace std is considered bad practice most of the time. Use (e.g.) std::cin instead for things which come from the std namespace.
numbers.reserve(size) is not necessary for correctness, but will make the program faster by reserving space in advance.
for ( auto &num : numbers ) uses a range-based for loop, available in c++11 and later versions.
You could make your for loop indices go from high to low:
for (int i = N-1; i > 0; --i)
{
std::cout << a[i] << "\n"; // Replace '\n' with space for horizontal printing.
}
std::cout << "\n";
This would apply with std::vector as well.
With std::vector, you can use a reverse iterator. There are other techniques available (as in other answers).

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.