Course: C Programming - BTech First Semester

Instructor: Dr. Mohsin Dar
Position: Assistant Professor
Department: Cloud & Software Operations Cluster | SOCS | UPES

C Programming Fundamentals

Type Casting, Operators & Error Types

🎯 Learning Objectives

📚 Part 1: Type Casting in C Programming

What is Type Casting?

Type casting is the process of converting one data type to another. In C, this can happen automatically (implicit) or manually (explicit).

1.1 Implicit Type Casting (Automatic)

Rule: When performing operations between different data types, C automatically converts the "smaller" type to the "larger" type.

Let's solve your examples step by step:

Example 12: Integer Division Assignment to Float

#include <stdio.h>
int main() {
    float x = 5/2;    // Integer division happens FIRST!
    printf("%.5f", x);
    return 0;
}
Output: 2.00000
Why 2.00000?
1. 5/2 is integer division = 2 (not 2.5)
2. Then 2 is converted to float 2.0
3. Assigned to x as 2.00000

Example 13: Similar Integer Division

#include <stdio.h>
int main() {
    float x = 7 / 4;   // Integer division
    printf("%.2f", x);
    return 0;
}
Output: 1.00

Explanation: 7 ÷ 4 in integer division = 1 (remainder ignored)

Example 14: Mixed Type Division

#include <stdio.h>
int main() {
    float x = 7 / 4.0;  // Mixed division: int / float
    printf("%.2f", x);
    return 0;
}
Output: 1.75
Key Point: 4.0 is a float, so 7 is automatically converted to 7.0, giving us floating-point division: 7.0 ÷ 4.0 = 1.75

1.2 Explicit Type Casting

Manual conversion using the cast operator: (datatype)variable

Example 15: Post-Division Casting (WRONG WAY)

#include <stdio.h>
int main() {
    int a = 5, b = 2;
    printf("%.1f", (float)(a / b));  // Cast AFTER division
    return 0;
}
Output: 2.0
Problem: Division happens first (5/2 = 2), then 2 is cast to float 2.0

Example 16: Pre-Division Casting (CORRECT WAY)


#include <stdio.h>
int main() {
    int a = 5, b = 2;
    printf("%.1f", (float)a / b);  // Cast BEFORE division
    return 0;
}
Output: 2.5
Success: a is cast to float first (5.0), then division: 5.0 ÷ 2 = 2.5

Type Casting Summary Table

Expression Order of Operations Result Explanation
float x = 5/2; 5/2 → assign to x 2.0 Integer division first
float x = 5/2.0; 5→5.0, then 5.0/2.0 2.5 Float division
(float)(5/2) 5/2 → cast result 2.0 Cast after division
(float)5/2 cast 5 → divide by 2 2.5 Cast before division

⚡ Part 2: Operators in C Programming

2.1 Increment/Decrement Operators

Pre-increment (++x)

int x = 5;
int y = ++x;  // x is incremented FIRST, then assigned
// x = 6, y = 6
            

Post-increment (x++)

int x = 5;
int y = x++;  // x is assigned FIRST, then incremented
// x = 6, y = 5
            

Complex Examples

#include <stdio.h>
int main() {
    int a = 5, b, c;
    
    b = ++a;    // Pre-increment: a becomes 6, b gets 6
    c = a++;    // Post-increment: c gets 6, a becomes 7
    
    printf("a = %d, b = %d, c = %d\n", a, b, c);
    return 0;
}
            
div>
Output: a = 7, b = 6, c = 6

2.2 Bitwise Operators

Left Shift (<<)

Formula: x << n = x × 2^n
int x = 5;        // Binary: 101
int result = x << 2;  // Shift left by 2 positions
// Result: 10100 (binary) = 20 (decimal)
// 5 × 2² = 5 × 4 = 20
            
div>

Right Shift (>>)

Formula: x >> n = x ÷ 2^n
int x = 20;       // Binary: 10100
int result = x >> 2;  // Shift right by 2 positions
// Result: 101 (binary) = 5 (decimal)
// 20 ÷ 2² = 20 ÷ 4 = 5
            

Operator Precedence Examples

#include <stdio.h>
int main() {
    int x = 5;
    int result1 = x++ + ++x;  // Complex expression
    
    // Step by step:
    // x = 5 initially
    // x++: uses 5, then x becomes 6
    // ++x: x becomes 7, uses 7
    // result1 = 5 + 7 = 12
    // Final x = 7
    
    printf("result1 = %d, x = %d\n", result1, x);
    return 0;
}
            
div>
Output: result1 = 12, x = 7

🐛 Part 3: Types of Errors in C Programming

