Compute alternating series: 1 − 2 + 3 − 4 + ... ± n Dry Run in C

Compute alternating series: 1 − 2 + 3 − 4 + ... ± n is an interactive C dry run visualizer from the For programs section. Study the source code, then use the execution controls to follow each step, variable update, highlighted line, and console output.

This page provides a browser-based dry run with source-code highlighting, auto-scroll, voice narration controls, and execution output for learning the program step by step.

Compute alternating series: 1 − 2 + 3 − 4 + ... ± n Program Code

#include <stdio.h>
int main() {
    int n, sum = 0, i;
    printf("Enter n: ");
    scanf("%d", &n);
    
    for(i = 1; i <= n; i++) {
        if(i % 2 == 0) {
            sum -= i;   // even: subtract
        } else {
            sum += i;   // odd: add
        }
    }
    
    printf("Alternating sum = %d\n", sum);
    
    // Formula: if n even: -n/2, if n odd: (n+1)/2
    if(n % 2 == 0)
        printf("Formula verification: -%d/2 = %d\n", n, -n/2);
    else
        printf("Formula verification: (%d+1)/2 = %d\n", n, (n+1)/2);
    
    return 0;
}

View the complete For programs page.

Program Console Compute alternating series: 1 − 2 + 3 − 4 + ... ± n Topic: C Vignaankosh.com
Execution Panel
Step 0/0
Console is empty.