Back to C Programming
2026-07-126 min read

Example 2: Integer Output (C Programming)

Learn Example 2: Integer Output (C Programming) step by step with clear examples and exercises.

Title: Example 2: Integer Output (C Programming)

Why This Matters

In C programming, understanding how to output integers is fundamental as it allows you to interact with your program and see the results of your computations. This skill is essential for solving real-world problems, debugging code, and acing coding interviews or exams. When you can effectively print integers, you'll have a solid foundation for building more complex programs that manipulate data.

Prerequisites

Before diving into this lesson, make sure you have a good understanding of:

  1. C basics, including variables, operators, and data types (int, char, float, etc.)
  2. Basic input/output functions like scanf() for user input and printf() for outputting results
  3. Understanding the syntax and structure of a simple C program
  4. Familiarity with control structures such as if-else statements and loops (for, while)
  5. Knowledge of array manipulation and pointers (optional but recommended for more complex programs)

Core Concept

In C programming, the printf() function is used to display text or values on the screen. To print an integer, we use the format specifier %d inside the parentheses. Here's a breakdown of how it works:

#include <stdio.h>
int main() {
int num = 42; // Declare and initialize an integer variable
printf("The value of num is %d\n", num); // Output the integer value using printf()
return 0;
}

In this example, we declare an integer variable num and assign it a value of 42. Then, we use the printf() function to print the string "The value of num is" followed by the value of num enclosed in %d. The \n at the end of the format string causes a new line to be printed after the output.

Variable Interpolation

Variable interpolation allows you to include variables directly within the format string, making it more readable and flexible:

#include <stdio.h>
int main() {
int num = 42;
char* message = "The value of num is";
printf("%s %d\n", message, num); // Output the custom message with variable interpolation
return 0;
}

In this example, we create a string message that contains the text to be printed before the integer value. We then use the %s format specifier for strings and concatenate it with the integer value using variable interpolation.

Worked Example

Let's create a simple program that takes an integer from the user, squares it, and outputs the result:

#include <stdio.h>
int main() {
int num, square; // Declare two integer variables
printf("Enter an integer: "); // Prompt the user for input
scanf("%d", &num); // Read the user's input and store it in the variable `num`

square = num * num; // Calculate the square of the entered number and store it in the variable `square`
printf("The square of %d is %d\n", num, square); // Output the original number and its square using printf()

return 0;
}

In this example, we first declare two integer variables: num for the user's input and square to store the result. We then prompt the user for input using printf(), read the input using scanf(), calculate the square of the entered number, and finally output both the original number and its square using printf().

Common Mistakes

  1. Forgetting semicolons: Semicolons are crucial in C programming, as they signal the end of a statement. Forgetting to include them can lead to syntax errors.
  1. Incorrect format specifier: When using printf(), make sure you use the correct format specifier for your data type. In this case, use %d for integers.
  1. Not taking the address of the variable in scanf(): When using scanf(), always take the address of the variable by prefixing it with an ampersand (&) to ensure that the correct memory location is read from or written to.
  1. Incorrect variable declaration: Make sure you declare your variables before using them in your code, and use the appropriate data type for each variable.
  1. Mismatched parentheses: Be careful with parentheses when using multiple format specifiers, as they can affect the order of evaluation.
  1. Not checking for input errors: Always check whether scanf() was successful in reading the expected data before proceeding with further calculations to avoid unexpected behavior or crashes.

Common Scenarios and Solutions

Scenario 1: Infinite loop due to incorrect user input

If a user enters invalid input (e.g., characters instead of numbers), scanf() will not read the expected data, causing an infinite loop. To avoid this, check whether scanf() was successful and handle invalid input accordingly:

int num;
if (scanf("%d", &num) != 1) {
printf("Invalid input! Please enter a valid integer.\n");
return -1; // Exit the program with an error code
}

Practice Questions

  1. Write a program that takes two integers as input and outputs their sum.
  2. Write a program that calculates and outputs the factorial of a given integer (use recursion).
  3. Write a program that checks whether an entered number is even or odd.
  4. Write a program that sorts three integers in ascending order using bubble sort.
  5. Write a program that takes an array of integers as input, finds the maximum and minimum values, and outputs them.
  6. Write a program that calculates the average of a list of numbers entered by the user (up to 10 numbers).
  7. Write a program that generates Fibonacci series up to a given number (n) provided by the user.
  8. Write a program that finds all prime numbers between two given integers (m and n).
  9. Write a program that calculates the greatest common divisor (GCD) of two integers using Euclid's algorithm.
  10. Write a program that checks whether a given number is a prime number, composite number, or a perfect square.

FAQ

  1. Why do I get a segmentation fault when running my code?

A segmentation fault usually occurs due to accessing memory locations that have not been allocated or are out of bounds. Double-check your variable declarations, memory allocation, and array indexing to ensure they're within valid ranges.

  1. Why doesn't my printf() output work as expected?

Make sure you've included the correct header file (#include ) and that your format string contains the appropriate format specifier for your data type (e.g., %d for integers). Also, ensure you're not encountering any syntax errors or logic issues in your code.

  1. Why do I need to take the address of a variable when using scanf()?

Taking the address of a variable with the ampersand (&) is necessary because scanf() needs the memory address of the variable to write the input data into it, rather than just its name.

  1. Why can't I use printf() or scanf() inside a function other than main()?

In C, only the main() function has a return type of int, which is required by the C standard. Other functions should not have a return type of int. If you need to perform input/output operations in other functions, use global variables or pass arguments by reference (using pointers).

  1. Why does my program hang when I try to read more than one line of input using scanf()?

When reading multiple lines of input using scanf(), make sure you handle the newline character left in the buffer after each input. You can do this by adding an extra scanf("%*c") to consume the remaining characters:

char line[100];
scanf("%s", line); // Read a line of input
scanf("%*c"); // Consume the newline character left in the buffer