๏ปฟ Computer Programming in C | EduArtha

University Textbook โ€ข EduArtha

Computer Programming in C

Master C programming โ€” data types, operators, control flow, functions, arrays, pointers, strings, structures, file handling, linked lists & more.

๐Ÿ“š 10 Chapters โ€ข 200+ MCQs โ€ข 12 Lab Experiments โ€ข Real-life & Industry Problems

Unit I

Foundations of C Programming

Character set, data types, operators & expressions

Chapter 1

Basics and Introduction to C

Learning Objectives

  • Understand the history and features of the C programming language
  • Describe the structure of a C program
  • Identify the C character set, identifiers, and all 32 keywords
  • Declare variables and use all fundamental data types
  • Work with constants, expressions, and all categories of operators
  • Apply type casting โ€” both implicit and explicit
  • Write, compile, and execute your first C program

1.1 History of C

The C programming language was developed by Dennis Ritchie at Bell Laboratories (AT&T) in 1972. It evolved from two earlier languages โ€” BCPL (Basic Combined Programming Language, by Martin Richards, 1967) and B (by Ken Thompson, 1970). C was originally designed to re-implement the UNIX operating system, which had previously been written in assembly language.

YearLanguageDeveloper
1967BCPLMartin Richards
1970BKen Thompson
1972CDennis Ritchie
1978K&R CKernighan & Ritchie (book)
1989ANSI C (C89)ANSI Committee
1999C99ISO/IEC
2011C11ISO/IEC
2018C17ISO/IEC
2024C23ISO/IEC

1.2 Features of C

  • Middle-level language โ€” combines features of high-level and low-level languages
  • Structured programming โ€” supports functions and blocks
  • Portability โ€” C programs can be compiled on different platforms with minimal changes
  • Rich operator set โ€” arithmetic, bitwise, logical, relational, and more
  • Pointers โ€” direct memory access and manipulation
  • Fast execution โ€” compiled to machine code, close to hardware
  • Extensible โ€” new functions can be added to the library
  • Recursion โ€” functions can call themselves

1.3 Applications of C

C is used to build: Operating systems (Linux, Windows kernel), Embedded systems (microcontrollers, IoT), Compilers (GCC), Database engines (MySQL, PostgreSQL), Game engines, Device drivers, and Networking tools.

1.4 Structure of a C Program

C
/* Documentation Section (optional) */
/* Preprocessor Directives */
#include <stdio.h>

/* Global Declarations (optional) */
int globalVar = 10;

/* Main Function */
int main() {
    /* Local Declarations */
    int a = 5;

    /* Executable Statements */
    printf("Hello, World!\n");

    return 0;
}

/* User-defined Functions (optional) */
Hello, World!

Every C Program Must Have main()

The main() function is the entry point of every C program. The operating system calls main() when the program starts. return 0; indicates successful execution.

1.5 The C Character Set

CategoryCharacters
Uppercase LettersA B C D โ€ฆ Z (26)
Lowercase Lettersa b c d โ€ฆ z (26)
Digits0 1 2 3 4 5 6 7 8 9 (10)
Special Characters~ ! @ # $ % ^ & * ( ) _ + - = { } [ ] | \ : " ; ' < > ? , . /
WhitespaceSpace, Tab (\t), Newline (\n), Carriage Return (\r)

1.6 Identifiers and Naming Rules

An identifier is a name given to variables, functions, arrays, or any user-defined item. Rules:

  • Must begin with a letter (A-Z, a-z) or underscore (_)
  • Can contain letters, digits (0-9), and underscores
  • Cannot start with a digit
  • Cannot use C keywords as identifiers
  • C is case-sensitive: age and Age are different
  • No limit on length (but first 31 characters are significant in C89)
ValidInvalidReason
count2countStarts with digit
_tempintReserved keyword
total_markstotal marksContains space
MAX_SIZEmy-varContains hyphen

1.7 Keywords in C

C has 32 reserved keywords (C89/C90). These cannot be used as identifiers.

All 32 C Keywords
autobreakcasecharconstcontinuedefaultdo
doubleelseenumexternfloatforgotoif
intlongregisterreturnshortsignedsizeofstatic
structswitchtypedefunionunsignedvoidvolatilewhile

1.8 Data Types

C provides several fundamental data types. The size may vary by platform; the table below shows typical sizes on a 32/64-bit system.

