This code has a bug! (Bugs on lines 4 and 21 according to online compiler C++ shell.)
Purpose of this program: I am trying to cin inside an array and pass in that array to another function to do some multiplication and then print out the values . Please take a look at this code.
Kourosh23, the problem with your code is that a unknown sized array (in your code, n[]) can't be passed as a parameter of a method. Try to pass a size-known array or a pointer to the 0th element instead.
You can consult to "The C++ Programming Language" Ch7.4 for a better explanation.
#include <iostream>
usingnamespace std;
void tripler (int n[], size){
for (int i = 0; i < size; i++){
n[i] = n[i] * i;
cout << n[i];
}
}
int main (){
int a[3];
int size = 0; // Note: size needs to be defined outside the loop because it needs to be used outside the loop
for (int i = 0; i < 3; i++){
cin >> a[i];
int size = 0;size += i; // Note: += i is wrong
++size;
tripler (a[], size);
}
tripler (a, size); // Note: outside the loop/[] are wrong here
return 0;
}
#include <iostream>
usingnamespace std;
void tripler (int a[], int size){
cout << "Tripled elements: ";
/* This for loop will loop through all the elements of the array and times them by
three which will print out array elements with 3 times the original value. */
for (int i = 0; i < size; i ++){
a[i] *= 3;
cout << a[i] << " ";
}
}
int main (){
int size = 6;
int a[size];
cout << "Enter "<< size << " elements: ";
for (int i = 0; i < size; i++){
cin >> a[i];
}
tripler (a, size);
return 0;
}
EXTRA INFORMATION: PROGRAM WILL CRASH
This code contains const int a[] as a parameter which checks if the array a[] changes throughout the program or no, and since we are doing a[i] *= 3; or a[i] = a[i] * 3; Then we are changing the original value of the array, thus the program crashes. It is all because of the addition of const to the parameter array.
#include <iostream>
usingnamespace std;
void tripler (constint a[], int size){
cout << "Tripled elements: ";
for (int i = 0; i < size; i ++){
a[i] *= 3; // Will show as bug! We are changing array.
cout << a[i] << " ";
}
}
int main (){
int size = 6;
int a[size];
cout << "Enter "<< size << " elements: ";
for (int i = 0; i < size; i++){
cin >> a[i];
}
tripler (a, size);
return 0;
}
Just a note:
You should use code comments to explain what you expect to happen. For example, there should be a comment block above tripler() that helps to explain:
1) What you expect the result of tripler() to be.
2) What the calling function should pass to tripler()
Getting into this habit now will help you write code that is easier to debug and maintain.