Computer >> Computer tutorials >  >> Programming >> C programming

Add 1 to a given number?


A program to add 1 to a given number increments the value of the variable by 1 . This is general used in counters.

There are 2 methods to increase that can be used to increase a given number by 1 −

  • Simple adding of one to the number and reassigning it to the variable.

  • Using increment operator in the program.

Method 1 − using reassignment method

This method takes the variable, add 1 to it and then reassigns its value.

Example Code

#include <stdio.h>
int main(void) {
   int n = 12;
   printf("The initial value of number n is %d \n", n);
   n = n+ 1;
   printf("The value after adding 1 to the number n is %d", n);
   return 0;
}

Output

The initial value of number n is 12
The value after adding 1 to the number n is 13

Method 2 − Using the increment operator

This method uses the increment operator to add 1 to the given number. This is a shorthand trick to add 1 to a number.

Example Code

#include <stdio.h>
int main(void) {
   int n = 12;
   printf("The initial value of number n is %d \n", n);
   n++;
   printf("The value after adding 1 to the number n is %d", n);
   return 0;
}

Output

The initial value of number n is 12
The value after adding 1 to the number n is 13