Back to Programming

C

C Language Basics – Input, Output and Operators

Overview of basic structure of a C program, printf/scanf, data types and operators.

1. Structure of a C Program

A typical C program contains preprocessor directives, global declarations, main() function and optional user-defined functions. Understanding the structure is crucial for writing correct and maintainable C programs.

The structure follows a specific order: preprocessor directives (like #include and #define) come first, followed by global variable declarations, function prototypes, the main() function which is the entry point of the program, and finally user-defined function implementations. This organization makes the code readable and helps the compiler process it correctly.

Every C program must have a main() function, which is where program execution begins. The main() function can take command-line arguments and returns an integer value (typically 0 for success, non-zero for errors). Understanding this structure helps in organizing code and understanding how C programs are compiled and executed.

Example Program Structure


#include <stdio.h>  // Preprocessor directive
#define MAX 100      // Macro definition

int global_var = 10; // Global variable

void function_name(); // Function prototype

int main() {         // Main function
    int local_var = 20;
    printf("Hello, World!\n");
    function_name();
    return 0;
}

void function_name() { // Function definition
    // Function body
}

2. Input and Output

Input and output operations are fundamental to any programming language. C provides standard library functions for formatted input and output, which are essential for interactive programs and data processing.

  • printf() – Used for formatted output to the console. It allows you to display text, variables, and formatted data. Format specifiers like %d, %f, %c, %s control how data is displayed. printf() is one of the most commonly used functions in C programming.
  • scanf() – Used for formatted input from the user. It reads data according to format specifiers and stores values in variables. The address operator (&) must be used with variables (except arrays/strings). scanf() is essential for interactive programs that require user input.

I/O Examples


int age;
float salary;
char name[50];

printf("Enter your age: ");
scanf("%d", &age);

printf("Enter salary: ");
scanf("%f", &salary);

printf("Enter name: ");
scanf("%s", name);  // No & for strings

printf("Age: %d, Salary: %.2f, Name: %s\n", age, salary, name);

3. Data Types

Data types define the type of data a variable can hold and determine the operations that can be performed on it. C provides several built-in data types, each with specific characteristics and memory requirements.

Understanding data types is crucial for efficient programming. Choosing the right data type affects memory usage, program performance, and correctness. C also allows type modifiers to customize data types for specific needs.

Basic Data Types

  • int – Stores integers (whole numbers). Size typically 2 or 4 bytes depending on system. Range: -32,768 to 32,767 (for 2 bytes) or larger for 4 bytes.
  • float – Stores single-precision floating-point numbers. Size: 4 bytes. Precision: approximately 6-7 decimal digits. Used for numbers with decimal points.
  • double – Stores double-precision floating-point numbers. Size: 8 bytes. Precision: approximately 15-17 decimal digits. More precise than float, used when higher precision is needed.
  • char – Stores a single character. Size: 1 byte. Range: -128 to 127 (signed) or 0 to 255 (unsigned). Used for characters and small integers.

Type Modifiers

  • short, long – Modify the size of int and double. short int is typically 2 bytes, long int is 4 or 8 bytes depending on system.
  • signed, unsigned – Control whether negative values are allowed. unsigned types can only store non-negative values but have a larger positive range. signed is the default for int and char.

4. Operators

Operators are symbols that perform operations on operands (variables and values). C provides a rich set of operators for various operations. Understanding operator precedence and associativity is crucial for writing correct expressions.

Operators are categorized based on their functionality. Some operators can be used in multiple ways (like + for addition and unary plus), and operator precedence determines the order of evaluation in complex expressions. Using parentheses can clarify and control evaluation order.

Operator Categories

  • Arithmetic operators: + (addition), - (subtraction), * (multiplication), / (division), % (modulus/remainder). These perform mathematical operations. The modulus operator (%) returns the remainder of division and only works with integers.
  • Relational operators: < (less than), > (greater than), <= (less than or equal), >= (greater than or equal), == (equal to), != (not equal). These compare values and return 1 (true) or 0 (false). Essential for conditional statements.
  • Logical operators: && (logical AND), || (logical OR), ! (logical NOT). Used to combine multiple conditions. && returns true only if both conditions are true, || returns true if at least one condition is true, ! negates a condition.
  • Assignment operators: = (simple assignment), +=, -=, *=, /=, %= (compound assignment). Assignment operators store values in variables. Compound operators perform an operation and assignment in one step (e.g., x += 5 is equivalent to x = x + 5).
  • Increment/Decrement operators: ++ (increment), -- (decrement). Can be used as prefix (++x) or postfix (x++). Prefix increments before use, postfix increments after use. Very common in loops.

Operator Precedence

Operators have different precedence levels. From highest to lowest: parentheses, unary operators, multiplicative (*, /, %), additive (+, -), relational (<, >, etc.), equality (==, !=), logical AND (&&), logical OR (||), assignment (=). Use parentheses to clarify and control evaluation order.

5. Practice Recommendations

Students should practice small programs using combinations of operators and formatted I/O. Start with simple programs that use basic I/O and arithmetic operations, then gradually introduce more complex concepts like conditional statements and loops.

Practice programs should include: reading and displaying values, performing calculations, using different operators, understanding operator precedence, and formatting output properly. Regular practice with these fundamentals builds a strong programming foundation.

Frequently Asked Questions

Q1: What is the difference between = and == in C?

= is the assignment operator that assigns a value to a variable. == is the equality comparison operator that checks if two values are equal. Using = in conditions is a common error that assigns instead of comparing, often leading to bugs.

Q2: When should I use float vs double?

Use float when memory is limited and 6-7 decimal precision is sufficient. Use double when you need higher precision (15-17 decimals) or when performing many calculations where precision errors can accumulate. In modern systems, double is often preferred unless memory is a constraint.

Q3: What happens if I use the wrong format specifier in printf/scanf?

Using wrong format specifiers leads to undefined behavior. The program may display incorrect values, crash, or behave unpredictably. Always match format specifiers with variable types: %d for int, %f for float, %lf for double, %c for char, %s for strings.