Home > Back-end >  Can anyone explain, Im learning Pointers in C, Here While running the code, why it asking 2 inputs w
Can anyone explain, Im learning Pointers in C, Here While running the code, why it asking 2 inputs w

Time:08-21

#include<stdio.h>
void square(int *n);
int main(){
  int number;printf("Enter number : ");
  scanf("%d\n", &number);

  square(&number);
  return 0;
  }
void square(int *n){
*n=(*n)*(*n);
printf("Square : %d\n", *n);
}

This is my code, Here while running, it taking two inputs to run. I don't why. Can anyone explain this.

CodePudding user response:

Please try removing the \n from your scanf.

scanf will try to consume each of the specifiers you are giving it. You are telling it to expect a 'newline', so it will consume the first newline you supply by hitting 'enter'. Essentially you are telling your program to expect the user to hit Enter twice.

#include <stdio.h>
void square(int *n);
int main(){
  int number;printf("Enter number : ");
  scanf("%d", &number);

  square(&number);
  return 0;
}
void square(int *n){
    *n=(*n)*(*n);
    printf("Square : %d\n", *n);
}
  •  Tags:  
  • c
  • Related