1

This is literally my first lines of code in C, so it's really basic.

The code is this:

#include<stdio.h>

int main()

{
    int l, b, ar, pr;

    printf("Enter the length of the rectangle");
    scanf("%d", l);
    
    printf("Enter the breadth of the rectangle");
    scanf("%d", b);

    ar = l * b;
    pr = 2 * (l + b);

    printf("\n Area of Rectangle is: %d", ar);
    printf("\n Perimeter of Rectangle is: %d", pr);

}

It starts running properly, outputs "Enter the length of the rectangle", but when I input a number, it just stops and I don't get to input the second value.

What am I missing?

1
  • 2
    You need to pass a pointer to a variable to the scanf so it can fill it with the input: scanf("%d", l);, scanf("%d", &b);. OT: Don't use l as a variable name as it can be confused with I or 1 Commented May 20, 2021 at 13:27

2 Answers 2

2

You have to pass pointers to the variables to get the values instead of the values in the variables.

You should use unary & operators to get pointers like this:

scanf("%d", &l);

Note that you don't need & to read strings because arrays are automatically converted to pointers to the first element (except for some cases, including when used as an operand of unary & operator).

char str[10];
scanf("%9s", str);
Sign up to request clarification or add additional context in comments.

Comments

0

Corrected code

#include<stdio.h>

int main()

{
    int l, b, ar, pr;

    printf("Enter the length of the rectangle");
    scanf("%d", &l);
    
    printf("Enter the breadth of the rectangle");
    scanf("%d", &b);

    ar = l * b;
    pr = 2 * (l + b);

    printf("\n Area of Rectangle is: %d", ar);
    printf("\n Perimeter of Rectangle is: %d", pr);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.