Programming in C - Part 2

Identifiers, Variables, Operators, and Basic Programs

Part 2: Identifiers, Variables, and Basic Programs (90 mins)

Topic 1: Identifiers in C - The "Names" of Things

Definition: Identifiers are names used to identify variables, functions, arrays, structures, or any other user-defined items in a program. They uniquely identify program elements and allow us to refer to them later.

// Creating a variable with identifier 'val'
int val = 10;

// Creating a function with identifier 'func'
void func() {}

// Creating an array with identifier 'scores'
int scores[5];

Rules for Naming Identifiers in C

Identifiers must follow these strict rules:

Valid vs Invalid Identifiers
Valid Identifiers Invalid Identifiers Reason
student_name student name Space not allowed
_count 9students Starts with digit
totalAmount int Keyword not allowed
MAX_SIZE student@name Special character @

Examples of Identifiers in Action

Variable Identifier Example
#include <stdio.h>

int main() {
  // Creating an integer variable with identifier 'var'
  int var;

  // Assigning value using the identifier
  var = 10;

  // Referring to the variable using its identifier
  printf("%d", var);

  return 0;
}

Output: 10

Function Identifier Example
#include <stdio.h>

// Function declaration with identifier 'sum'
int sum(int a, int b) {
  return a + b;
}

int main() {
  // Calling function using its identifier
  printf("%d", sum(10, 20));
  return 0;
}

Output: 30

Naming Conventions (Best Practices)

While not enforced by the compiler, following conventions makes code more readable:

Element Type Convention Examples
Variables camelCase or snake_case studentCount, total_amount
Constants UPPER_SNAKE_CASE MAX_SIZE, PI_VALUE
Functions camelCase (verb-based) calculateTotal(), getUserName()
Structures PascalCase StudentInfo, CarDetails

Keywords vs Identifiers

Feature Keywords Identifiers
Definition Reserved words with special meaning User-defined names for program elements
Purpose Define program structure and control flow Name variables, functions, etc.
Examples int, if, while, return age, calculateTotal, studentName
Modification Fixed by language (cannot be changed) Created by programmer as needed
Common Error: Using Keywords as Identifiers
#include <stdio.h>

int main() {
  // ERROR: 'const' is a keyword, cannot be used as identifier
  int const = 90;

  return 0;
}

Compilation Error: expected identifier or '(' before '=' token

Topic 2: Variables in Depth - Declaration, Definition, and Scope

Variable Declaration vs Definition

Declaration: Tells the compiler about the variable's existence and type

Definition: Actually allocates memory for the variable

// Declaration (informs compiler)
extern int globalVar;

// Definition (allocates memory)
int score = 95;
int age; // Also a definition (memory allocated)

Variable Scope - Where Variables are Accessible

1. Local Variables (Block Scope)

Declared inside a function or block, accessible only within that block

#include <stdio.h>

void demoFunction() {
  int localVar = 10; // Local variable
  printf("Inside function: %d\n", localVar);
}

int main() {
  demoFunction();
  // printf("%d", localVar); // ERROR: localVar not accessible here
  return 0;
}
2. Global Variables (File Scope)

Declared outside all functions, accessible throughout the file

#include <stdio.h>

// Global variable
int globalCount = 0;

void increment() {
  globalCount++;
  printf("Count: %d\n", globalCount);
}

int main() {
  increment();
  increment();
  printf("Final count: %d\n", globalCount);
  return 0;
}

Output:
Count: 1
Count: 2
Final count: 2

Topic 3: Practical Programming Examples

Example 1: Basic Arithmetic Calculator

#include <stdio.h>

int main() {
  int num1, num2;
  int sum, difference, product;
  float quotient;

  printf("Enter two integers: ");
  scanf("%d %d", &num1, &num2);

  // Calculations
  sum = num1 + num2;
  difference = num1 - num2;
  product = num1 * num2;
  quotient = (float)num1 / num2; // Type casting for decimal result

  printf("\nResults:\n");
  printf("Sum: %d\n", sum);
  printf("Difference: %d\n", difference);
  printf("Product: %d\n", product);
  printf("Quotient: %.2f\n", quotient);

  return 0;
}

Example 2: Temperature Converter

#include <stdio.h>

int main() {
  float celsius, fahrenheit;
  int choice;

  printf("Temperature Converter\n");
  printf("1. Celsius to Fahrenheit\n");
  printf("2. Fahrenheit to Celsius\n");
  printf("Enter your choice (1 or 2): ");
  scanf("%d", &choice);

  if (choice == 1) {
    printf("Enter temperature in Celsius: ");
    scanf("%f", &celsius);
    fahrenheit = (celsius * 9/5) + 32;
    printf("%.2f°C = %.2f°F\n", celsius, fahrenheit);
  } else if (choice == 2) {
    printf("Enter temperature in Fahrenheit: ");
    scanf("%f", &fahrenheit);
    celsius = (fahrenheit - 32) * 5/9;
    printf("%.2f°F = %.2f°C\n", fahrenheit, celsius);
  } else {
    printf("Invalid choice!\n");
  }

  return 0;
}

