Get array input and print the array (C++) - c++

I am writing a code that takes an array of 10 and collects user input. I want to print out the array after the user has finished putting all the values into it. The problem is that when I printout the array it gives me a bunch of garbage values and a weird output. I am not sure why it is doing what it is doing.
This is my code:
#include <iostream>
#include<ctime>
using namespace std;
int main(){
int num;
int arr[10] = {0};
cout<<"Enter 10 numbers: "<< endl;
for(int i = 0; i < 10; i++){
cin>>arr[i];
}
for(int i = 0; i < sizeof(arr); i++){
cout<<arr[i]<< " ";
}
return 0;
}

That is because you are running the loop from 0 till sizeof(arr), here sizeof(arr) means the size of array in bytes. Which happens to be sizeof(int) times the number of elements in the array.
So if we consider sizeof(int) to be 4bytes(i.e. each int takes 4bytes in memory), and number of elements to be 10, then it would be 4*10 = 40. So the for loop would run for 40 times.
Instead do the following:
#include <iostream>
#include<ctime>
using namespace std;
int main(){
int num;
int arr[10];
cout<<"Enter 10 numbers: "<< endl;
for(int i = 0; i < (sizeof(arr)/sizeof(arr[0])); i++){
cin>>arr[i];
}
for(int i = 0; i < (sizeof(arr)/sizeof(arr[0])); i++){
cout<<arr[i]<< " ";
}
return 0;
}
As pointed out by #user4581301, it's better to make the loop stop taking input at (sizeof(arr)/sizeof(arr[0])), as the size can be changed laterwards.
I have corrected it. It will work now.

Why you are getting garbage values is very well explained in the other answers. You can use std::begin and std::end or range-based for-loop here for iterating through the array. C++ is smart enough to deduce the length of the array for you.
int main(){
int arr[10]{0};
/* Take inputs from the console and fill the array here. */
auto start = std::begin(arr);
auto end = std::end(arr);
for(; start!=end; ++start)
std::cout<<*start<<" ";
// Or using range-based for-loop
for(auto val: arr)
std::cout<<val<<" ";
}

sizeof(arr) is the total size in bytes of the array, not the number of elements. That's probably 40 rather than 10, Because the typical compiler targeting desktop PC hardware uses a 32 bit int at this time.
If your compiler's up to date and supports at least the C++17 Standard revision, use std::size to get the number of elements in the array, but a better option (supported back to C++11) is to use range-based for loops and let the compiler figure out the bounds for you. This makes changes to the count of elements in arr self-managing.
Eg:
for(auto & val:arr){
cin>>val;
}
for(auto & val:arr){
cout<<arr[i]<< " ";
}
If range-based for and std::size are not available, define and use a constant value everywhere you use 10 or sizeof(arr).
Eg:
const int ARR_SIZE = 10;
and then the definition of arr becomes
int arr[ARR_SIZE] = {0};
and the control for both for loops become
for(int i = 0; i < ARR_SIZE; i++)
This allows you to vary the size of arr with only one change required to make the code function correctly. This is also less cumbersome than repeating sizeof(arr)/sizeof(arr[0]) everywhere the number of elements in arr is needed.

Related

C++ : Longest Arithmetic Subarray

Given an input array, the output must be the length of the longest arithmetic subarray of the given array.
I am getting a different output other than the desired one. I don't understand where I went wrong, I'm still a beginner so please ignore the rookie mistakes and kindly help me out wherever I'm wrong. Thanks in advance.
Here's the code:
#include <iostream>
using namespace std;
int main () {
int n;
cin>>n;
int array[n];
for (int i=0;i<n;i++)
{
cin>>array[i];
}
int length = 2;
int cd = array[1] - array[0];
for(int i=2; i<n; i++){
if(array[i] - array[i-1] == cd){
length++;
}
else {
cd = array[i] - array[i-1];
length=2;
}
cout<<length<<" ";
}
return 0;
}
If you are looking for a subsequence then what you did would not accomplish that.
For example:
Input: nums = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
You would require a nested loop structure (a for loop within the for loop you currently have) to accomplish that as you want to check a certain cd with the entire array and not just the next element.
If you require to find a subsequence/subarray given that the elements must be adjacent to one another then your program would work correctly.
Also a big error in your code is that you are printing the length inside the for loop. Unsure of whether that was for debugging purposes.
The problem here is you're resetting length after every update. You need a variable to store the maximum of every length.
#include <iostream>
using namespace std;
const int maxn = 1e6;
int arr[maxn];
int main ()
{
int n; cin>>n;
for (int i=0;i<n;i++) { cin >> arr[i]; }
int length = 2;
int maxLength = 2; //max variable
int cd = arr[1] - arr[0];
for(int i=2; i<n; i++){
if(arr[i] - arr[i-1] == cd) {length++;}
else {
cd = arr[i] - arr[i-1];
length=2;
}
//cout<<length<<" "; //remove this
maxLength = max(maxLength, length); //update maxLength
}
cout << maxLength;
}
A few more aesthetic notes:
array is a keyword in C++ used to declare std::array. Although the program may still run, it could create unnecessary confusion.
int array[n] is a VLAs (variable length array). It's not a C++ standard. It may or may not work depends on the compiler.
Why is "using namespace std;" considered bad practice?

