Home > Blockchain >  Why the array is not printing without the pointer? Is the following code correct?
Why the array is not printing without the pointer? Is the following code correct?

Time:10-02

I'm new to coding. I'm working on pointers. The following code is correct, means there is no syntax error in it but still the second while loop is not printing anything.

#include<stdio.h>
#include<stdlib.h>
int main(){
   
    int arr[]={10,20,30};
    int *ptr=arr;
    int i=0;
    //Printing Array with Pointer
    while(i<3)
    {
        printf("%d\n",*ptr);
        ptr  ;
        i  ;
    }
    //Printing Array without Pointer
    printf("\n\n");
    while(i<3)
    {
        printf("%d\n",*(arr i));
        i  ;
    }

    return 0;
}

CodePudding user response:

After the first while loop

while(i<3)
{
    printf("%d\n",*ptr);
    ptr  ;
    i  ;
}

the variable i is equal to 3.

So the condition of the second while loop

while(i<3)
{
    printf("%d\n",*(arr i));
    i  ;
}

at once evaluates to false.

The problem of your code is that you selected a wrong loop. The variable i is used only within the loops so it should be declared in the scope of the loops.

Also the variable is redundant if you want to output elements of an array using a pointer.

You could write for example

int arr[]={10,20,30};
const size_t N = sizeof( arr ) / sizeof( *arr ); // or use std::size

//Printing Array with Pointer
for ( const int *ptr = arr; ptr != arr   N;   ptr )
{
    printf("%d\n",*ptr);
}

//Printing Array without Pointer
printf("\n\n");
for ( size_t i = 0; i != N; i   )
{
    printf("%d\n",*(arr i));
}

CodePudding user response:

Write i = 0; just above the while loop. After completing for loop then value i=3 so you have to again i=0 so that while loop start printing

Hope you will get it

  • Related