chtp02

Introduction to C Programming

Objectives

  • Write simple programs in C.

  • Use simple input/output statements.

  • Understand fundamental data types.

  • Learn computer memory concepts.

  • Use arithmetic operators and learn their precedence.

  • Write simple decision-making statements.

Program Structure

Basic Components of a C Program

  • Comments: Labeled with // for single-line or /*...*/ for multi-line; improve code readability without affecting execution.

  • Preprocessor Directive: #include <stdio.h> includes standard input/output functions such as printf.

  • Main Function: int main(void) is where C programs begin execution. It returns an integer value.

Printing Output

  • Printing a Simple Message: Using printf to display text.

    • Example: printf("Welcome to C!\n");

    • \n is an escape sequence for newline.

Basic Input and Output

Variables and Data Types

  • Variable Definition: Every variable must be defined with a type before use. Example: int integer1, integer2;

  • Types: int for integers.

Input Using scanf

  • Example: scanf("%d", &integer1); reads an integer input by the user.

  • Address Operator: & indicates the memory location where the data should be stored.

Arithmetic Operators

  • C uses operators like +, -, *, / for operations. The remainder operator % finds out division remainders, e.g., 7 % 4 results in 3.

  • Integer Division: E.g., 7 / 4 yields 1.

Operator Precedence

  1. Parentheses ()

  2. Multiplication *, Division /, Remainder %

  3. Addition +, Subtraction -

  4. Assignment =

Decision Making in C

  • If Statement: Executes a block of code based on a condition.

    • Syntax: if (condition) { /* statements */ }

    • Example: Checks equality with operators: ==, !=, <, >, <=, >=.

Programming Best Practices

  • Indentation and Comments: Enhance code readability. Every function should have a comment describing its purpose.

  • Variable Naming: Use meaningful names for clarity.

  • Avoid Confusing Operators: Distinguish between the assignment operator = and equality operator ==.