comparing one array element with the next element to find what is the biggest element

I'm trying to find a way to iterating while comparing the element with the next element to find what is the biggest element in the array. But, the output i want keep repeating as much as the loop run.
int main(){
int array[4];
for ( int i = 0; i < 4; i++){
cin >> array[i];
}
for (int i:array){
for (int j = 1; j < 4; j++){
if (i < array[j]){
break;
}
if (i > array[j] ){
cout << i;
}
}
}
}
You can use the following program to find the biggest element in the array. Note that there is no need to use two for loops as you did in your code snippet.
#include <iostream>
int main()
{
int array[4] = {1,10, 13, 2};
int arraySize = sizeof(array)/sizeof(int);//note that you can also use std::size() with C++17
int startingValue = array[0];
for(int i = 1; i < arraySize; ++i)//start from 1 instead of 0 since we already have array[0]
{
if(array[i] > startingValue)
{
startingValue = array[i];
}
}
//print out the biggest value
std::cout<<"the biggest element in the array is: "<<startingValue<<std::endl;
return 0;
}
Your program is reapeating output because you have the cout inside the if which is satisfied multiple times(depending upon how big the array is and what elements it contains). For example, if you try your example on the array int array[] = {23,2,13,6,52,9,3,78}; then the output of your program will be 2323231313652525293787878 . So the output is reapeating more than 2 times. You can instead use the version i gave that uses only 1 for loop and prints the correct biggest element only once.
Note that you can also use std::size with C++17 while sizeof(array)/sizeof(int) works with all C++ versions.

Array doesn't print anything on executing code

