Exulansis
Exulansis

Reputation: 23

'for' loop terminating before termination condition is met

Edit: Solved

This is a program to rotate an array of size 'n' by 'd' towards the left. For example: 1 2 3 4 5 6 7 for d=3 goes to 4 5 6 7 1 2 3. My problem is regarding the final loop in int main() that is being used to print the array. That loop is not printing the array upto all it's 'n' members.

I've tried printing the array for a specific 'n' for example n=7. It works in that case. Hence, I don't think there is any logical error in the rotleft() function.

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int arr[],int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d,arr[n];

    cin>>n>>d;
    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

When I replaced 'n' by 7 in the final loop I got the accurate result, but for general 'n', it shows 4 5 6 instead of 4 5 6 7 1 2 3 (refer to above example).

Upvotes: 1

Views: 213

Answers (3)

Rushikesh
Rushikesh

Reputation: 173

C++ does not support array of dynamic size yet. The size of array needs to be known at compile time. So as suggested already, use vector instead of array if your size is dynamic.

You may achieve the same result by using already existing library function: std::rotate(). However, if you are trying to learn to implement rotate yourself then, its fine.

Upvotes: 0

Ludo
Ludo

Reputation: 512

For dynamically allocated arrays you should use pointers and memory allocation on the heap. Otherwise the variables get assigned random values from memory.

http://www.cplusplus.com/doc/tutorial/dynamic/

#include <bits/stdc++.h>
#include <iostream>
using namespace std;

void rotleft(int* arr,int d,int n)
{
    int temp[d];
    for(int i=0;i<d;i++)
    {
        temp[i]=arr[i];
    }
    for(int i=0;i<n-d;i++)
    {
        arr[i]=arr[i+d];
    }
    for(int i=n-d;i<n;i++)
    {
        arr[i]=temp[i-n+d];
    }

}

int main()
{
    int n,d;

    cin>>n>>d;
    int* arr = new int[n];

    for(int i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    rotleft(arr,d,n);
    for(int i=0;i<n;i++)
    {
        cout<<arr[i]<<" ";
    }

    delete [] arr;
    return 0;
}

Upvotes: -3

VLL
VLL

Reputation: 10165

You are creating the array before n is initialized, so there might not be space for all members.

// n is used here
int n,d,arr[n];
// Initialized here
cin>>n>>d;

Instead of array, you could use for example std::vector. With it you don't have to know the size when declaring the variable.

Upvotes: 4

Related Questions