CACS151 C Programming

C ProgrammingUnit 211 min read

C Data Types & Syntax: Variables, Constants, Input/Output

Unit 2 of C Programming covers fundamental building blocks: how to declare variables, constants, and literals; the five core data types (int, float, char, etc.) and their storage sizes; input/output operations via scanf()/printf(); and type conversion rules with practical examples like calculating student grades or pro

TAKEAWAYS:

  • Variables store data temporarily (e.g., int age = 20;), while constants (#define PI 3.14) remain fixed.
  • C’s five primitive types (int, float, char, double, void) differ in size (e.g., int = 4 bytes) and use cases (e.g., char for single characters).
  • Input/Output uses scanf() (read) and printf() (display) with format specifiers like %d (integer) or %f (float).
  • Type casting forces conversions (e.g., (float)total/5 avoids integer division).
  • Literals (e.g., 5, 'A', 3.14) are fixed values assigned directly to variables.
  • Memory allocation varies by type: int uses 4 bytes, float 4 bytes, double 8 bytes.

1. Variables and Constants

1.1 Variables: Temporary Data Storage

Variables are named memory locations that store data temporarily during program execution. They must be declared before use with a data type and an optional initial value.

int marks;          // Declaration (uninitialized)
float temperature;  // Declaration (uninitialized)
char grade = 'A';   // Declaration + initialization

Key Rules:

  • Variable names must start with a letter or underscore (_), followed by letters, digits, or underscores.
  • No spaces or special characters (e.g., student_age ✅, student-age ❌).
  • Case-sensitive (Age ≠ age).

Visual: Variable Declaration in Memory


(Shows how x occupies 4 bytes at address 0x7ffd with value 5, and y occupies 4 bytes at 0x7ffe with value 3.140000.)

1.2 Constants: Fixed Values

Constants are immutable values defined using:

  • #define (preprocessor directive):
    #define MAX_STUDENTS 100
    
  • const keyword:
    const float GRAVITY = 9.8;
    

Why Use Constants?

  • Avoid "magic numbers" (e.g., if (marks > 50) → if (marks > PASS_MARK)).
  • Prevent accidental modification.

2. Data Types in C

C supports five primitive data types, each with a specific size and use case. The sizes may vary slightly across systems (e.g., 32-bit vs. 64-bit), but the following is standard for most compilers:

Data Type Size (bytes) Range Example Use Case
int 4 to int age = 20; Whole numbers (e.g., age, count).
float 4 ~ decimal places float height = 5.6f; Single-precision decimals.
double 8 ~ decimal places double pi = 3.14159; High-precision decimals (e.g., PI).
char 1 to (ASCII) char grade = 'A'; Single characters or small integers.
void 0 N/A void func(); Functions with no return type.

Note:

  • float literals must end with f (e.g., 5.6f), while double uses no suffix.
  • char can store ASCII values (e.g., 'A' = 65, '0' = 48).

Visual: Data Type Sizes

classDiagram
    class int {
        +Size: 4 bytes
        +Range: -2147483648 to 2147483647
    }
    class float {
        +Size: 4 bytes
        +Precision: ~6 decimal places
    }
    class double {
        +Size: 8 bytes
        +Precision: ~15 decimal places
    }
    class char {
        +Size: 1 byte
        +Range: -128 to 127 (ASCII)
    }
    int --> "Stores whole numbers"
    float --> "Stores single-precision decimals"
    double --> "Stores double-precision decimals"
    char --> "Stores single characters"

3. Input and Output in C

3.1 printf(): Displaying Output

printf() prints formatted output to the console. Format specifiers control how data is displayed:

  • %d: Integer (int)
  • %f: Float (float/double)
  • %c: Character (char)
  • %s: String (character array)
  • %.2f: Float with 2 decimal places.

Example:

#include <stdio.h>
int main() {
    int marks = 85;
    float cgpa = 3.7;
    printf("Marks: %d, CGPA: %.2f\n", marks, cgpa);
    return 0;
}

Output:

Marks: 85, CGPA: 3.70

3.2 scanf(): Reading Input

scanf() reads input from the user. The format specifiers match printf():

int age;
float salary;
printf("Enter age and salary: ");
scanf("%d %f", &age, &salary);

Key Points:

  • Use & (address-of operator) before variable names.
  • Spaces in scanf() skip whitespace (e.g., "%d %f" reads 50 1200.5).

Visual: scanf() vs. printf()

flowchart TD
    A["User Input"] -->|"Enter age: 25"| B["scanf('%d', &age)"]
    B --> C["age = 25 (stored in memory)"]
    C --> D["printf('Age: %d', age)"]
    D -->|"Age: 25"| E["Console Output"]

4. Type Conversion

4.1 Implicit Conversion

C automatically converts smaller types to larger ones to avoid data loss:

int a = 5;
float b = a;  // Implicit: int → float (5 → 5.0)

Implicit Rules:

  • char → int → float → double.

4.2 Explicit Conversion (Type Casting)

Force conversion using (type):

float total = 10.5;
int students = 3;
float average = (float)total / students;  // 3.5 (not 3)

Why Cast? Avoids integer division (e.g., 10/3 = 3 instead of 3.33).

Visual: Type Casting in Action

flowchart LR
    A["total = 10.5 (float)"] -->|"/ 3"| B["10.5 / 3 = 3.5"]
    C["int total = 10"] -->|"/ 3"| D["10 / 3 = 3 (integer division)"]
    E[(float)total / 3] --> B

5. Literals in C

Literals are fixed values assigned directly to variables or constants:

  • Integer literals: 5, -10 (default int).
  • Floating-point literals: 3.14, -0.5f (use f for float).
  • Character literals: 'A', '$' (stored as ASCII).
  • String literals: "Hello" (stored as char[]).
  • Boolean literals: true/false (C uses 1/0).

Example:

int x = 100;          // Integer literal
float y = 3.14f;      // Float literal
char z = 'C';         // Character literal
printf("%d, %f, %c", x, y, z);

6. Real-World Applications

Example 1: eSewa Transaction Fees

eSewa calculates transaction fees based on data types:

  • int: Stores the amount (e.g., int amount = 500;).
  • float: Stores the fee (e.g., float fee = amount * 0.01;).
  • char: Stores the transaction type (e.g., 'E' for electricity).

Code Snippet:

#include <stdio.h>
int main() {
    int amount;
    char type;
    printf("Enter amount and type (E/M): ");
    scanf("%d %c", &amount, &type);
    float fee = (type == 'E') ? amount * 0.01 : amount * 0.02;
    printf("Fee: %.2f", fee);
    return 0;
}

Input/Output:

Enter amount and type (E/M): 500 E
Fee: 5.00

Example 2: Daraz Order Queue

Daraz uses int to track order IDs and float for prices:

int orderId = 1001;
float price = 1299.99;
printf("Order #%d: Rs. %.2f", orderId, price);

Output:

Order #1001: Rs. 1299.99

Example 3: NTC Electricity Bill Calculation

NTC bills use double for precise unit calculations:

double units = 250.5;
double rate = 4.50;
double bill = units * rate;
printf("Bill: Rs. %.2f", bill);

Output:

Bill: Rs. 1127.25

7. Common Pitfalls and Best Practices

Mistake Fix Example
Forgetting & in scanf Use & before variables. scanf("%d", &age); ✅
Integer division Cast to float before division. (float)total / count;
Mixing scanf formats Align % specifiers with variables. scanf("%d %f", &x, &y);
Uninitialized variables Always initialize variables. int x = 0;
Using = instead of == Use == for comparison. if (x == 5) ✅, if (x = 5) ❌

8. Worked Example: Student Grade Calculator

Problem: Write a program to input marks in 3 subjects and calculate:

  1. Total marks (int).
  2. Percentage (float).
  3. Grade (char).

Solution:

#include <stdio.h>
int main() {
    int sub1, sub2, sub3;
    float percentage;
    char grade;

    // Input marks
    printf("Enter marks for 3 subjects: ");
    scanf("%d %d %d", &sub1, &sub2, &sub3);

    // Calculate total and percentage
    int total = sub1 + sub2 + sub3;
    percentage = (float)total / 3;  // Explicit cast

    // Determine grade
    if (percentage >= 90) grade = 'A';
    else if (percentage >= 80) grade = 'B';
    else if (percentage >= 70) grade = 'C';
    else grade = 'F';

    // Output results
    printf("Total: %d\n", total);
    printf("Percentage: %.2f%%\n", percentage);
    printf("Grade: %c\n", grade);

    return 0;
}

Input/Output:

Enter marks for 3 subjects: 85 90 78
Total: 253
Percentage: 84.33%
Grade: B

Visual: Execution Flow

flowchart TD
    A["Start"] --> B["Input sub1, sub2, sub3"]
    B --> C["Calculate total = sub1 + sub2 + sub3"]
    C --> D["Calculate percentage = (float)total / 3"]
    D --> E["Check percentage >= 90?"]
    E -->|"Yes"| F["grade = 'A'"]
    E -->|"No"| G["Check percentage >= 80?"]
    G -->|"Yes"| H["grade = 'B'"]
    G -->|"No"| I["Check percentage >= 70?"]
    I -->|"Yes"| J["grade = 'C'"]
    I -->|"No"| K["grade = 'F'"]
    K --> L["Print total, percentage, grade"]
    L --> M["End"]

9. Exam Tip

What Examiners Look For:

  1. Correct Syntax: Ensure scanf() uses &, printf() uses % specifiers correctly.
  2. Type Matching: Align data types (e.g., %d for int, %f for float).
  3. Initialization: Always initialize variables before use.
  4. Type Casting: Use (float) or (double) to avoid integer division.
  5. Real-World Relevance: Relate examples to eSewa, Daraz, or NTC (e.g., "This float stores transaction fees like in eSewa").
  6. Error Handling: Avoid common mistakes like:
    • Forgetting & in scanf.
    • Using = instead of ==.
    • Mixing scanf formats (e.g., %d for float).

Common Exam Questions:

  • Define int, float, char and give examples.
  • Write a program to input 2 numbers and swap them using scanf/printf.
  • Explain type casting with an example (e.g., converting int to float).
  • How does C handle implicit type conversion? Give an example.

Model Answer for Past Question: Q: Define Data Types. Explain different data types available in C Programming. A: Data types define the size, range, and type of data a variable can hold. C supports five primitive data types:

  1. int: Stores integers (whole numbers) in 4 bytes (range: to ). Example: int age = 20;

  2. float: Stores single-precision floating-point numbers (4 bytes, ~6 decimal places). Example: float height = 5.6f;

  3. double: Stores double-precision floating-point numbers (8 bytes, ~15 decimal places). Example: double pi = 3.14159;

  4. char: Stores single characters (1 byte, ASCII range: to ). Example: char grade = 'A';

  5. void: Represents no type (used in functions with no return value). Example: void greet() { printf("Hello!"); }

Comparison Table:

Data Type Size (bytes) Range Example
int 4 to int x = 100;
float 4 ~ decimal places float y = 3.14f;
double 8 ~ decimal places double z = 3.14159;
char 1 to (ASCII) char c = 'B';

Why It Matters:

  • Choosing the right data type saves memory (e.g., char for single letters).
  • Prevents overflow (e.g., int can’t store values beyond ).
  • Ensures precision (e.g., double for financial calculations like NEPSE stock prices).

End of Note

Based on the TU BCA syllabus for C Programming (CACS151), unit 2.

Discussion

Loading…