C uses another operator that is not common in other languages: the increment operator. Consider the following program:
included files
void main()
{
int num=0;
clrscr();
printf("Number=%d",num);
printf("\nNumber=%d",num++);
printf("\nNumber=%d",num);
getch();
}
The output of the program will be:
Number=0
Number=0
Number=1
How did the variable num get to be 1? As you can guess by examination of the program, the (++) operator had the effect of incrementing num; that is , adding 1 to it. The first printf() statement printed the original value of num, which was 0, The second printf() also printed the original value of num; then, after num was printed, the (++) operator incremented it. Thus the third printf() statement printed out the incremented value. The effect of num(++) is exactly the same as that of the statement
num=num+1;
However, num(++) is far compact to write.
Since there's an increment operator you can guess there will be a decrement operator as well. Let's modify the above program, using (--), the decrement operator:
included files
void main()
{
int num=0;
clrscr();
printf("Number=%d",num);
printf("\nNumber=%d",num--);
printf("\nNumber=%d",num);
getch();
}
The output will be:
Number=0
Number=0
Number=-1
The effect is just the same as executing the statement
num=num-1;
The (++) and (--) operators can increment and decrement a variable without the need for a separate program statement.
If you have any question, you can ask me freely!
included files
void main()
{
int num=0;
clrscr();
printf("Number=%d",num);
printf("\nNumber=%d",num++);
printf("\nNumber=%d",num);
getch();
}
The output of the program will be:
Number=0
Number=0
Number=1
How did the variable num get to be 1? As you can guess by examination of the program, the (++) operator had the effect of incrementing num; that is , adding 1 to it. The first printf() statement printed the original value of num, which was 0, The second printf() also printed the original value of num; then, after num was printed, the (++) operator incremented it. Thus the third printf() statement printed out the incremented value. The effect of num(++) is exactly the same as that of the statement
num=num+1;
However, num(++) is far compact to write.
Since there's an increment operator you can guess there will be a decrement operator as well. Let's modify the above program, using (--), the decrement operator:
included files
void main()
{
int num=0;
clrscr();
printf("Number=%d",num);
printf("\nNumber=%d",num--);
printf("\nNumber=%d",num);
getch();
}
The output will be:
Number=0
Number=0
Number=-1
The effect is just the same as executing the statement
num=num-1;
The (++) and (--) operators can increment and decrement a variable without the need for a separate program statement.
If you have any question, you can ask me freely!
0 comments:
Post a Comment