PadhaikoAll subjects

Overview of C Programming

Computer Programming (ENCT 101)

Open in the Padhaiko app

2.1 Introduction to C programming

C is a general-purpose, procedural, structured, and middle-level programming language. It combines the expressive control structures and portability of high-level languages (functions, loops, structured data types) with low-level hardware capabilities (direct memory addressing via pointers, bitwise manipulation, and predictable byte-level layout).

Because C provides a thin abstraction over machine instructions without hidden runtime overhead, it remains the foundational language for operating systems, embedded firmware, device drivers, compilers, and high-performance libraries.


2.2 History and importance of C

C evolved through a clear lineage of systems languages at Bell Laboratories:

Evolutionary Timeline of the C Language
YearLanguage / StandardCreator / BodyKey Milestone
1960ALGOL 60International CommitteeIntroduced block structure and structured programming concepts
1967BCPLMartin RichardsTypeless systems language used for writing compilers
1970BKen ThompsonStripped-down successor to BCPL for early UNIX on PDP-7
1972Traditional CDennis Ritchie (Bell Labs)Added data types (char, int, float) and structures to rewrite UNIX in C on PDP-11
1978K&R CBrian Kernighan & Dennis RitchieThe C Programming Language served as the informal standard
1989 / 1990ANSI C / ISO C (C89 / C90)ANSI X3J11 / ISOFirst formal portable standard introducing function prototypes and void
1999 / 2011 / 2017C99 / C11 / C17ISO/IEC JTC1/SC22/WG14Added // comments, long long int, <stdbool.h>, multithreading, and safety fixes

Why C Remains Important:

  1. System-Level Power: Operating system kernels (Linux, Windows core subsystems, macOS Darwin) and embedded microcontrollers are written predominantly in C.
  2. Speed and Efficiency: Compiled directly to native machine code with minimal runtime footprint.
  3. Portability: Standard C code compiles with few or no modifications across diverse hardware architectures.
  4. Rich Standard Library and Foundation: Forms the syntactic and conceptual ancestor of C++, Java, C#, JavaScript, and PHP.

2.3 C headers and library functions

Rather than bloating the core language with built-in I/O or math keywords, C delegates these capabilities to library functions organized by header files (.h). A header file contains function declarations (prototypes), macro constants, and type definitions so the compiler can verify argument and return types before the linker attaches the compiled library code.

Essential Standard C Header Files
Header FilePurposeCommon Library Functions / Macros
<stdio.h>Standard Input/Outputprintf(), scanf(), getchar(), putchar(), fopen(), fclose(), EOF
<math.h>Mathematical Functionssqrt(), pow(), sin(), cos(), fabs(), ceil(), floor()
<string.h>String & Memory Operationsstrlen(), strcpy(), strcat(), strcmp(), memcpy()
<stdlib.h>General Utilities & Dynamic Memorymalloc(), calloc(), free(), exit(), atoi(), rand(), abs()
<ctype.h>Character Testing & Conversionisalpha(), isdigit(), isspace(), toupper(), tolower()
<limits.h>Integer Type LimitsINT_MAX, INT_MIN, CHAR_BIT, UINT_MAX

2.4 Basic structure of a C program

Every standalone C program follows a standard structural layout consisting of six well-defined sections:

