Beginner · C PROGRAMMING

Reading standard input

Read values supplied by the learner

The standard input box supplies text to the program when you press Run code. Enter 12 8 to supply two integers. The & operator passes the address of each variable so that scanf can store a converted value there.

Validate the conversion

scanf returns the number of successful conversions. This program needs two. A failed conversion produces a message and ends the program. It then restricts both values to a small range before adding them.

Expected output

Sum: 20

Practise

Try 15 and -4, then try the text hello. Predict the result before running. Use the Example input button to return to the starting values.

Common mistake

Do not use a variable after a failed conversion. This introductory scanf example expects text representable as int; extremely long numbers are not a safe input. For robust untrusted input parsing, use fgets with strtol and explicit range checks.

Lesson discussion

Log in to participate.

#include <stdio.h>

int main(void) {
    int first, second;
    if (scanf("%d %d", &first, &second) != 2) {
        puts("Enter two integers.");
        return 1;
    }
    if (first < -1000 || first > 1000 || second < -1000 || second > 1000) {
        puts("Use values from -1000 to 1000.");
        return 1;
    }
    printf("Sum: %d\n", first + second);
    return 0;
}
PRACTICE LAB

Read. Edit. Run.

C source · .c

Experiment with the program below. Your code and input are sent to the selected compiler only when you run it.

Tab indents · Shift+Tab unindents · Esc then Tab leaves the editor · Ctrl/Cmd+Enter runs · Ctrl/Cmd+S saves a draft

Changes save automatically to your account.

Input / output example

Example input
12 8
Expected output for the original program
Sum: 20
Output will appear here.

Log in to save your progress

Ready when you are

Need help with your laptop or computer?

Send us the model and fault details. Start your repair request online or contact TCS Pune directly.

WA