I was creating a function that takes an integer number, finds the next multiple of 5 after the number and then if the difference between the multiple and the number is less than 3, then it prints out the multiple else the number itself, finally prints out an array of all the numbers.
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
vector<int> gradingStudents(vector<int> grades) {
int size=grades.size();
int c=0;
int d;
vector<int> array;
for(int i=0;i<size;i++){
while(grades[i]>(c*5)){
c++;
}
d=c*5;
if((d-grades[i])<3){
array[i]=d;
}else{
array[i]=grades[i];
}
d=0;
c=0;
}
return array ;
Now I tried running this function, and the compiler gives shows no error in the program in the code, however the code doesn't print anything.
Someone Please help.
First, I have to say that this code is extremely inefficient. Finding the difference between the closest muliplication of 5 and a number can be simply done by:
int difference = (n - (n + 4) / 5 * 5) - n;
Explanation: C++ is rounding down the division, so (n + 4) / 5 is n / 5 rounded up, and hence (n+4)/5*5 is the closest multiplication of 5.
Another thing, you declare an array but never resize it, so its size is 0. You need to resize it either by specifying the size in the constructor or using the std::vector::resize method.
code:
std::vector<int> gradingStudents(std::vector<int> grades) {
std::size_t size = grades.size();
std::vector<int> array(size);
for (int i = 0; i < size; i++) {
int closestMul = (grades[i] + 4) / 5 * 5;
if (closestMul - grades[i] < 3) {
array[i] = closestMul;
}
else {
array[i] = grades[i];
}
}
return array;
}
Proably your code is crashing, which is why it doesn't print anything. And one reason it might be crashing is your vector use is wrong.
It's very common to see beginners write code like this
vector<int> array;
for (int i=0;i<size;i++) {
array[i] = ...;
But your vector has zero size. So array[i] is an error, always.
Two possible solutions
1) Make the vector the correct size to begin with
vector<int> array(size);
for (int i=0;i<size;i++) {
array[i] = ...;
2) Use push_back to add items to the vector, every time you call push_back the vector increases in size by one.
vector<int> array(size);
for (int i=0;i<size;i++) {
array.push_back(...);
And please don't call your vector array, that's just taking the piss.
i feel nothing is wrong with your function but calling of this function is a bit tricky let me give you a quick main to try may be that will help you.
int main() {
vector <int> test ;
test.push_back(1);
test.push_back(2);
gradingStudents(test);
return 0;
}
Try initially the size of the vector is empty i hope you are sending something from the main . Your code is very inefficient whenever you find time must read how to write an efficient code.

C++ program does nothing when executed

I am on Ubuntu 18.04 using the default c++ compiler it comes with. I am trying to get the size of vector required from the keyboard and eventually fill a vector with the increasing value of i in the makeGaps function. I would then like to return a filled vector to my variable x. However, when I run the code below, after it displays the "enter gap size" it does nothing even after I supply an integer. No output, no errors and also in code blocks all the debugger icons go gray. The code also doesn't
terminate and I cannot figure out what is wrong.
#include <iostream>
#include <vector>
using namespace std;
vector<int> makeGaps (int size){
vector<int> vectorOfGaps(size);
for(int i = 0; i <= vectorOfGaps.size();i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
void printV(vector<int> collection){
for (int i = 0; i <= collection.size(); i++){
cout << collection[i]<< '\n';
}
}
int main()
{ //get the number of gaps required
int numberOfGaps;
cout << "Enter gap size";
cin >> numberOfGaps;
vector<int> x = makeGaps(numberOfGaps);
printV(x);
return 0;
}
Also if i run it in the terminal that comes with vs code it crashes my machine.
Vectors in c++ are dynamically sized.
You can create a vector without a size argument in the constructor then push size number of elements like so:
vector<int> makeGaps (int size){
vector<int> vectorOfGaps;
for(int i = 0; i < size;i++){
vectorOfGaps.push_back(i);
}
return vectorOfGaps;
}
Edit: Also, as someone already pointed out in your comments, it appears you had an off by one error in your for loop. If the for loop runs until x <= size, it will iterate size+1 number of times.

finding even numbers in the array issue (C++)

My code is to extract odd number and even number in an 1D array.
#include <iostream>
using namespace std;
int main() {
int a[6] = {1,6,3,8,5,10};
int odd[]={};
int even[]={};
for (int i=0; i < 6; i++) {
cin >> a[i];
}
for (int i=0; i < 6; i++) {
if (a[i] % 2 == 1) {
odd[i] = a[i];
cout << odd[i] << endl;
}
}
cout << " " << endl;
for (int i=0; i < 6; i++) {
if (a[i] % 2 == 0) {
even[i] = a[i];
cout << even[i] << endl;
}
}
return 0;
}
the output is:
1
3
5
2
1
6
It shows that it successfully extract odd numbers but the same method applied to the even number. It comes with an issue while the even number is 4.
Could anyone help me find the cause here? Thanks.
You've got an Undefined Behavior, so result may be any, even random, even formatted hard drive.
int odd[] = {} is the same as int odd[/*count of elements inside {}*/] = {/*nothing*/}, so it's int odd[0];
Result is not defined when you're accessing elements besides the end of array.
You probably have to think about correct odd/even arrays size, or use another auto-sizeable data structure.
First, although not causing a problem, you initialize an array with data and then overwrite it. The code
int a[6] = {1,6,3,8,5,10};
can be replaced with
int a[6];
Also, as stated in the comments,
int odd[]={};
isn't valid. You should either allocate a buffer as big as the main buffer (6 ints) or use a vector (although I personally prefer c-style arrays for small sizes, because they avoid heap allocations and extra complexity). With the full-size buffer technique, you need a value like -1 (assuming you intend to only input positive numbers) to store after the list of values in the arrays to tell your output code to stop reading, or store the sizes somewhere. This is to prevent reading values that haven't been set.
I don't understand your problem when 4 is in the input. Your code looks fine except for your arrays.
You can use std::vector< int > odd; and then call only odd.push_back(elem) whem elem is odd.