Basic Structure of a C Program

Basic structure of a C program

A C program is made of declarations, functions and statements. For a small program, the most important pieces are the header include, the main() function, executable statements and the return value.

Minimal C Program Top ↑

#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    return 0;
}

Output

Hello, World!

What Each Part Does Top ↑

#include <stdio.h> supplies declarations for standard input/output functions such as printf() and scanf(). The main() function is the program entry point. The final return 0; indicates successful completion.

Comments in a C Program Top ↑

// A single-line comment

/* A block comment
   can continue on another line. */

Comments are ignored by the compiler as program instructions. See the C comments tutorial for more examples.

Read a Name and Display It Top ↑

The full page structure is already shown above, so this example focuses on the changed declarations and input/output statements.

char name[30];

printf("Enter your name: ");
scanf("%29s", name);
printf("Welcome %s\n", name);

Key change: %29s limits the number of characters written into the 30-character array. scanf("%s", ...) reads a word and stops at whitespace.

Sum of Two Integers Top ↑

int a = 4;
int b = 5;
int sum = a + b;

printf("Sum = %d\n", sum);

Output

Sum = 9

Sum and Average of Three Numbers Top ↑

int a = 3;
int b = 5;
int c = 6;
int sum = a + b + c;
double average = sum / 3.0;

printf("Sum = %d\n", sum);
printf("Average = %.2f\n", average);

Output

Sum = 14
Average = 4.67

Key change: dividing by 3.0 performs floating-point division.

Command-Line Arguments Top ↑

#include <stdio.h>

int main(int argc, char *argv[]) {
    if (argc > 1) {
        printf("Argument received: %s\n", argv[1]);
    } else {
        printf("No argument received.\n");
    }
    return 0;
}

Preprocessor Constant Top ↑

#include <stdio.h>
#define PI 3.14

int main(void) {
    printf("The value of PI: %.2f\n", PI);
    return 0;
}

Preserved Example: Sum and Average from User Input Top ↑

The original page also had a second sum-and-average program where all three values are entered by the user. That variation is preserved here separately.

#include <stdio.h>

int main(void) {
    int a, b, c;

    printf("Enter three integers: ");
    if (scanf("%d %d %d", &a, &b, &c) != 3) {
        printf("Invalid input.\n");
        return 1;
    }

    int sum = a + b + c;
    double average = sum / 3.0;

    printf("Sum = %d\n", sum);
    printf("Average = %.2f\n", average);
    return 0;
}




plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer