Elective Programming In C

Programming In CUnit 213 min read

Data Types, Variables & Operators: Fundamentals of C Programming

Unit 2 of Programming In C covers the core building blocks of C: fundamental data types (integer, float, char), variable declaration rules, arithmetic/logical operators, type conversion, and operator precedence—with visual traces, real-world examples, and exam-focused comparisons.

Core Concepts: Data Types in C

1. What Are Data Types?

Data types define:

  • The kind of data a variable can hold (numbers, characters, etc.).
  • The size of memory allocated (e.g., int uses 4 bytes on most systems).
  • The range of values (e.g., int ranges from to on 32-bit systems).
mindmap
  root((Data Types in C))
    Fundamental
      Integer: int, short, long, long long
      Floating: float, double, long double
      Character: char
    Derived
      Array, Pointer, Structure, Union
    Enumeration
      enum
    Void
      void (no data)

2. Fundamental Data Types

Type Keyword Size (bytes) Range Example
Integer int 4 to int age = 20;
Short Integer short 2 to short year = 2023;
Long Integer long 4 (or 8) to (or larger) long population = 3000000000L;
Floating Point float 4 ~6-7 decimal digits precision float pi = 3.14f;
Double double 8 ~15 decimal digits precision double salary = 50000.50;
Character char 1 to (or to ) char grade = 'A';

Key Notes:

  • long long (8 bytes) is used for very large integers (e.g., long long distance = 1000000000000LL;).
  • float vs double: double is preferred for precision (e.g., financial calculations).
  • char stores single characters (e.g., 'A', '$') or ASCII values (e.g., 65 for 'A').

3. Variable Declaration and Initialization

Rules for Naming Variables:

  1. Must start with a letter or underscore (_).
  2. Can contain letters, digits, or underscores (no spaces or special characters).
  3. Case-sensitive: Age ≠ age.
  4. Cannot be a keyword (e.g., int, if, return).

Example:

int studentCount = 50;       // Valid
int 5count;                  // Invalid (starts with digit)
int class-room;              // Invalid (hyphen)
int _totalMarks = 95;        // Valid (starts with underscore)

Visual Trace: Variable Memory Allocation


Operators in C

Operators perform operations on variables and values.

1. Arithmetic Operators

Operator Name Example Result (if a=10, b=3)
+ Addition a + b 13
- Subtraction a - b 7
* Multiplication a * b 30
/ Division a / b 3 (integer division)
% Modulus a % b 1 (remainder)
++ Increment a++ 11 (post-increment)
-- Decrement a-- 9 (post-decrement)

Example: Modulus Operator (Divisibility Check)

#include <stdio.h>
int main() {
    int num = 17;
    if (num % 2 == 0) {
        printf("%d is even.", num);
    } else {
        printf("%d is odd.", num);
    }
    return 0;
}

Output: 17 is odd.

Real-World Link:

  • eSewa uses modulus (%) to validate transaction IDs (e.g., checking if a 10-digit ID is divisible by 7 for error detection).
  • Khalti applies modulus to generate OTP codes (e.g., last digit of a 6-digit OTP is sum_of_first_five % 10).

2. Relational and Logical Operators

Category Operator Name Example Result (if a=5, b=10)
Relational == Equal to a == b 0 (false)
!= Not equal to a != b 1 (true)
> Greater than a > b 0 (false)
< Less than a < b 1 (true)
Logical && Logical AND (a > 0) && (b > 0) 1 (true)
|| Logical OR (a > 10) || (b > 10) 1 (true)
! Logical NOT !(a == b) 1 (true)

Example: Checking Loan Eligibility (Bank Scenario)

#include <stdio.h>
int main() {
    int age = 25, income = 50000;
    if (age >= 18 && income >= 30000) {
        printf("Eligible for loan.");
    } else {
        printf("Not eligible.");
    }
    return 0;
}

Output: Eligible for loan.

Real-World Link:

  • Nepal Rastra Bank (NRB) uses logical AND (&&) to check if a borrower meets both minimum age (18+) and income criteria (≥₹30,000) before approving a loan.
  • Pathao applies || to validate either a phone number or email for driver registration.

3. Assignment Operators

Operator Example Equivalent To
= a = 5 a = 5
+= a += 3 a = a + 3
-= a -= 1 a = a - 1
*= a *= 2 a = a * 2
/= a /= 2 a = a / 2
%= a %= 3 a = a % 3

Example: Compound Assignment in Discount Calculation

float price = 1000.0, discount = 0.1;
price *= (1 - discount);  // price = price * (1 - 0.1)
printf("Final price: %.2f", price);  // Output: 900.00

Real-World Link:

  • Daraz uses *= to apply bulk discounts (e.g., total *= 0.9 for a 10% sale).
  • NTC applies -= to deduct taxes from bills (e.g., bill -= tax_amount).

4. Operator Precedence

Operators are evaluated in a specific order. Use parentheses to override precedence.

Precedence (High to Low) Operators
1 (), [], ., ->
2 !, ~, ++, --, + (unary), - (unary)
3 *, /, %
4 +, -
5 <<, >>
6 <, <=, >, >=
7 ==, !=
8 &&
9 ||
10 ?: (ternary)
11 =, +=, -=, etc.

Example: Evaluating a + b * c - d / e

flowchart TD
  A["Start"] --> B["Evaluate b * c"]
  B --> C["Evaluate d / e"]
  C --> D["Evaluate a + (result from B)"]
  D --> E["Evaluate (result from D) - (result from C)"]
  E --> F["Final Result"]

Trace Table:

