Values in C do not return what is expected

Asked

Viewed 98 times

0

I am in personal studies following a booklet that this algorithm gives the following result:

Algorithm of the Apostille

#include <stdio.h>
#include <conio.h>

main() {

   int n = 10;
   int m = ++n;
    printf("\n N=%d M=%d",n,m);

   int a = 10;
   int x = a++;
    printf("\n A=%d, X=%d",a,x);

}

The result comes out this value:

N = 11 M= 11 
A=11 X=10

The amount they put in the booklet was:

N=10 M=11
A=10 X=10

What’s wrong with it? I didn’t get the result they put in the workbook... My algorithm is identical to the workbook.

  • Apostille link: https://www.apostilando.com/apostila/3353/apostila-structuraL-data apostille.

  • I believe the workbook is wrong, the prefix first increases the n then sends to m, the post-fixed sends the value of a to x first, then increases the

  • Got it. Thanks @Four

2 answers

1


This occurs because of these two lines int m = ++n; and int x = a++; that besides m and x are receiving the value n and a, the value of n and a are being added to 1 more. Then the value of n and a which were 10 goes to 11. But there is another factor there, the preincrement and post-increment.

In the preincrement the ++ comes before the variable int m = ++n; this way when executing the value of n will be added to 1 going to 11 and right after the variable m receives the amount n going to 11.

In the post-increment the ++ comes after the variable int x = a++; this way when executing the variable x received the value of a going to 10 and after the value of a will be added to 1 going to 11.

0

If the code is like this in the workbook with this result the workbook put the wrong result, if you modify a little as I put it we have this result that does not match the workbook.

outworking:

N=10 M=11

A=11, X=10

code:

include stdio.h
include conio.h

main() {
    int m = 10;
    int n = m++;

    printf("\n N=%d M=%d",n,m);

    int a = 10;
    int x = a++;

    printf("\n A=%d, X=%d",a,x);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.