Index size of an array - c++

If I have an array like a[100] and I start from 1 or 0. When I declare int a[100], how long is my array?
It always starts counting from 0? If yes it will be an array with 101 spaces.
#include <iostream>
using namespace std;
int main()
{
float time[20]; //
int a, first = 20, y, x;
for (x = 1; x < 21; x++) {
cout << "Enter the time of the person number " << x << " : ";
cin >> time[x];
}
for (y = 1; y < 20; y++) {
if (time[y] < first) {
first = time[y];
a = y;
}
}
getchar();
cout << "The person " << a << " was the faster.";
cout << time[1];
getchar();
return 0;
}
Here it starts from 1.
And if I change it will start from 0.
for (x=0;x<21;x++)
for (y=0;y<20;y++)
And why is much better to start from 0?

C++ uses 0-indexing, so, for int a[20]; valid indexes are 0, .., 19.
a[20] does out of bound access, leading to UB.

"When I declare int a[100] , how long is my array"
It is 100 elements in size.
The valid indices are a[0] through a[99] (both inclusive). Index a[100] is past the end of the array (out of bounds).

In c++ arrays always start from 0 index and the number you passed in the brackets is the size of array.
If you write, int A[10] ... It means you can store 10 element in the array, but the indexing begins from 0 and goes up to 9.

Related

what does int numbers[n+2]; statement do?

#include<iostream>
int fastFibonacci(int n)
{
int numbers[n+2]; // int numbers[n].
numbers[0] = 0;
numbers[1] = 1;
for (int i = 2; i <= n; i++)
{
numbers[i] = numbers[i - 1] + numbers[i - 2];
}
return numbers[n];
}
int main() {
int n;
std::cout << "Enter a Number";
std::cin >> n;
int result = fastFibonacci(n);
std::cout << result << "\n";
return 0;
}
in this code when i enter input 0 or 1 get correct answer. But the problem is that when i replace int numbers[n+2]; with the commented part it start giving me wrong answer when input is 0 or 1. why? anyone please explain me.
In this function
int fastFibonacci(int n)
{
int numbers[n+2]; // int numbers[n].
numbers[0] = 0;
numbers[1] = 1;
for (int i = 2; i <= n; i++)
{
numbers[i] = numbers[i - 1] + numbers[i - 2];
}
return numbers[n];
}
there is used a variable length array with n + 2 elements declared in this line
int numbers[n+2]; // int numbers[n].
Variable length arrays is not a standard C++ feature. It can be implemented as own language extension of a C++ compiler.
Using the variable length array makes the function very unsafe because there can occur a stack overflow.
As within the function there is explicitly used two elements of the array
numbers[0] = 0;
numbers[1] = 1;
then the array shall have at least two elements even when the parameter has a value less than 2.
To calculate the n-th Fibonacci number there is no need to declare an array of such a size.
Apart from this the function argument shall have an unsigned integer type. Otherwise the function can invoke undefined behavior if the user passes a negative number.
Also for big values of n there can be an integer overflow for the type int.
The function can be implemented in various ways.
Here is one of possible its implementations.
#include <iostream>
#include <functional>
unsigned long long fibonacci( unsigned int n )
{
unsigned long long a[] = { 0, 1 };
while ( n-- )
{
a[1] += std::exchange( a[0], a[1] );
}
return a[0];
}
int main()
{
const unsigned int N = 10;
for ( unsigned int i = 0; i < N; i++ )
{
std::cout << i << ": " << fibonacci( i ) << '\n';
}
return 0;
}
The program output is
0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
int numbers[n+2]; is the declaration of an array of ints with space for n + 2 ints, this is a variable lenght array and is not part of C++ standard, though some compilers allow it it's not somenthing you should use.
If you need a variable lenght array use std::vector.
With int numbers[n+2]; if n is equal to 0 you still have space for 2 ints, if you have int numbers[n]; the array will have space for 0 ints, so the code will fail because you are trying to access memory that does not exist with numbers[0] and numbers[1].
There are several good ways to implement the Fibonacci sequence, in the site you can find many questions regarding this matter in several programming languages, here is one of them Fibonacci series in C++
Edit
So I've seen your comments about using a vector, for making the sequence you wouldn't need the vector just two variables to store the two numbers to add, to store the sequence in a vactor, you can do somenthing like:
#include <iostream>
#include <vector>
#include <iomanip>
//passing the vector by reference
void fastFibonacci(unsigned long long n, std::vector<unsigned long long>& sequence) {
unsigned long long first = 0;
unsigned long long second = 1;
sequence.push_back(first); //add first values to the vector
sequence.push_back(second); //add first values to the vector
for (unsigned long long i = 0, value = 0; i < n && value <= LLONG_MAX ; ++i) {
value = first + second;
first = second;
second = value;
sequence.push_back(value); //adding values to the vector
}
}
int main() {
unsigned long long limit; //number of values in the sequence
int num = 1;
std::vector<unsigned long long> sequence; //container for the sequence
std::cout << "Enter upper limit: ";
std::cin >> limit;
fastFibonacci(limit, sequence);
//print the sequence in a range based loop formatted with <iomanip> library
for(auto& i : sequence){
std::cout << std::setw(4) << std::left << num++ << " " << i << std::endl;
}
return 0;
}
If you want to print just one of the numbers in the sequence, just use, for instance:
std::cout << sequence[10];
Instead of the whole vector.
The code you post in the comment to the other answer won't work because the access to the vector is out of bounds in numbers[i] = numbers[i - 1] + numbers[i - 2];, if for instance i = 5, your vector only has 2 nodes but you are accessing the 6th node numbers[5].