Data TypeSize (bytes)RangeFormat Specifier
char1-128 to 127%c
unsigned char10 to 255%c
short2-32,768 to 32,767%hd
int4-2,147,483,648 to 2,147,483,647%d
unsigned int40 to 4,294,967,295%u
long4 or 8ยฑ2 billion (32-bit) or larger%ld
long long8-9.2ร—10ยนโธ to 9.2ร—10ยนโธ%lld
float43.4ร—10โปยณโธ to 3.4ร—10ยณโธ (6-7 digits precision)%f
double81.7ร—10โปยณโฐโธ to 1.7ร—10ยณโฐโธ (15-16 digits)%lf
long double12 or 16Extended precision%Lf
void0No valueโ€”
C
#include <stdio.h>

int main() {
    printf("Size of char:        %zu byte\n", sizeof(char));
    printf("Size of int:         %zu bytes\n", sizeof(int));
    printf("Size of float:       %zu bytes\n", sizeof(float));
    printf("Size of double:      %zu bytes\n", sizeof(double));
    printf("Size of long long:   %zu bytes\n", sizeof(long long));
    return 0;
}
Size of char: 1 byte Size of int: 4 bytes Size of float: 4 bytes Size of double: 8 bytes Size of long long: 8 bytes

1.9 Constants

Integer Constants

Decimal: 42, Octal (prefix 0): 052, Hexadecimal (prefix 0x): 0x2A

Suffixes: 10L (long), 10U (unsigned), 10UL (unsigned long), 10LL (long long)

Floating-Point Constants

3.14, 2.0e5 (= 200000.0), 1.5E-3 (= 0.0015). Default type is double; suffix f for float: 3.14f

Character Constants

A single character in single quotes: 'A', '9', '$'. Stored as ASCII integer value.

Escape SequenceMeaningASCII
\nNewline10
\tHorizontal Tab9
\0Null character0
\\Backslash92
\'Single quote39
\"Double quote34
\aAlert (bell)7
\bBackspace8
\rCarriage return13

String Constants

A sequence of characters in double quotes: "Hello". Automatically terminated with \0.

1.10 Variables

A variable is a named location in memory that holds a value which can change during program execution.

data_type variable_name = initial_value;
C
int age = 21;              // Declaration + Initialization
float gpa;                   // Declaration only (contains garbage)
gpa = 8.75;                 // Assignment
char grade = 'A';          // Character variable
const int MAX = 100;       // Constant โ€” cannot be changed

1.11 Expressions and Statements

An expression is a combination of variables, constants, and operators that evaluates to a value: a + b * c. A statement is a complete instruction ending with a semicolon: x = a + b;

1.12 Arithmetic Operators

OperatorMeaningExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division5 / 31 (integer!)
%Modulus5 % 32

Integer Division Gotcha

5 / 3 gives 1, not 1.666! When both operands are integers, C performs integer division (truncates decimal). Use 5.0 / 3 or (float)5 / 3 to get 1.666667.

C
#include <stdio.h>

int main() {
    int a = 17, b = 5;
    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);
    printf("a / b = %.2f\n", (float)a / b);  // Float division
    return 0;
}
a + b = 22 a - b = 12 a * b = 85 a / b = 3 a % b = 2 a / b = 3.40

1.13 Unary Operators

OperatorMeaningExample
++xPre-increment (increment, then use)x=5; y=++x; โ†’ x=6, y=6
x++Post-increment (use, then increment)x=5; y=x++; โ†’ x=6, y=5
--xPre-decrementx=5; y=--x; โ†’ x=4, y=4
x--Post-decrementx=5; y=x--; โ†’ x=4, y=5
-xUnary minus (negation)x=5; -x โ†’ -5
+xUnary plusx=5; +x โ†’ 5
!xLogical NOT!0 โ†’ 1, !5 โ†’ 0
~xBitwise NOT (complement)~0 โ†’ -1 (all bits flipped)
sizeof(x)Size in bytessizeof(int) โ†’ 4
&xAddress of xReturns memory address
*pDereference pointer pReturns value at address
C
#include <stdio.h>

int main() {
    int a = 5, b, c;

    b = ++a;   // Pre: a becomes 6, then b = 6
    printf("After ++a: a=%d, b=%d\n", a, b);

    a = 5;
    c = a++;   // Post: c = 5, then a becomes 6
    printf("After a++: a=%d, c=%d\n", a, c);

    printf("!0 = %d, !5 = %d\n", !0, !5);
    printf("~0 = %d\n", ~0);
    return 0;
}
After ++a: a=6, b=6 After a++: a=6, c=5 !0 = 1, !5 = 0 ~0 = -1