3.1 Compile-Time Errors (Syntax Errors)

When: Detected during compilation
Cause: Violation of C language rules
Result: Program won't compile

Common Compile-Time Errors:

// Missing semicolon
int x = 5  // ERROR: Missing semicolon
printf("Hello");

// Undeclared variable
int x = 5;
y = 10;    // ERROR: 'y' not declared

// Wrong function name
#include <stdio.h>
int main() {
    Print("Hello");  // ERROR: should be 'printf'
    return 0;
}

// Mismatched braces
int main() {
    if (x > 5) {
        printf("Greater");
    // ERROR: Missing closing brace
    return 0;
}
            

3.2 Runtime Errors

When: Occurs during program execution
Cause: Invalid operations or conditions
Result: Program crashes or behaves unexpectedly

Common Runtime Errors:

// Division by zero
#include <stdio.h>
int main() {
    int a = 10, b = 0;
    int result = a / b;  // RUNTIME ERROR: Division by zero
    printf("%d\n", result);
    return 0;
}

// Array index out of bounds
#include <stdio.h>
int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    printf("%d\n", arr[10]);  // RUNTIME ERROR: Invalid index
    return 0;
}

// Infinite recursion
int factorial(int n) {
    return n * factorial(n);  // ERROR: No base case
}
            

3.3 Logical Errors

When: Program runs but produces wrong output
Cause: Incorrect algorithm or logic
Result: Wrong results, hardest to debug

Examples of Logical Errors:

// Wrong loop condition
#include <stdio.h>
int main() {
    int sum = 0;
    // Intent: sum numbers from 1 to 10
    for(int i = 1; i < 10; i++) {  // BUG: Should be i <= 10
        sum += i;
    }
    printf("Sum: %d\n", sum);  // Prints 45 instead of 55
    return 0;
}

// Wrong formula
#include <stdio.h>
int main() {
    int celsius = 25;
    // Intent: Convert Celsius to Fahrenheit
    // Correct formula: F = (C × 9/5) + 32
    int fahrenheit = celsius * 9/5 + 32;  // BUG: Integer division
    printf("%d°C = %d°F\n", celsius, fahrenheit);
    return 0;
}
            

Error Comparison Table

Error Type Detection Time Program Behavior Example Difficulty to Fix
Compile-Time During compilation Won't compile Missing semicolon Easy
Runtime During execution Crashes/abnormal termination Division by zero Medium
Logical During testing/use Wrong output Incorrect formula Hard

🔧 Part 4: Debugging Strategies

4.1 For Compile-Time Errors

  • Read error messages carefully
  • Check line numbers mentioned in errors
  • Look for missing semicolons, braces, or quotes
  • Verify variable declarations
  • Check spelling of keywords and function names

4.2 For Runtime Errors

  • Use printf statements to trace execution
  • Check for division by zero
  • Validate array bounds
  • Ensure proper memory allocation
  • Test edge cases and boundary conditions

4.3 For Logical Errors

  • Trace through code manually with sample data
  • Add printf statements to check intermediate values
  • Verify algorithms and formulas
  • Test with known input-output pairs
  • Use a debugger to step through code

📝 Practice Problems

Type Casting Challenges

// Problem 1: Predict the output
int a = 7, b = 3;
printf("%.2f\n", (float)a / b);
printf("%.2f\n", a / (float)b);
printf("%.2f\n", (float)(a / b));

// Problem 2: Fix this code to get accurate division
int marks = 85, total = 100;
float percentage = marks / total * 100;  // Currently gives 0.00
// How would you fix this?
            

Operator Challenges

// Problem 3: Trace the execution
int x = 3, y = 4, z;
z = ++x + y++;
printf("x=%d, y=%d, z=%d\n", x, y, z);

// Problem 4: Bitwise operations
int num = 12;  // Binary: 1100
printf("Left shift by 2: %d\n", num << 2);
printf("Right shift by 1: %d\n", num >> 1);
            

🎯 Key Takeaways

Type Casting Rules:
  • Integer division always produces integer result
  • Cast operands BEFORE division for accurate results
  • Mixed-type operations promote to higher precision type
Operator Guidelines:
  • ++x: increment first, then use
  • x++: use first, then increment
  • Left shift multiplies by powers of 2
  • Right shift divides by powers of 2
Error Prevention:
  • Always compile and test frequently
  • Use meaningful variable names
  • Comment your complex logic
  • Test with edge cases and boundary values

These lecture notes are designed to help BTech students master fundamental C programming concepts. Practice regularly and don't hesitate to ask questions during class!

- Dr. Mohsin Dar, UPES