Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add 1 to a given number?
Adding 1 to a given number is a fundamental operation in C programming that increments a variable's value by one. This operation is commonly used in loops, counters, and iterative processes.
Syntax
variable = variable + 1; // Method 1: Addition assignment variable++; // Method 2: Post-increment ++variable; // Method 3: Pre-increment
There are multiple methods to add 1 to a given number in C −
Simple addition and reassignment
Using post-increment operator (++)
Using pre-increment operator (++)
Method 1: Using Addition Assignment
This method explicitly adds 1 to the variable and reassigns the result −
#include <stdio.h>
int main() {
int n = 12;
printf("The initial value of number n is %d<br>", n);
n = n + 1;
printf("The value after adding 1 to the number n is %d<br>", n);
return 0;
}
The initial value of number n is 12 The value after adding 1 to the number n is 13
Method 2: Using Post-Increment Operator
The post-increment operator (++) is a concise way to add 1 to a variable. The value is incremented after the current expression is evaluated −
#include <stdio.h>
int main() {
int n = 12;
printf("The initial value of number n is %d<br>", n);
n++;
printf("The value after adding 1 to the number n is %d<br>", n);
return 0;
}
The initial value of number n is 12 The value after adding 1 to the number n is 13
Method 3: Using Pre-Increment Operator
The pre-increment operator increments the value before the expression is evaluated −
#include <stdio.h>
int main() {
int n = 12;
printf("The initial value of number n is %d<br>", n);
printf("The value after adding 1 to the number n is %d<br>", ++n);
return 0;
}
The initial value of number n is 12 The value after adding 1 to the number n is 13
Key Points
- Performance: Increment operators are generally more efficient than addition assignment
- Readability: The ++ operator clearly indicates increment operation
- Usage: Pre-increment (++n) increments before use, post-increment (n++) increments after use
Conclusion
Adding 1 to a number in C can be accomplished through direct addition or increment operators. The increment operators (++ and ++) are preferred for their conciseness and efficiency in most programming scenarios.