1.14 Relational Operators

Relational operators compare two values and return 1 (true) or 0 (false).

OperatorMeaningExample (a=10, b=20)Result
==Equal toa == b0 (false)
!=Not equal toa != b1 (true)
<Less thana < b1 (true)
>Greater thana > b0 (false)
<=Less than or equala <= b1 (true)
>=Greater than or equala >= b0 (false)

1.15 Logical Operators

OperatorMeaningExampleResult
&&Logical AND(5 > 3) && (2 < 4)1 (both true)
||Logical OR(5 > 3) || (2 > 4)1 (one true)
!Logical NOT!(5 > 3)0 (negation)

Short-Circuit Evaluation

In A && B, if A is false, B is never evaluated. In A || B, if A is true, B is never evaluated. This is called short-circuit evaluation and is often used for safe pointer checks: if (ptr != NULL && *ptr == 5)

1.16 Assignment Operators

OperatorExampleEquivalent
=x = 10Assign 10 to x
+=x += 5x = x + 5
-=x -= 3x = x - 3
*=x *= 2x = x * 2
/=x /= 4x = x / 4
%=x %= 3x = x % 3
<<=x <<= 2x = x << 2
>>=x >>= 1x = x >> 1
&=x &= 0xFx = x & 0xF
|=x |= 0x1x = x | 0x1
^=x ^= 0xFFx = x ^ 0xFF

1.17 Conditional (Ternary) Operator

condition ? value_if_true : value_if_false
C
int a = 10, b = 20;
int max = (a > b) ? a : b;   // max = 20
printf("Max = %d\n", max);

// Equivalent to:
if (a > b) max = a;
else max = b;

1.18 Bitwise Operators

Bitwise operators work on individual bits of integer values.

OperatorNameExample (a=5 โ†’ 0101, b=3 โ†’ 0011)Result
&AND5 & 3 โ†’ 0101 & 00110001 = 1
|OR5 | 3 โ†’ 0101 | 00110111 = 7
^XOR5 ^ 3 โ†’ 0101 ^ 00110110 = 6
~NOT~5 โ†’ ~0000010111111010 = -6
<<Left Shift5 << 1 โ†’ 0101 << 11010 = 10
>>Right Shift5 >> 1 โ†’ 0101 >> 10010 = 2
C
#include <stdio.h>

int main() {
    int a = 5, b = 3;  // a = 0101, b = 0011
    printf("a & b  = %d\n", a & b);   // 0001 = 1
    printf("a | b  = %d\n", a | b);   // 0111 = 7
    printf("a ^ b  = %d\n", a ^ b);   // 0110 = 6
    printf("~a     = %d\n", ~a);      // -6
    printf("a << 1 = %d\n", a << 1);  // 1010 = 10
    printf("a >> 1 = %d\n", a >> 1);  // 0010 = 2
    return 0;
}
a & b = 1 a | b = 7 a ^ b = 6 ~a = -6 a << 1 = 10 a >> 1 = 2

Left Shift = Multiply by 2โฟ, Right Shift = Divide by 2โฟ

x << n is equivalent to x ร— 2โฟ. x >> n is equivalent to x / 2โฟ (integer division). This is much faster than multiplication/division and is used extensively in embedded systems and game engines.

1.19 Operator Precedence and Associativity

PrecedenceOperatorDescriptionAssociativity
1 (highest)() [] -> .PostfixLeft to Right
2++ -- + - ! ~ * & sizeof (type)Unary/PrefixRight to Left
3* / %MultiplicativeLeft to Right
4+ -AdditiveLeft to Right
5<< >>ShiftLeft to Right
6< <= > >=RelationalLeft to Right
7== !=EqualityLeft to Right
8&Bitwise ANDLeft to Right
9^Bitwise XORLeft to Right
10|Bitwise ORLeft to Right
11&&Logical ANDLeft to Right
12||Logical ORLeft to Right
13?:TernaryRight to Left
14= += -= *= /= %= etc.AssignmentRight to Left
15 (lowest),CommaLeft to Right

1.20 Type Casting

Implicit Casting (Widening / Type Promotion)

C automatically converts a smaller type to a larger type: char โ†’ int โ†’ long โ†’ float โ†’ double

C
int x = 10;
float y = 3.5;
float result = x + y;  // x is promoted to float: 10.0 + 3.5 = 13.5

Explicit Casting (Narrowing)

C
float pi = 3.14159;
int truncated = (int)pi;    // truncated = 3 (decimal lost!)

