Unit 1 - Notes

CSE109

Unit 1: Basics and introduction to C

1. The C Character Set

The C character set is the fundamental set of valid characters that can be used to write a source program in C. It is categorized into four main groups:

A. Letters (Alphabets)

C distinguishes between uppercase and lowercase letters (case-sensitive).

  • Uppercase: A to Z
  • Lowercase: a to z

B. Digits

  • Decimal digits: 0 to 9

C. Special Characters

These characters have specific meanings in C statements or expressions.

  • Examples: , . ; : ? ' " ! | / \ ~ _ $ % & ^ * - + < > ( ) { } [ ] #

D. White Space Characters

Used to separate words and lines. The compiler generally ignores these during compilation (except in strings).

  • Blank space
  • Horizontal tab (\t)
  • Carriage return (\r)
  • New line (\n)
  • Form feed

2. Identifiers and Keywords

Identifiers

Identifiers are user-defined names given to various program elements such as variables, functions, and arrays.

Rules for naming Identifiers:

  1. Must begin with a letter (A-Z or a-z) or an underscore (_).
  2. Subsequent characters can be letters, digits, or underscores.
  3. No special characters (like @, $, %) are allowed.
  4. Keywords cannot be used as identifiers.
  5. Identifiers are case-sensitive (e.g., Sum and sum are different).
  6. Spaces are not allowed.
  • Valid: total_marks, _temp, a123
  • Invalid: 1stPlace (starts with digit), total-marks (hyphen not allowed), int (keyword).

Keywords

Keywords are reserved words in C that have fixed, predefined meanings. They cannot be changed or used as variable names. ANSI C defines 32 standard keywords.

Common Keywords: Type Keywords
Data Types int, char, float, double, void
Control Flow if, else, switch, case, default
Loops while, do, for, break, continue
Storage Classes auto, extern, register, static
Others return, struct, union, typedef, const, sizeof

3. Data Types

Data types specify the type of data a variable can hold and how much memory is allocated for it.

A. Primary (Fundamental) Data Types

  1. Integer (int):
    • Stores whole numbers.
    • Format Specifier: %d
    • Size: Typically 2 or 4 bytes (machine dependent).
  2. Character (char):
    • Stores a single character (ASCII value).
    • Format Specifier: %c
    • Size: 1 byte.
  3. Floating Point (float):
    • Stores numbers with decimal points (single precision).
    • Format Specifier: %f
    • Size: 4 bytes (6 decimal places precision).
  4. Double (double):
    • Stores numbers with decimal points (double precision).
    • Format Specifier: %lf
    • Size: 8 bytes (15 decimal places precision).
  5. Void (void):
    • Represents the absence of value. Used in functions returning nothing.

B. Data Type Modifiers

Used to alter the size or range of primary data types:

  • signed: (Default) Positive and negative values.
  • unsigned: Only positive values (doubles the positive range).
  • short: Reduces storage size (usually 2 bytes).
  • long: Increases storage size.

4. Constants and Variables

Variables

A variable is a named location in memory used to hold a value that may be modified during program execution.

Syntax:

C
data_type variable_name;           // Declaration
data_type variable_name = value;   // Initialization

Example:
C
int age = 21;
float salary = 5000.50;

Constants (Literals)

Constants are fixed values that do not change during the execution of a program.

  1. Integer Constants: Whole numbers (e.g., 10, -5, 0).
    • Can be Decimal, Octal (starts with 0), or Hexadecimal (starts with 0x).
  2. Real (Floating-point) Constants: Numbers with decimals (e.g., 3.14, -0.05).
  3. Character Constants: Single character enclosed in single quotes (e.g., 'a', '5', '+').
  4. String Constants: Sequence of characters enclosed in double quotes (e.g., "Hello World"). Ends with a null character \0 automatically.

Defining Constants:

  • Using #define: Preprocessor directive.
    C
        #define PI 3.14
        
  • Using const keyword:
    C
        const int MAX_VAL = 100;
        

5. Expressions

An expression is a combination of variables, constants, and operators that results in a single value.

  • L-value: Refers to a memory location (appears on the left side of assignment).
  • R-value: Refers to the data value stored (appears on the right side).

Type Conversion in Expressions:

  1. Implicit (Type Promotion): Compiler automatically converts lower precision types to higher precision (e.g., int to float).
  2. Explicit (Type Casting): User forces conversion.
    C
        float a = (float) 5 / 2; // Result is 2.5
        

6. Operators

Operators are symbols that tell the compiler to perform specific mathematical or logical manipulations.

A. Arithmetic Operators

Used for mathematical calculations.

Operator Meaning Example (a=10, b=3)
+ Addition a + b = 13
- Subtraction a - b = 7
* Multiplication a * b = 30
/ Division a / b = 3 (Integer division truncates decimals)
% Modulus (Remainder) a % b = 1 (Only works with integers)

B. Unary Operators

Operators that require only one operand.

  1. Unary Minus (-): Negates a value (-a).
  2. Increment (++): Increases value by 1.
    • Pre-increment (++a): Increment first, then use value.
    • Post-increment (a++): Use value first, then increment.
  3. Decrement (--): Decreases value by 1.
  4. Sizeof (sizeof): Returns the size of a variable or type in bytes.

C. Relational Operators

Used to compare two values. Returns 1 (True) or 0 (False).

Operator Meaning Example (a=10, b=20)
== Equal to a == b is 0 (False)
!= Not equal to a != b is 1 (True)
> Greater than a > b is 0
< Less than a < b is 1
>= Greater than or equal a >= b is 0
<= Less than or equal a <= b is 1

D. Logical Operators

Used to combine multiple conditions.

  1. Logical AND (&&): True only if both operands are true.
    • if (a > 5 && b < 30)
  2. Logical OR (||): True if at least one operand is true.
    • if (a == 5 || b == 5)
  3. Logical NOT (!): Reverses the state (True becomes False).
    • !(a == b)

E. Assignment Operators

Used to assign the result of an expression to a variable.

  • Simple Assignment: =
  • Compound Assignment (Shorthand):
    • += : a += b implies a = a + b
    • -= : a -= b implies a = a - b
    • *= : a *= b implies a = a * b
    • /= : a /= b implies a = a / b
    • %= : a %= b implies a = a % b

F. Conditional (Ternary) Operator

A shorthand for if-else. It is the only operator in C that takes three operands.

Syntax:

C
Condition ? Expression1 : Expression2;

If the condition is True, Expression1 executes. If False, Expression2 executes.

Example:

C
int a = 10, b = 20;
int max = (a > b) ? a : b; // max becomes 20

G. Bitwise Operators

Used to perform operations at the bit level (binary level).

Operator Name Description Example (A=5 0101, B=9 1001)
& Bitwise AND 1 if both bits are 1. A & B = 1 (0001)
| Bitwise OR 1 if either bit is 1. A | B = 13 (1101)
^ Bitwise XOR 1 if bits are different. A ^ B = 12 (1100)
~ One's Complement Inverts all bits. ~A = -6
<< Left Shift Shifts bits to left (Multiply by 2^n). A << 1 = 10 (1010)
>> Right Shift Shifts bits to right (Divide by 2^n). A >> 1 = 2 (0010)

Operator Precedence and Associativity

When multiple operators appear in an expression, the priority is determined by precedence.

  1. Unary (++, --, !)
  2. Arithmetic (*, /, % then +, -)
  3. Relational (<, >, <=, >=)
  4. Equality (==, !=)
  5. Logical (&& then ||)
  6. Conditional (?:)
  7. Assignment (=, +=, etc.)