Why isn't the value of a variable that is serving as "count " not resetting to zero when the loops reiterates?

This is the code that I have written and I am giving you sample inputs and outputs to this just to clear my question even more
Sample input
2 (value of t, which are test cases)
3 (number of inputs )
2 4 2
3
0
2
3
I am getting output as
1
1
I should be getting output as
1
0
#include<iostream>
#include<vector>
#define ll long long
using namespace std;
int main()
{
int t;
cin >> t;
while (t--)
{
vector<ll int> x;
ll int n;
cin >> n;
ll int i, ent;
for (i = 0; i < n; i++)
{
cin >> ent;
x.push_back(ent);
}
vector<ll int>::iterator y,z;
for(y=(x.begin());y!=(x.end()-1);y++)
for (z = (x.begin() + 1); z != (x.end()); z++)
{
int count=0;
if (*y + *z == *y * (*z))
count++;
}
cout << count<<endl;
}
return 0;
}
Updated code: But still having the same problem
#include<iostream>
#include<vector>
#define ll long long
int main()
{
int t;
std ::cin >> t;
while (t--)
{
std :: vector<ll int> x;
ll int n;
std :: cin >> n;
ll int i, ent;
for (i = 0; i < n; i++)
{
std :: cin >> ent;
x.push_back(ent);
}
std::vector<ll int>::iterator y,z;
int count = 0;
for(y=(x.begin());y!=(x.end()-1);y++)
for (z = (x.begin()+1); z != (x.end()); z++)
{
if (*y + *z == *y * (*z))
count++;
}
std ::cout << count<< std ::endl;
}
return 0;
}
Your first problem is that you're accessing the variable count outside its scope. It is declared in the scope of the inner for() loop, and you're trying to print it outside of it. Move its declaration above the for() loops
Now, to answer your question. In the second iteration of the while() loop (vector 0, 2, 3),
in one of the for() loops' iterations, *x and *z will be equal to 2. What you should have done to avoid it is to initialize z as z = y + 1
Your code as written should produce that output (if it even complies...) g++ won't compile it because you reference count after the loop it was created in. count is scoped to that loop so it doesn't exist outside. Anyway I assume you're using some compiler switches or a compiler that allows that.
You effectively make one list of numbers and loop through it checking the mathematical relation you coded (ie when two numbers added together is the same as them multiplied together.) Your first loop goes from the first value to the second last value (because you check for equality against end() - 1) I'm not sure if that's what you really wanted or not. Your second loop starts at the second value and then goes till the last value. So in your second test case your second number is 2 and 2 will be used for the parameter *y and then it is the first value in the second loop so you're doing the check with 2 and 2 and 2+2 == 4 == 2*2 so the check passes and count is incremented. Try the code below to get some insight into what you're doing (note that I removed the declaration of count from inside the loop and moved it just above the declaration of y and z which was required for me to compile it with my system):
{
cout << "y:" << *y <<" z:" << *z << endl;
if (*y + *z == *y * (*z)){
cout << "match " << *y << " " << *z << endl;
count++;
}
}
Name conflict between std::count and your local count. Remove using namespace std; and you will have more meaningful error message: as unknown identifier count, as count should be declared outside of the loop:
int count=0;
for(y=(x.begin());y!=(x.end()-1);y++)
for (z = (x.begin() + 1); z != (x.end()); z++)
{
if (*y + *z == *y * (*z))
count++;
}
std::cout << count << std::endl;
Note: std::cout << function_name outputs 1 with implicit bool conversion.
Note: logic of the code itself might still have issues

Select every 3 consecutive elements from an array and comparing them using a function