Six Structural Sections of a C Program
SectionRoleMandatory?
1. Documentation SectionComments (/* ... */ or //) describing author, date, and purposeOptional (strongly recommended)
2. Link Section#include directives bringing in header declarationsAlmost always needed (e.g., <stdio.h>)
3. Definition Section#define symbolic constants and macrosOptional
4. Global Declaration SectionGlobal variables and user-defined function prototypesOptional
5. main() Function SectionEntry point of program execution (int main(void)); contains declaration and executable partsMandatory (exactly one main per program)
6. Subprogram SectionUser-defined function definitions called from main() or other functionsOptional
Complete C Program Illustrating All Six SectionsC
/* Program: Calculate area and circumference of a circle */
#include <stdio.h>                      /* Link section */
#define PI 3.14159                      /* Definition section */

double calc_area(double r);             /* Global function prototype */

int main(void) {                        /* main() entry point */
    double radius = 5.0;                /* Local variable declaration */
    double area = calc_area(radius);    /* Executable statement */
    printf("Area = %.2f\n", area);
    return 0;                           /* Exit status 0 = success */
}

double calc_area(double r) {            /* Subprogram definition */
    return PI * r * r;
}

2.5 Preprocessor directives

The C Preprocessor (cpp) runs automatically before actual compilation. Every preprocessor directive begins with # at the start of a line and does not end with a semicolon (;).

Definition

Common C Preprocessor Directives

  1. File Inclusion (#include): Inserts the full text of a header file into the source file before compilation.
    • #include <stdio.h> searches standard system include directories.
    • #include "myheader.h" searches the current project directory first, then system directories.
  2. Macro Substitution (#define and #undef):
    • Object-like macro: #define MAX 100 replaces every occurrence of token MAX with 100.
    • Function-like macro: #define SQR(x) ((x) * (x)) substitutes inline expressions textually. Parentheses around parameters and the entire macro prevent operator-precedence surprises.
  3. Conditional Compilation (#ifdef, #ifndef, #if, #else, #endif): Includes or skips blocks of code at compile time (used heavily in header guards and cross-platform builds).

2.6 Tokens in C (Character set, keywords and identifiers)

A token is the smallest individual lexical unit recognized by the C compiler. C source code is built from characters in the C Character Set:

Six Categories of C Tokens
Token TypeMeaningExamples
KeywordsReserved words with fixed meaning in C (32 in ANSI C89)int, float, if, else, for, while, return, struct, sizeof
IdentifiersUser-defined names for variables, functions, arrays, and structssum, student_age, _count, calcArea
ConstantsFixed literal values that do not change during execution42, 3.14f, 'A', "Institute of Engineering"
String LiteralsSequence of characters enclosed in double quotes ending with '\0'"Hello", "ENCT 101"
OperatorsSymbols specifying arithmetic, logical, or bitwise actions+, -, *, /, &&, ==, ++
Punctuators / SeparatorsStructural delimiters;, ,, (, ), {, }

Rules for Valid C Identifiers:

  1. Must begin with a letter (A–Z, a–z) or an underscore (_).
  2. Subsequent characters may be letters, digits (0–9), or underscores (_).
  3. Cannot be a reserved C keyword (e.g., int, float, switch).
  4. Cannot contain spaces, hyphens (-), or special symbols (@, #, %).
  5. Identifiers are case-sensitive (total, Total, and TOTAL are three distinct names).

2.7 Type casting (Implicit and explicit)

Type casting (type conversion) converts a value from one data type to another so operations match compatible representations.

AspectImplicit Type Conversion (Type Promotion)Explicit Type Casting
Who Performs ItPerformed automatically by the C compilerWritten explicitly by the programmer using (type) expression
DirectionUsually widening (lower rank promoted to higher rank along char -> int -> long -> float -> double) to avoid data lossCan widen or narrow intentionally (e.g., (int) 3.9 truncates fractional part to 3)
Syntaxdouble d = 5 + 2.5; (5 promoted to 5.0)double avg = (double) sum / count;
Common PitfallInteger division 5 / 2 yields 2, even if assigned to a float (float f = 5 / 2; stores 2.0)Casting after division (double)(5 / 2) is too late; it casts 2 to 2.0

Usual Arithmetic Conversion Hierarchy: When a binary operator mixes types, the smaller type is promoted upward before the operation: short / char -> int -> unsigned int -> long -> float -> double -> long double.


2.8 Data types, variables and constants

A variable is a named storage location in memory whose value can change during program execution, while a constant is an unmodifiable value. Every variable in C must be declared with a data type before use so the compiler knows how many bytes to allocate and how to interpret the stored bits.

Primary C Data Types (Typical 32/64-bit LP64 / LLP64 Desktop Architecture)
Data TypeSize (Bytes)Format SpecifierTypical Value RangePurpose
char1%c-128 to 127 (signed) or 0 to 255 (unsigned)Single ASCII character or small byte
short int2%hd-32,768 to 32,767Small integers
int4%d-2,147,483,648 to 2,147,483,647Standard signed integers
unsigned int4%u0 to 4,294,967,295Non-negative integers
long long int8%lld-9.22e18 to 9.22e18Very large integers
float4%f~1.2e-38 to 3.4e38 (6–7 digits precision)Single-precision floating-point
double8%lf~2.3e-308 to 1.7e308 (15 digits precision)Double-precision floating-point
void——No valuesEmpty type (functions returning nothing, generic pointers)

Declaring Variables and Constants:


2.9 Compiler and IDE for C programming

Writing and running C code requires a compiler (to translate source files into executables) and optionally an IDE (Integrated Development Environment) that combines an editor, compiler invocation, and debugger.

Popular C Compilers and IDEs
ToolCategoryPlatformKey Features
GCC (gcc)CompilerLinux, macOS, Windows (MinGW)Open-source GNU Compiler Collection; standard CLI compilation (gcc prog.c -o prog -Wall)
Clang (clang)CompilerLinux, macOS, WindowsFast compilation and clear diagnostic messages
MSVC (cl)CompilerWindowsMicrosoft Visual C++ toolchain
VS CodeLightweight Editor / IDECross-platformSyntax highlighting, integrated terminal, debugging with GDB/LLDB
Code::Blocks / Dev-C++Beginner C/C++ IDEWindows / LinuxPre-packaged GUI with bundled MinGW GCC compiler
Turbo C / C++Legacy 16-bit IDEDOS / DOSBoxHistorical textbook tool (non-standard <conio.h>, 16-bit int); avoid for modern C11/C17 work

Worked Examples

Example 1

1 (6 marks)

Predict the exact output of the following C program that demonstrates integer division, implicit promotion, and explicit type casting:

Implicit vs Explicit Casting ExampleC
#include <stdio.h>

int main(void) {
    int a = 17, b = 4;
    double r1 = (a + b) / 2;
    double r2 = (double)(a + b) / 2;
    double r3 = (double)((a + b) / 2);
    printf("r1=%.2f r2=%.2f r3=%.2f\n", r1, r2, r3);
    return 0;
}

Evaluating r1 = (a + b) / 2;: Both (a + b) = 21 and 2 are of type int. C performs integer division, discarding the remainder: 21 / 2 evaluates to integer 10. Only during assignment to double r1 is 10 implicitly converted to 10.00.

Evaluating r2 = (double)(a + b) / 2;: (a + b) evaluates to 21, which is explicitly cast to 21.0 (double). Because one operand of / is now double, C implicitly promotes 2 to 2.0, producing 21.0 / 2.0 = 10.50.

Evaluating r3 = (double)((a + b) / 2);: The inner expression (a + b) / 2 executes first as integer division (21 / 2 = 10), and only then is 10 cast to 10.00.

Answer:

Output:

Program OutputText
r1=10.00 r2=10.50 r3=10.00
Example 2

2 (5 marks)

Classify each of the following candidate identifiers in C as valid or invalid. For every invalid identifier, state the exact rule violated: totalMarks, 2nd_value, _buffer, float, student-id, MAX_SIZE, roll no, int_1.

Checking Each Candidate Against C Identifier Rules:

  1. totalMarks: Starts with a letter and uses only letters -> Valid.
  2. 2nd_value: Begins with digit 2 -> Invalid (identifiers cannot start with a digit).
  3. _buffer: Begins with underscore _ followed by letters -> Valid.
  4. float: Matches a reserved C keyword -> Invalid (keywords cannot be used as identifiers).
  5. student-id: Contains a hyphen - (subtraction operator) -> Invalid (only letters, digits, and _ are allowed).
  6. MAX_SIZE: Letters and underscore -> Valid.
  7. roll no: Contains a whitespace space -> Invalid (whitespace is a token separator, not permitted inside an identifier).
  8. int_1: Starts with a letter; int is only a prefix, not the standalone keyword int -> Valid.
Answer:
  • Valid: totalMarks, _buffer, MAX_SIZE, int_1
  • Invalid: 2nd_value (starts with digit), float (reserved keyword), student-id (contains -), roll no (contains space).
Example 3

3 (6 marks)

Explain why parenthesizing #define macro parameters matters by tracing the output of this program:

Macro Precedence PitfallC
#include <stdio.h>
#define BAD_MUL(a, b) a * b
#define GOOD_MUL(a, b) ((a) * (b))

int main(void) {
    int x = BAD_MUL(3 + 1, 10 + 2);
    int y = GOOD_MUL(3 + 1, 10 + 2);
    printf("x=%d y=%d\n", x, y);
    return 0;
}

Expanding BAD_MUL(3 + 1, 10 + 2): The preprocessor performs raw text replacement before compilation: int x = 3 + 1 * 10 + 2; Because * has higher precedence than +, this evaluates as 3 + (1 * 10) + 2 = 3 + 10 + 2 = 15 (note: not (3 + 1) * (10 + 2)!).

Expanding GOOD_MUL(3 + 1, 10 + 2): With parentheses around every parameter and the macro body: int y = ((3 + 1) * (10 + 2)); This evaluates as 4 * 12 = 48.

Answer:

Output: x=15 y=48. Always wrap macro arguments and the macro result in parentheses because #define performs textual substitution before operator precedence rules are applied.


Exercises

Exercises — Overview of C Programming

Question 1

Why is C called a "middle-level" structured programming language? Mention four key historical milestones in its evolution from ALGOL/BCPL to ANSI C.

Why C is Middle-Level: C bridges high-level structured programming (portable control flow, functions, typed variables, standard libraries) and low-level machine programming (pointers for direct memory access, bitwise operations, compact machine code).

Four Historical Milestones:

  1. 1967 (BCPL by Martin Richards): Typeless systems language influencing B.
  2. 1970 (B by Ken Thompson): Early UNIX systems language at Bell Labs.
  3. 1972 (C by Dennis Ritchie): Added data types and structures to rewrite the UNIX kernel.
  4. 1989 (ANSI C / C89): Standardized the language formally across compilers and platforms.
Answer:

C is called middle-level because it pairs high-level structured abstractions with low-level pointer and bit-level control. Key milestones: BCPL (1967) -> B (1970) -> Dennis Ritchie's typed C (1972) -> ANSI C standard (1989).

Question 2

Describe the six basic sections of a C program and explain the specific roles of <stdio.h> and return 0; inside main().

Six Sections: Documentation (comments), Link (#include), Definition (#define), Global Declaration (global variables and function prototypes), main() Function (declarations and executable statements), and Subprogram Section (user-defined functions).

Roles of <stdio.h> and return 0;:

  • #include <stdio.h> supplies prototypes for standard I/O functions such as printf() and scanf() so the compiler checks argument types and return values.
  • return 0; in int main(void) returns exit status 0 to the operating system, signaling normal error-free termination.
Answer:

A C program comprises Documentation, Link, Definition, Global Declaration, main(), and Subprogram sections. <stdio.h> provides declarations for standard I/O functions (printf, scanf), while return 0; reports successful program termination to the OS.

Question 3

What is a token in C? List all six types of C tokens with two examples of each, and state the rules for forming a valid identifier.

Definition and Six Token Categories: A token is the smallest meaningful unit of a C program recognized by the lexical analyzer:

  1. Keywords: int, return
  2. Identifiers: total, calc_sum
  3. Constants: 25, 'A'
  4. String Literals: "Nepal", "123"
  5. Operators: +, &&
  6. Punctuators: ;, {

Rules for Valid Identifiers:

  • Start with an alphabet (A–Z, a–z) or underscore (_).
  • Contain only letters, digits (0–9), and underscores.
  • Cannot be a C keyword; no spaces or punctuation; case-sensitive.
Answer:

Tokens are the six atomic building blocks of C code (keywords, identifiers, constants, string literals, operators, punctuators). Valid identifiers start with a letter or _, contain only letters/digits/_, are case-sensitive, and cannot match keywords.

Question 4

Explain the difference between implicit type conversion and explicit type casting. Given int a = 7, b = 2;, what values are stored in float x = a / b; and float y = (float)a / b;?

Implicit vs. Explicit Conversion:

  • Implicit conversion is performed automatically by the compiler when mixed types appear in an expression (promoting smaller types to larger types).
  • Explicit casting uses the (type) operator written by the programmer to force conversion at a chosen point.

Evaluating x and y:

  • In float x = a / b;, both a and b are int, so integer division 7 / 2 gives 3, which is then implicitly promoted to 3.0 when stored in x.
  • In float y = (float)a / b;, (float)a converts 7 to 7.0f; b is implicitly promoted to 2.0f, giving 7.0 / 2.0 = 3.5.
Answer:

Implicit conversion is automatic type promotion by the compiler, whereas explicit casting uses (type) expr. For a = 7, b = 2: x stores 3.0 (integer division before assignment) and y stores 3.5 (float division after explicit cast).

Question 5

Compare #define symbolic constants with const variables in C across at least four criteria (processing stage, type safety, memory usage, and scope).

Comparison Criteria:

  1. Processing Stage: #define is handled textually by the preprocessor before compilation; const is checked by the compiler during compilation.
  2. Type Safety: #define has no data type and no compiler type checking; const requires an explicit type (const int N = 10;).
  3. Memory & Debugging: #define substitutes literals directly (no memory address, invisible to debuggers); const variables occupy typed storage (unless optimized out) and have symbol names in debuggers.
  4. Scope Rules: #define applies globally from its line to the end of the file (unless #undefined); const obeys normal C block/file scope rules.
Answer:

#define performs untyped preprocessor text substitution globally without allocating a typed variable, whereas const defines a type-checked, scoped read-only variable handled by the compiler.

← Introduction to Computer ProgrammingOperators and Expressions →