TECHNOLOGY 

Published on

Study Guide: Factorial Calculation in C

1. C Implementation of Factorial

Code:

// Calculate the factorial of n.
int factorial(int n)
{
  int result = n;

  while(--n > 0)
  {
    result = result * n;
  }

  return result;
}
  

Functionality:

- Takes an integer n as input.

- Calculates the factorial of n.

- Uses a while loop and a local variable result to compute the factorial.

- Returns the calculated factorial value.

Key Aspects:

- Uses a while loop to iterate.

- The --n operator decrements n before its value is compared to 0.

- More readable compared to assembly language.

- Portable and can be compiled for different processor types.

2. Exercise: Running the C Code

Goal: Understand the step-by-step execution of the C factorial function.

Method:

- Trace the code's execution with a specific input value (e.g., n = 4).

- Keep track of variable values (n and result) before and after each step.

Expected Outcome: Verify that the function returns the correct factorial (e.g., 24 for n = 4).

3. Compilation and Disassembly

Process:

- C code is compiled into machine code.

- Machine code can be disassembled into assembly language.

Implication: Compiled programs can be analyzed even without the original source code.

ARM Assembly Output:

Address     Assembly
0001051c    sub     r3, r0, #1
00010520    cmp     r3, #0
00010524    bxle    lr
00010528    mul     r0, r3, r0
0001052c    subs    r3, r3, #1
00010530    bne     00010528
00010534    bx      lr
  

Compiled C code outputs similar logic to the ARM assembly above.

Note: A compiler translates high-level language to machine code.

4. Cross-Platform Compilation

Advantage of High-Level Languages: Code portability.

Concept: The same C code can be compiled for different processors (e.g., ARM, x86) and operating systems (e.g., Linux, Windows), as long as it doesn’t depend on OS-specific features.

x86 Assembly Output (Windows):

Address     Assembly
00406c35    mov     ecx,dword ptr [esp+4]
00406c39    mov     eax,ecx
00406c3b    jmp     00406c40
00406c3d    imul    eax,ecx
00406c40    dec     ecx
00406c41    test    ecx,ecx
00406c43    jg      00406c3d
00406c45    ret
  

5. Key Takeaways

- High-level languages simplify development compared to assembly.

- Compilers handle the translation to machine code.

- High-level languages enable portability across processors and operating systems.

- Compiled code can be disassembled to study its underlying structure.

Picture
0 Comments