#include <iostream>
using namespace std;
// function to compare the three values
int maximum(int x, int y, int z)
{
int max;
if (x > y) {
max = x;
if (z > max)
max = z;
} else {
max = y;
if (z > max)
max = z;
}
return max;
}
// main code
int main() {
int i, a, b;
cout << "La dimension de la table?" << endl;
// Ask user to select the size of the array, maximum 20. "a" is the size
cin >> a;
while (a > 20) {
cout << "La dimension maximum est 20! Reessayez!" << endl;
cin >> a;
}
int v1[a];
// ask user to fill the array
cout << "Remplisez la table" << endl;
for (i = 0; i < a; i = i + 1) {
cin >> v1[i];
}
// using this variable to know when the loop should stop
b = 0;
// selecting the 3 consecutive elements to compare
while (b <= a) {
for (i = b; i < 4; i = i + 1) {
// this is were it should compare the 3 selected values and print them
cout << "Le maximum est " << maximum(v1[i], v1[i], v1[i]) << endl;
}
// passing to the next 3 values
b = b + 3;
}
}
This is my complete code. Everything works just fine except the last part where I have to select the values somehow and send them to the function to be compared. Any sugestions?
Thanks alot!
Alex,
Your logic is correct for the most part. Having said that, I have some comments as follows:
You are creating a dynamic array as if it is a fixed size array:
int v1[a];
This array should be defined as follows:
int* v1 = int[a];
since the size is not known during the compile time. Therefore you need to allocate memory in the heap in runtime. Another option is using std::vector as Chris suggested.
AND
You are sending the same value to the function in all three arguments in your function call:
maximum(v1[i], v1[i], v1[i]);
which is a minor typo but would give erroneous results.
AND
You do not need nested loops for picking every three elements and sending them to the function.
Try:
b=0;
while(b <= (a-3))
{
maximum(v1[b], v1[b+1], v1[b+2]);
b+=3;
}
Here b needs to iterate until a-3 since the last three elements will start from that point.
Lastly, you can shorten your function as follows:
int maximum(int x, int y, int z) {
int max=x;
if(y>max) max=y;
if(z>max) max=z;
return max;
}
Hope that helps!
From what I understand you are trying to compare every element in the array in groups of 3. To accomplish that use
for (int i=0; i+2<a; i+=3)
cout << "Le maximum est " << maximum(v1[i], v1[i+1], v1[i+2]) << endl;

Save sub Integer in Array in c++

I want to save an integer type value in array.
Here is a code.
int a,arr[5];
cout<<"Enter a Number ";
cin >> a;
Suppose user enter the value 73972 This value save in arr like this.
arr[0] = 7;
arr[1] = 3;
.. .. .. ..
.. .. .. ..
arr[4] = 2;
How can I do that.???
Iterate reversely on the array and each time divide the number by 10 and store the reminder on the array.
for(int i=4; i>=0; i--)
{
arr[i] = a % 10;
a /= 10;
}
Read a string and break it into digits.
First of all integer values can have more than 5 digits.
You can get the number of digits that an object of type int can contain by using expression
std::numeric limits<int>::digits10 + 1
class std::numeric_limits is declared in header <limits>
Also take into account that if a number contains less digits than the size of the array then you need some mark that will determine the end of the number in the array.
I would advice you to use a character array instead of an array of integers in which the terminating zero will determine the end of the number.
If you want to use an integer array then the code could look the following way
#include <iostream>
#include <algorithm>
#include <limits>
int main()
{
int arr[std::numeric_limits<int>::digits10 + 1];
int a;
std::cout << "Enter a Number ";
std::cin >> a;
int n = 0;
do
{
arr[n++] = a % 10;
} while ( a /= 10 );
std::reverse( arr, arr + n );
for ( int i = 0; i < n; i++ ) std::cout << arr[i] << ' ';
std::cout << std::endl;
}

Nearest value in an array

I am supposed write a function that is passed two parameters: a one-dimensional array of int values, and an integer value. The function finds the value in the array that is closest in value to the second parameter. My code works but not when I enter numbers 1-5 my output is 0. When I enter numbers above 5 then I start getting accurate results. I am not too sure why this is happening but here is my code so far:
#include <iostream>
#include <cmath>
using namespace std;
const int MAX = 5;
int searchNearest(int anArray[],int key)
{
int value = abs(key - anArray[0]);
int num = 0;
for(int x = 0;x < MAX; x++)
{
if(value > abs(key - anArray[x]))
{
value = abs(key - anArray[x]);
num = anArray[x];
}
}
return num;
}
int main()
{
int A[MAX] = {3,7,12,8,10};
int search;
int nearest;
cout << "Enter a number to search: ";
cin >> search;
nearest = searchNearest(A,search);
cout << "The nearest number is: " << nearest << endl;
system("pause");
return 0;
}
In your original code, numbers 1-5 are closest to the first element of the array. Because of this, the code in the if statement is never executed, and when you return num, you return its initial value, which happens to be 0. To fix this, just initialize num differently:
int num = anArray[0]; // <-- used to be 0