int a = 7, b = 2;
float div = (float)a / b;  // 7.0 / 2 = 3.5 (not 3!)

Temperature Converter

A program that converts between Celsius and Fahrenheit โ€” commonly used in weather apps and IoT sensors.

C
#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 choice: ");
    scanf("%d", &choice);

    if (choice == 1) {
        printf("Enter Celsius: ");
        scanf("%f", &celsius);
        fahrenheit = (celsius * 9.0 / 5.0) + 32;
        printf("%.2fยฐC = %.2fยฐF\n", celsius, fahrenheit);
    } else if (choice == 2) {
        printf("Enter Fahrenheit: ");
        scanf("%f", &fahrenheit);
        celsius = (fahrenheit - 32) * 5.0 / 9.0;
        printf("%.2fยฐF = %.2fยฐC\n", fahrenheit, celsius);
    }
    return 0;
}
=== Temperature Converter === 1. Celsius to Fahrenheit 2. Fahrenheit to Celsius Enter choice: 1 Enter Celsius: 100 100.00ยฐC = 212.00ยฐF

Simple Calculator

C
#include <stdio.h>

int main() {
    double a, b, result;
    char op;

    printf("Enter expression (e.g. 5 + 3): ");
    scanf("%lf %c %lf", &a, &op, &b);

    switch (op) {
        case '+': result = a + b; break;
        case '-': result = a - b; break;
        case '*': result = a * b; break;
        case '/':
            if (b != 0) result = a / b;
            else { printf("Error: Division by zero!\n"); return 1; }
            break;
        case '%': result = (int)a % (int)b; break;
        default: printf("Invalid operator!\n"); return 1;
    }
    printf("%.2lf %c %.2lf = %.2lf\n", a, op, b, result);
    return 0;
}
Enter expression (e.g. 5 + 3): 15 * 4 15.00 * 4.00 = 60.00

Bit Manipulation for Embedded Systems Flags

In embedded systems (e.g., microcontrollers), hardware registers use individual bits as flags. Bitwise operators are essential for setting, clearing, and checking these flags without affecting others.

C
#include <stdio.h>

// Device status flags (each bit = one flag)
#define FLAG_POWER    (1 << 0)  // Bit 0: 0x01
#define FLAG_WIFI     (1 << 1)  // Bit 1: 0x02
#define FLAG_BLUETOOTH (1 << 2) // Bit 2: 0x04
#define FLAG_GPS      (1 << 3)  // Bit 3: 0x08
#define FLAG_ERROR    (1 << 7)  // Bit 7: 0x80

void printStatus(unsigned char reg) {
    printf("Status: Power=%d WiFi=%d BT=%d GPS=%d Error=%d\n",
        (reg & FLAG_POWER) ? 1 : 0,
        (reg & FLAG_WIFI) ? 1 : 0,
        (reg & FLAG_BLUETOOTH) ? 1 : 0,
        (reg & FLAG_GPS) ? 1 : 0,
        (reg & FLAG_ERROR) ? 1 : 0);
}

int main() {
    unsigned char deviceReg = 0x00;  // All off

    // SET flags (turn ON): use OR
    deviceReg |= FLAG_POWER;
    deviceReg |= FLAG_WIFI;
    printf("After power + wifi ON:\n");
    printStatus(deviceReg);

    // CLEAR a flag (turn OFF): use AND NOT
    deviceReg &= ~FLAG_WIFI;
    printf("After wifi OFF:\n");
    printStatus(deviceReg);

    // TOGGLE a flag: use XOR
    deviceReg ^= FLAG_GPS;
    printf("After GPS toggle:\n");
    printStatus(deviceReg);

    // CHECK a flag
    if (deviceReg & FLAG_POWER)
        printf("Device is powered ON\n");
    return 0;
}
After power + wifi ON: Status: Power=1 WiFi=1 BT=0 GPS=0 Error=0 After wifi OFF: Status: Power=1 WiFi=0 BT=0 GPS=0 Error=0 After GPS toggle: Status: Power=1 WiFi=0 BT=0 GPS=1 Error=0 Device is powered ON

Multiple Choice Questions โ€” Chapter 1

Q1. Who developed the C programming language?

  1. Bjarne Stroustrup
  2. James Gosling
  3. Dennis Ritchie
  4. Ken Thompson
Answer: (c) Dennis Ritchie โ€” C was developed at Bell Labs in 1972.

Q2. Which of the following is NOT a valid C identifier?

  1. _count
  2. 2ndValue
  3. total_marks
  4. MAX_SIZE