Expression Step-by-Step Evaluation (a=1, b=2, c=3, d=6, e=2)
b * c 2 * 3 = 6
d / e 6 / 2 = 3
a + (b * c) 1 + 6 = 7
7 - (d / e) 7 - 3 = 4

Type Conversion in C

1. Implicit Conversion (Automatic)

  • Smaller data type is converted to a larger one to avoid data loss.
  • Example: int to float.
int a = 5;
float b = a;  // a is converted to 5.0 (implicit)

2. Explicit Conversion (Casting)

  • Use (type) to force conversion.
  • Example: float to int (truncates decimal).
float x = 7.99;
int y = (int)x;  // y = 7 (decimal part lost)

Example: Converting Temperature (Celsius to Fahrenheit)

float celsius = 25.5;
float fahrenheit = (celsius * 9/5) + 32;  // Explicit conversion to float
printf("Fahrenheit: %.2f", fahrenheit);  // Output: 77.90

Real-World Link:

  • Weather apps (e.g., AccuWeather) use explicit casting to convert Celsius to Fahrenheit for global users.
  • NTC’s electricity billing truncates float units to int for final consumption (e.g., 56.99 kWh → 56 kWh).

Common Pitfalls and Best Practices

1. Integer Division

  • / between integers truncates the decimal.
int a = 7, b = 2;
printf("%d", a / b);  // Output: 3 (not 3.5)

Fix: Use float or double for division.

float result = (float)a / b;  // Output: 3.5

2. Uninitialized Variables

  • Always initialize variables to avoid garbage values.
int x;  // Uninitialized (contains garbage)
int y = 10;  // Initialized (safe)

3. Operator Precedence Errors

  • Use parentheses to clarify intent.
int result = 10 + 20 * 30;  // 10 + (20 * 30) = 610 (correct)
int result = (10 + 20) * 30;  // (30) * 30 = 900 (intended)

In the Real World

  1. Khalti’s Transaction Validation

    • Uses modulus (%) to check if a transaction ID is valid (e.g., ID % 7 == 0).
    • Example: If a user enters 12345678, Khalti checks 12345678 % 7 == 0 to verify authenticity.
  2. Pathao’s Driver Matching Algorithm

    • Uses logical OR (||) to match drivers based on either proximity or availability.
    • Example:
      if (distance < 5 || driverAvailable) {
          assignRide();
      }
      
  3. Nepal Stock Exchange (NEPSE) Index Calculation

    • Uses floating-point arithmetic (float/double) to compute the NEPSE index (a weighted average of stock prices).
    • Example:
      double totalMarketCap = 0;
      for (int i = 0; i < numStocks; i++) {
          totalMarketCap += (stockPrice[i] * shares[i]);
      }
      double nepseIndex = totalMarketCap / baseValue;
      
  4. eSewa’s Bill Splitting

    • Uses compound assignment (-=) to deduct individual shares from a total bill.
    • Example:
      float totalBill = 5000.0;
      totalBill -= friend1Share;  // Deduct ₹1000
      totalBill -= friend2Share;  // Deduct ₹2000
      

Exam Tip

What Examiners Look For

  1. Correct Syntax

    • Always declare variables with proper data types (e.g., int, float).
    • Example: ❌ int salary = 50000.50; (error) ✅ float salary = 50000.50;
  2. Operator Precedence

    • Questions often test precedence. Always use parentheses if unsure.
    • Example: a = 5 + 3 * 2 → a = 11 (not 16).
  3. Type Conversion

    • Explicit casting ((type)) is critical in calculations involving mixed types.
    • Example: int x = 7 / 2; → x = 3 (lose precision). Use (float)7 / 2 for 3.5.
  4. Real-World Applications

    • Expect 1-2 questions linking concepts to scenarios (e.g., bank interest, e-commerce discounts).
    • Example: "A bank charges 5% interest on a loan. Write a program to calculate the monthly installment using float."
  5. Common Mistakes to Avoid

    • ❌ Using = instead of == in conditions.
    • ❌ Forgetting to initialize variables.
    • ❌ Mixing int and float without casting.

Sample Exam Question & Solution

Question: Write a program to input the marks of 3 subjects and calculate the total marks and percentage. Use float for percentage and ensure no precision loss.

Solution:

#include <stdio.h>
int main() {
    float sub1, sub2, sub3, total, percentage;
    printf("Enter marks for 3 subjects: ");
    scanf("%f %f %f", &sub1, &sub2, &sub3);
    total = sub1 + sub2 + sub3;
    percentage = (total / 300) * 100;  // Explicit division to avoid integer truncation
    printf("Total: %.2f\nPercentage: %.2f%%", total, percentage);
    return 0;
}

Input: 85 90 78 Output:

Total: 253.00
Percentage: 84.33%

Practice Questions for TU/PU Exams

  1. Short Answer:

    • What is the output of printf("%d", 7 / 2 * 2);?
    • Explain the difference between = and ==.
  2. Programming:

    • Write a program to input a number and check if it is divisible by 3 or 5 (use logical OR).
    • Calculate the area of a circle using float for radius and double for area.
  3. Debugging:

    • Find and fix the error in:
      int a = 5, b = 2;
      printf("%d", a / b + b);  // Expected output: 4 (but gives 3)
      
    • Fix: Use (a / b) + b or cast to float.

Final Checklist Before Submission

  • All variables are initialized.
  • Operators are used correctly (no = vs == mix-ups).
  • Parentheses are used where needed.
  • Data types match the requirement (e.g., float for decimals).
  • Real-world relevance is linked (if applicable).

Based on the PU BE Computer (PU) syllabus for Programming In C, unit 2.

Discussion

Loading…