Example 3: Student Grade Calculator

#include <stdio.h>

int main() {
  char studentName[50];
  float marks[5];
  float total = 0, average;
  int i;

  printf("Enter student name: ");
  scanf("%s", studentName);

  printf("Enter marks for 5 subjects:\n");
  for(i = 0; i < 5; i++) {
    printf("Subject %d: ", i+1);
    scanf("%f", &marks[i]);
    total += marks[i];
  }

  average = total / 5;

  printf("\n--- Student Report ---\n");
  printf("Name: %s\n", studentName);
  printf("Total Marks: %.2f/500\n", total);
  printf("Average: %.2f\n", average);

  if(average >= 90) {
    printf("Grade: A\n");
  } else if(average >= 80) {
    printf("Grade: B\n");
  } else if(average >= 70) {
    printf("Grade: C\n");
  } else if(average >= 60) {
    printf("Grade: D\n");
  } else {
    printf("Grade: F\n");
  }

  return 0;
}

Topic 4: Common Errors and Debugging

Error 1: Uninitialized Variables

#include <stdio.h>

int main() {
  int uninitializedVar; // Contains garbage value
  printf("Garbage value: %d\n", uninitializedVar); // Unexpected output
  return 0;
}

Error 2: Using Wrong Format Specifiers

#include <stdio.h>

int main() {
  int age = 25;
  // Wrong: using %f for integer
  printf("Age: %f\n", age); // Undefined behavior
  // Correct: using %d for integer
  printf("Age: %d\n", age);
  return 0;
}

Error 3: Case Sensitivity Issues

#include <stdio.h>

int main() {
  int studentAge = 20;
  // Wrong: different case
  printf("Age: %d\n", StudentAge); // Compilation error
  // Correct: same case
  printf("Age: %d\n", studentAge);
  return 0;
}

Part 5: Hands-On Practice Exercises

Exercise 1: Simple Interest Calculator

Problem: Write a program to calculate simple interest using the formula: SI = (P × R × T) / 100

Requirements: Take principal amount, rate of interest, and time as input from user

Exercise 2: Area Calculator

Problem: Write a program that calculates area of circle, rectangle, and triangle based on user choice

Formulas:

Exercise 3: BMI Calculator

Problem: Calculate Body Mass Index using formula: BMI = weight(kg) / (height(m))²

Categories:

Part 6: Summary and Key Takeaways

What We Covered Today:

Key Rules to Remember:

Topic 3: Operators in C

Operators are symbols that tell the compiler to perform specific mathematical or logical operations on variables and values.

1. Arithmetic Operators

Used for basic mathematical operations: + - * / %

#include <stdio.h>

int main() {
  int a = 10, b = 3;
  printf("a + b = %d\n", a + b);
  printf("a - b = %d\n", a - b);
  printf("a * b = %d\n", a * b);
  printf("a / b = %d\n", a / b); // integer division
  printf("a %% b = %d\n", a % b); // remainder
  return 0;
}

a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1

2. Relational and Logical Operators

Relational: <, <=, >, >=, ==, !=
Logical: && (AND), || (OR), ! (NOT)

int x = 5, y = 10;
printf("x < y = %d\n", x < y);
printf("x == y = %d\n", x == y);
printf("(x < y) && (y > 0) = %d\n", (x < y) && (y > 0));

x < y = 1
x == y = 0
(x < y) && (y > 0) = 1

3. Assignment Operators

Used to assign values: =, +=, -=, *=, /=, %=

int a = 10;
a += 5; // a = a + 5 (now 15)
a *= 2; // a = a * 2 (now 30)

4. Increment / Decrement Operators

++ increases value by 1, -- decreases by 1. They can be prefix (++x) or postfix (x++).

int x = 5;
printf("%d\n", ++x); // 6 (prefix: increment then use)
printf("%d\n", x++); // 6 (postfix: use then increment)
printf("%d\n", x); // 7

5. Bitwise Operators

Work at the binary level: & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left Shift), >> (Right Shift)

int a = 5, b = 3;
printf("a & b = %d\n", a & b); // 0101 & 0011 = 0001
printf("a | b = %d\n", a | b); // 0101 | 0011 = 0111
printf("a ^ b = %d\n", a ^ b); // 0101 ^ 0011 = 0110
printf("~a = %d\n", ~a);
printf("a << 1 = %d\n", a << 1); // shift left
printf("b >> 1 = %d\n", b >> 1); // shift right

6. Ternary Operator

Shorthand for if-else: condition ? expression1 : expression2

int age = 20;
printf("%s\n", (age >= 18) ? "Adult" : "Minor");

Adult

💡 Practice Tip

Try combining operators. For example, check if a number is even using both modulo and ternary operator:
printf("%s", (num % 2 == 0) ? "Even" : "Odd");

Topic 4: Practical Programming Examples

Topic 5: Common Errors and Debugging

Part 6: Hands-On Practice Exercises

Part 7: Summary and Key Takeaways