Answer: (b) 2ndValue โ€” Identifiers cannot start with a digit.

Q3. What is the size of int on most 32/64-bit systems?

  1. 1 byte
  2. 2 bytes
  3. 4 bytes
  4. 8 bytes
Answer: (c) 4 bytes โ€” int typically occupies 4 bytes on modern systems.

Q4. What is the output of printf("%d", 5/2);?

  1. 2.5
  2. 2
  3. 3
  4. 2.500000
Answer: (b) 2 โ€” Integer division truncates the decimal part.

Q5. What is the value of x after: int x=5; int y=x++;?

  1. 5
  2. 6
  3. 4
  4. Undefined
Answer: (b) 6 โ€” Post-increment: y gets 5, then x becomes 6.

Q6. Which operator has the highest precedence?

  1. +
  2. *
  3. ()
  4. =
Answer: (c) () โ€” Parentheses have the highest precedence.

Q7. What is the result of 5 & 3 in binary?

  1. 7
  2. 6
  3. 1
  4. 8
Answer: (c) 1 โ€” 0101 AND 0011 = 0001 = 1.

Q8. The % operator works with:

  1. float operands only
  2. integer operands only
  3. any data type
  4. double operands only
Answer: (b) integer operands only โ€” Modulus requires integer types in C.

Q9. What does sizeof(char) always return?

  1. 0
  2. 1
  3. 2
  4. Platform dependent
Answer: (b) 1 โ€” By definition, sizeof(char) is always 1 byte.

Q10. Which of the following is a valid float constant?

  1. 3.14f
  2. 3.14.15
  3. 314f.
  4. .f
Answer: (a) 3.14f โ€” The 'f' suffix denotes a float literal.

Q11. What is !0 in C?

  1. 0
  2. 1
  3. -1
  4. Undefined
Answer: (b) 1 โ€” Logical NOT of 0 (false) gives 1 (true).

Q12. Which storage is used for const int x = 10;?

  1. x can be modified later
  2. x is stored in ROM
  3. x cannot be modified after initialization
  4. x is stored in register
Answer: (c) โ€” const makes the variable read-only after initialization.

Q13. What is the output: printf("%d", (int)3.9);?

  1. 4
  2. 3
  3. 3.9
  4. Error
Answer: (b) 3 โ€” Explicit cast to int truncates (does not round).

Q14. How many keywords does standard C (C89) have?

  1. 16
  2. 24
  3. 32
  4. 64
Answer: (c) 32 โ€” C89/C90 defines exactly 32 keywords.

Q15. What is 5 << 2?

  1. 10
  2. 20
  3. 25
  4. 2
Answer: (b) 20 โ€” Left shift by 2 = 5 ร— 2ยฒ = 5 ร— 4 = 20.

Q16. The ternary operator ?: is equivalent to:

  1. for loop
  2. while loop
  3. if-else
  4. switch
Answer: (c) if-else โ€” a ? b : c is shorthand for if-else.

Q17. In the expression a + b * c, which operation happens first?

  1. Addition
  2. Multiplication
  3. Left to right
  4. Depends on compiler
Answer: (b) Multiplication โ€” * has higher precedence than +.

Q18. What is the escape sequence for a tab character?

  1. \n
  2. \t
  3. \b
  4. \r
Answer: (b) \t โ€” \t represents a horizontal tab.

Q19. C is considered a:

  1. High-level language only
  2. Low-level language only
  3. Middle-level language
  4. Machine language
Answer: (c) Middle-level language โ€” C combines high-level constructs with low-level memory access.

Q20. What does & do in scanf("%d", &x);?

  1. Logical AND
  2. Bitwise AND
  3. Returns address of x
  4. Dereferences x
Answer: (c) Returns address of x โ€” scanf needs the memory address to store the input value.

Chapter 1 Summary

  • C was created by Dennis Ritchie at Bell Labs in 1972 for UNIX
  • C has 32 keywords and is case-sensitive
  • Primary data types: int (4B), float (4B), double (8B), char (1B)
  • Operators: Arithmetic, Unary, Relational, Logical, Assignment, Ternary, Bitwise
  • ++x (pre) increments before use; x++ (post) uses then increments
  • Bitwise operators work on individual bits โ€” essential for embedded systems
  • Integer division truncates: 5/2 = 2, use casting for float result
  • Operator precedence determines evaluation order; use parentheses when in doubt
  • Type casting: implicit (automatic widening) and explicit (type)