0% found this document useful (0 votes)
0 views21 pages

C Programming Compressed Notes

This document provides compressed and syllabus-mapped notes for BCA Semester 1, specifically focusing on the C programming portion of the course. It includes a detailed breakdown of topics covered in the syllabus, along with additional content that was added to fill gaps. The notes are structured to follow the official syllabus order and include practical examples and explanations relevant to the Turbo C++ lab environment.

Uploaded by

theracerl875
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views21 pages

C Programming Compressed Notes

This document provides compressed and syllabus-mapped notes for BCA Semester 1, specifically focusing on the C programming portion of the course. It includes a detailed breakdown of topics covered in the syllabus, along with additional content that was added to fill gaps. The notes are structured to follow the official syllabus order and include practical examples and explanations relevant to the Turbo C++ lab environment.

Uploaded by

theracerl875
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

C PROGRAMMING

Compressed & Syllabus-Mapped Notes

Prepared for: BCA Semester 1


Mapped against: BBD University — "Fundamentals of Computer & Programming in C" (BCACSN11102)
Modules 3 & 4, and the Programming in C Lab (BCACSN11151)

Source: compressed & rewritten from a 76-page reference notes PDF, cross-checked line-by-line against the
official syllabus
How This Document Was Built
This document is not a copy of your reference PDF. It has been rewritten from scratch, topic by topic,
and reorganised to follow the exact order of your official BBD syllabus for the C-programming portion
of BCACSN11102 — not the order the reference notes happened to use.
Three things were done to build it:
● 1. Every page of your 76-page reference notes PDF was read and its topic list extracted.
● 2. The official BBD syllabus document for this paper was located and its Module 3 and Module
4 content (the actual C-language units) was extracted word for word.
● 3. The two were matched line by line. Anything the syllabus requires that your notes did not
cover has been written fresh and added here, clearly marked. Anything your notes covered
that is outside this semester's syllabus has been moved to an appendix and marked optional.

Scope note
This paper (BCACSN11102) also has two earlier modules on computer fundamentals and networking
(CPU architecture, OS, OSI model, etc). Those are a separate topic area and were not in your source
notes either, so they are not included here. This document covers only the C-language part of the
syllabus — Modules 3 and 4, plus the C Lab.

Wherever your college's Turbo C++ lab environment behaves differently from standard/modern C, a
boxed note like the one above flags it — that distinction matters for your practical exam specifically.
Syllabus Match & Gap Analysis
This table is the actual audit: every topic line from the official syllabus, checked against whether your
reference notes covered it.
Syllabus Topic Status Note
Program structure, first program, compiling Matched ✓ Covered
& executing
Comments Matched ✓ Covered
Data types, tokens, keywords, identifiers, Matched ✓ Covered
variables, constants, literals
I/O statements (printf, scanf) Matched ✓ Covered
Operators, precedence & associativity Matched ✓ Covered
Type conversion & type casting Matched ✓ Covered
if, if-else, nested if, if-else ladder, switch- Matched ✓ Covered
case
for, while, do-while loops Matched ✓ Covered
break, continue Matched ✓ Covered
goto statement Added ✗ Missing from source — written fresh
in Unit 1
Arrays — 1D and 2D Matched ✓ Covered
Address calculation of an array element Added ✗ Missing from source — written fresh
in Unit 2
Insertion & deletion in an array Added ✗ Missing from source — written fresh
in Unit 2
Functions, actual/formal arguments, call by Matched ✓ Covered
value/reference
Passing arrays as parameters Matched ✓ Covered
Storage classes (auto, extern, static, Added ✗ Missing from source — written fresh
register) in Unit 2
Pointers — declaration, arithmetic, with Matched ✓ Covered
arrays/strings, array of pointers, function
arguments
Structure & Union Matched ✓ Covered
Enumeration Added ✗ Missing from source — written fresh
in Unit 2

Extra topics in your source notes that are outside this semester's syllabus
● Recursion — not named in the syllabus text, but examiners commonly fold it into the
"Functions" topic. Kept in Unit 2, marked as bonus.
● File Handling (fopen, fscanf, fprintf, etc.) — not part of Semester 1 for this paper. Moved to
Appendix A as optional reading.
● Dynamic Memory Allocation (malloc, calloc, free, realloc) — not part of Semester 1 for this
paper. Moved to Appendix A as optional reading.
UNIT 1 — C Language Basics (Syllabus Module 3)
1.1 What C Is, and How a Program Runs
C is a general-purpose programming language — a way of writing instructions that a computer can
eventually execute. A computer's processor only understands binary machine code, so a translation
step is needed:
● You write source code in a plain-text file with a .c extension.
● A compiler translates that .c file into an executable file (.exe on Windows) — pure machine
code.
● The operating system runs that .exe file.
This is why Turbo C and every modern IDE show "Compile" and "Run" as two separate steps —
compiling and executing are not the same action.

1.2 Structure of a C Program


Every C program follows the same skeleton:

#include <stdio.h> // preprocessor directive — brings in


printf/scanf

int main() // execution always starts here


{
// statements go here, each ending in a semicolon
return 0; // tells the OS the program finished successfully
}
Rules that apply to every C program:
● Execution always starts from main() — no matter where other functions are placed in the file.
● Every statement ends with a semicolon (;).
● C is case-sensitive — Sum and sum are different identifiers.
● Statements execute in the order they are written, top to bottom.

Turbo C++ Lab Note


Your college lab uses Turbo C++, which follows the older C89 rule: all variable declarations in a block
must appear before any executable statement. In modern compilers (GCC) this restriction is relaxed. If
your program shows "Declaration is not allowed here" or "Multiple declaration", the fix is almost
always to move every int/float/char declaration to the very top of that { } block, before any other line.

1.3 The #include Directive and Header Files


C's core language is deliberately small — it has no built-in command to print text. Functions like printf()
and scanf() are pre-written and grouped into library files called headers. #include<stdio.h> tells the
compiler "make the declarations in this file available here", so the compiler recognises printf and
scanf.
● <stdio.h> — Standard Input/Output header: printf(), scanf().
● <conio.h> — Console I/O header: clrscr(), getch(). This is Turbo-C-specific and non-standard —
it will not exist if you ever compile the same code on GCC or any modern compiler.
1.4 Comments
Comments are notes for humans reading the code; the compiler ignores them entirely.

// single-line comment

/* multi-line
comment */

1.5 Data Types


A data type tells the compiler how much memory to reserve for a variable and what kind of value it
can legally hold.
● int — whole numbers (e.g. 10, -3)
● float — decimal numbers (e.g. 4.7)
● char — a single character, written in single quotes (e.g. 'A')
A value is silently changed ("demoted") if you assign it to an incompatible type:

int a = 3.5; // a becomes 3 — the decimal part is dropped (demotion)


float b = 8; // b becomes 8.0 — promoted to float

1.6 Tokens — Keywords, Identifiers, Variables, Constants, Literals


Keywords
Keywords are reserved words whose meaning is fixed by the C language — you cannot use them as
variable names. There are 32 keywords in standard C, including:
auto, break, case, char, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int,
long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void,
volatile, while.

Identifiers & Variables


An identifier is a name you give to a variable, function, or other entity. A variable is a named container
that stores a value which can change during program execution. Naming rules:
● The first character must be a letter or an underscore (_).
● No spaces, commas, or special symbols other than the underscore.
● Names are case-sensitive.
● Use meaningful names — it makes programs easier to read and debug.

Constants and Literals


A constant is an entity whose value cannot change once set. A literal is the actual fixed value written in
code. There are three primary types of constants:
● Integer constant — e.g. -1, 6, 19
● Real (floating-point) constant — e.g. -322.1, 2.5, 7.0
● Character constant — e.g. 'a', '5', enclosed in single quotes

1.7 Input/Output Statements


printf() sends output to the screen; scanf() reads input typed by the user. Both need a format specifier
that matches the data type: %d for int, %f for float, %c for char.
int i;
printf("Enter a number: ");
scanf("%d", &i); // & is the "address of" operator — required here
printf("You entered %d", i);
The & before a variable in scanf means "store the typed value at this variable's memory address" —
omitting it is one of the most common beginner bugs.

1.8 Operators, Precedence & Associativity


Types of operators
● Arithmetic: + - * / % (% is the modulus/remainder operator, and only works on integers)
● Relational: == != > < >= <= (== checks equality; = is assignment — mixing these up is a
classic bug)
● Logical: && (AND) || (OR) ! (NOT)
● Assignment: = and compound forms +=, -=, *=, /=, %=
● Increment / decrement: ++ --
● Conditional (ternary): condition ? expr_if_true : expr_if_false

Precedence and associativity


Simple left-to-right BODMAS-style math does not automatically apply in C — the answer to an
expression like 3 * x - 8 * y depends on operator precedence (which operator binds tighter) and
associativity (which direction ties are resolved).

Priority Operators
1 (highest) * / %
2 + -
3 < > <= >=
4 == !=
5 &&
6 ||
7 (lowest) =
Operators of equal priority are evaluated left to right for *, / (e.g. x*y/z means (x*y)/z).

1.9 Type Conversion & Type Casting


Type conversion happens automatically when an arithmetic operation mixes types:
● int and int → int
● int and float → float
● float and float → float
This matters most with division:

5 / 2 // gives 2 — both operands are int, so the result is int


(truncated)
5.0 / 2 // gives 2.5 — one operand is float, so the result is promoted
to float
Type casting is when you force a conversion explicitly, e.g. (float) a — useful when you want a float-
style division result from two int variables: (float)a / b.
1.10 Decision Control Statements
if / if-else
if (a > 18) {
printf("You can drive\n");
}
else {
printf("Not yet\n");
}
The else block is optional. The condition can be any valid expression — in C, any non-zero value is
treated as true, and 0 is treated as false.

Nested if and if-else ladder


An if inside another if is a nested if. A chain of else if is called an if-else-if ladder — it reduces the deep
indentation you'd get from nesting many plain if statements. The final else (if present) runs only when
every condition above it has failed.

if (marks >= 90) printf("Grade A");


else if (marks >= 80) printf("Grade B");
else if (marks >= 70) printf("Grade C");
else printf("Grade F");

switch-case
switch is used to choose between several fixed alternatives for one variable.

switch (integer_expression) {
case c1:
// code
break;
case c2:
// code
break;
default:
// code
}
● c1, c2, ... must be constants. Any valid C code can go inside a case.
● Without break, execution "falls through" into the next case — this is a frequent source of bugs.
● Cases don't have to be written in ascending order.
● char values are allowed in switch because they are automatically evaluated as their integer
(ASCII) value.

1.11 Loops
while loop
Checks the condition first, then runs the body — so the body may run zero times.

int i = 0;
while (i < 10) {
printf("%d", i);
i++;
}
If the condition never becomes false, this is called an infinite loop.
do-while loop
Runs the body first, then checks the condition — so the body always runs at least once.

int i = 1;
do {
printf("%d", i);
i++;
} while (i <= 4);

for loop
Bundles initialisation, condition, and increment/decrement into one line — the standard choice when
the number of iterations is known in advance.

for (i = 0; i < 3; i++) {


printf("%d\n", i);
}

1.12 Jump Statements: break, continue, goto


break
Immediately exits the loop (or switch) it is inside, regardless of whether the loop's condition is still
true.

continue
Skips the rest of the current iteration and jumps straight to the loop's next test/increment step — it
does not exit the loop.

for (i = 0; i < 10; i++) {


if (i == 5)
break; // stops the loop entirely at i == 5
printf("%d\n", i);
}
// prints 0 1 2 3 4

goto
[ADDED — required by BBD syllabus, not present in your source notes]
goto transfers control directly to a labelled line elsewhere in the same function. A label is a name
followed by a colon.

int i = 0;
start: // this is a label
if (i < 5) {
printf("%d\n", i);
i++;
goto start; // jumps back up to the label
}
goto is on your syllabus alongside break and continue, but is rarely used in real code — it tends to
make programs hard to follow ("spaghetti code"). Know the syntax for your exam; prefer loops in
practice.

1.13 Unit 1 Practice Questions


● 1. What will int a = 5 / 2; store, and why?
● 2. Write a program that reads a character and, using if-else, tells whether it is a vowel or a
consonant.
● 3. Write a program to check whether a given year is a leap year.
● 4. Rewrite a chain of 4 else-if conditions as a switch-case wherever possible, and explain when
switch cannot replace if-else.
● 5. Write a program to print a multiplication table for a number entered by the user, using a for
loop.
● 6. Explain the difference in output between i++ and ++i inside a printf statement.
● 7. Write a program using goto that prints numbers 1 to 5 without using any loop keyword
(for/while/do).
● 8. What is the output of: int a = 3.9; printf("%d", a); — explain why.
UNIT 2 — Arrays, Functions, Pointers, Structures (Syllabus Module 4)
2.1 Arrays
An array is a collection of elements of the same type, stored under one variable name — think of it as
several labelled boxes in a row instead of one box.

int marks[5]; // an integer array that can hold 5 values


char name[20]; // a character array (string)
float percentile[10]; // a float array

marks[0] = 33; // assign to the first element


marks[1] = 12;
Array indexing always starts at 0 — an array of size 5 has valid indices 0 to 4, never 5.
Arrays can also be initialised at the point of declaration:

int caps[3] = {9, 8, 8};

Address calculation of an array element


[ADDED — required by BBD syllabus, not present in your source notes]
Array elements sit in contiguous memory — one right after another. If an array starts at a base address
and each element takes size bytes, the address of any element at position index is calculated as:

Address of arr[index] = Base Address + (index × size of one element)


Example: for int arr[3] = {1, 2, 3}, where int is 4 bytes and the array starts at address 62302:
● arr[0] is at 62302
● arr[1] is at 62302 + (1 × 4) = 62306
● arr[2] is at 62302 + (2 × 4) = 62310
This is exactly why array indexing is zero-based — the formula gives the base address itself when index
= 0.

Insertion and deletion in an array


[ADDED — required by BBD syllabus, not present in your source notes]
Unlike a linked list, an array has no built-in way to "make room" or "close a gap" — insertion and
deletion are done manually by shifting elements.
To insert a value at a given position: shift every element from that position onward one slot to the
right (starting from the last element and moving backward, so you don't overwrite anything), then
place the new value in the freed slot. The array must have unused capacity for this to work.
To delete a value at a given position: shift every element after that position one slot to the left
(starting from the deleted position and moving forward), which overwrites the deleted value and
closes the gap. The logical size of the array is then treated as one less.

// Deleting the element at index 'pos' from an array of size n


for (i = pos; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
n = n - 1; // one fewer valid element now
Two-dimensional arrays
A 2-D array is an array of arrays — commonly used to represent a grid or table.

int arr[3][2] = { {1, 4}, {7, 9}, {11, 22} };


// arr[0][0] is 1, arr[0][1] is 4, arr[1][0] is 7, and so on
Like 1-D arrays, a 2-D array is stored in one continuous block of memory, row after row.

2.2 Functions
A function is a named, reusable block of code that performs one task. Breaking a program into
functions makes large programs manageable and avoids rewriting the same logic repeatedly.

#include <stdio.h>

void display(); // function prototype (declaration)

int main() {
display(); // function call
return 0;
}

void display() { // function definition


printf("Hi, I am display");
}
● Prototype — tells the compiler the function's name, return type, and parameters before it's
used.
● Call — the point where the function actually executes; main() pauses until the called function
finishes.
● Definition — the actual body of instructions the function runs.

Arguments and parameters


Parameters are the placeholder variables listed in the function's definition. Arguments are the actual
values passed in when the function is called.

int sum(int a, int b) { // a and b are parameters


int c;
c = a + b;
return c;
}

int d = sum(2, 3); // 2 and 3 are arguments; d becomes 5


A function can return only one value at a time.

Call by value vs. call by reference


These are the two ways C passes arguments into a function, and the syllabus treats them as a core
topic.
● Call by value: a copy of the argument's value is passed. Changes made inside the function do
not affect the original variable in the caller.
● Call by reference: the address of the variable is passed (using pointers). The function can then
modify the original variable directly.
// Call by value — b in main() is unaffected
void change(int a) { a = 77; }
// Call by reference — b in main() actually changes
void changeRef(int *a) { *a = 77; }
A classic example of call by reference is a swap function:

void swap(int *x, int *y) {


int temp = *x;
*x = *y;
*y = temp;
}
// swap(&a, &b) will genuinely exchange a and b in the caller

Passing arrays to functions


Arrays are passed to functions differently from ordinary variables — an array argument is
automatically passed as a pointer to its first element, so the function can modify the original array
directly (arrays behave like call by reference by default).

void printArray(int arr[], int n); // or: void printArray(int *arr, int
n);

Storage classes
[ADDED — required by BBD syllabus, not present in your source notes]
A storage class controls two things about a variable: where it is stored, and how long it lives (its scope
and lifetime). C has four storage classes:
● auto — the default for any variable declared inside a function. Local scope; created when the
block starts and destroyed when it ends.
● extern — declares a variable that is defined elsewhere (often another file), letting multiple files
share one global variable.
● static — a local variable declared static retains its value between function calls instead of
resetting each time; a static global variable is limited to the file it's declared in.
● register — a hint to the compiler to store the variable in a CPU register instead of RAM for
faster access (modern compilers mostly decide this automatically regardless of the hint).
void counter() {
static int count = 0; // keeps its value across every call
count++;
printf("%d\n", count);
}
// calling counter() three times prints 1, 2, 3 — not 1, 1, 1

2.3 Recursion (bonus — commonly examined alongside Functions)


A function that calls itself is a recursive function. Recursion is a natural way to express problems that
can be defined in terms of a smaller version of themselves — factorial is the standard example:

factorial(n) = n × factorial(n - 1)

int factorial(int x) {
int f;
if (x == 0 || x == 1)
return 1; // base condition — stops the recursion
else
f = x * factorial(x - 1);
return f;
}
Every recursive function needs a base condition — the point where it stops calling itself. Without one,
the function keeps calling itself indefinitely and eventually crashes with a memory error (stack
overflow).

2.4 Pointers
A pointer is a variable that stores the memory address of another variable, rather than an ordinary
value.

int i = 8;
int *j; // declares j as a pointer to an int
j = &i; // j now stores the address of i
●& (address-of operator) — gives you the memory address of a variable.
●* (value-at / dereference operator) — gives you the value stored at the address a pointer
holds.
The format specifier for printing a pointer's address is %u (or %p on modern compilers).

Pointer arithmetic
A pointer can be incremented to move to the next memory location of its own type — the compiler
automatically advances it by the correct number of bytes for that type (e.g. 4 for int), not by 1 byte.

int arr[] = {7, 9, 2, 8, 1};


int *ptr = arr; // ptr now points to arr[0]
ptr++; // ptr now points to arr[1]
printf("%d", *ptr); // prints 9

Pointers and arrays


An array name, used by itself, decays into a pointer to its first element — this is why arrays and
pointers are closely linked, and why arrays passed to functions behave like pointers.

Pointers and character strings


A string can be declared using a character array or a character pointer:

char s1[] = "HARRY"; // a character array


char *ptr = "HARRY"; // a character pointer
A key difference: a string declared as a fixed array (char s[] = "Harry") cannot later be reassigned to a
completely different string, but a string declared via a pointer (char *ptr) can simply be pointed at a
new string later (ptr = "Rohan";).

Array of pointers
Just as you can have an array of integers, you can have an array where every element is itself a pointer
— useful for holding a list of strings, since each string is really a pointer to its first character.

Pointer to a pointer
A pointer can itself be pointed to by another pointer, declared with two asterisks:

int i = 72;
int *j = &i; // j points to i
int **k = &j; // k points to j (a pointer to a pointer)

Pointers as function arguments


Passing a pointer into a function is exactly how call by reference is implemented in C — covered above
under Functions.

2.5 Strings
A string in C is really a 1-D character array terminated by a special null character, written '\0'. This
character is not visible when printed, but marks where the string ends in memory.

char s[] = {'H','A','R','R','Y','\0'}; // manual form


char s[] = "HARRY"; // shortcut — the compiler adds
'\0' automatically

Reading and printing strings


● scanf("%s", str) — reads a string, but stops at the first space (cannot read multi-word input).
● gets(str) — can read a full line including spaces (deprecated in modern C for safety reasons,
but still taught and used in Turbo C labs).
● printf("%s", str) or puts(str) — print an entire string at once.

Common string library functions (<string.h>)


● strlen(s) — returns the number of characters in s, excluding '\0'.
● strcpy(dest, src) — copies src into dest. dest must have enough space.
● strcat(s1, s2) — appends (concatenates) s2 onto the end of s1.
● strcmp(s1, s2) — compares two strings; returns 0 if equal, a negative value if s1 comes before
s2 alphabetically, and positive otherwise.

2.6 Structures, Union & Enumeration


Arrays hold multiple values of the same type. A structure holds multiple values of different types,
grouped under one name — useful when different pieces of related data belong together, like an
employee's code, salary, and name.

struct employee {
int code;
float salary;
char name[10];
}; // the semicolon here is required

struct employee e1; // declaring a structure variable


[Link] = 100;
[Link] = 71.22;
strcpy([Link], "Harry");
Structures can also be initialised directly, used in arrays (an array of structures), and accessed through
a pointer using the arrow operator:

struct employee *ptr = &e1;


printf("%d", ptr->code); // arrow operator — same as (*ptr).code
A structure can also be passed to a function just like any other data type.
Union
A union looks similar to a structure syntactically (struct → union in the declaration), but all its
members share the same block of memory instead of each getting their own — only one member
holds a valid value at any given time. This makes a union more memory-efficient when you only ever
need one of several possible values, but it means writing to one member overwrites the others.

Enumeration (enum)
[ADDED — required by BBD syllabus, not present in your source notes]
An enum is a user-defined type made up of a set of named integer constants, used to make code more
readable than using plain numbers for fixed categories.

enum day { MON, TUE, WED, THU, FRI, SAT, SUN };


enum day today = WED;
// internally, MON = 0, TUE = 1, WED = 2, and so on unless you assign
values yourself
You can also assign your own starting values:

enum status { PASS = 1, FAIL = 0 };

typedef
typedef creates an alias for an existing type name — most commonly used to shorten a structure
name so you don't have to write struct every time.

typedef struct {
float real;
float img;
} ComplexNo;

ComplexNo c1, c2; // instead of writing 'struct complex c1, c2;'

2.7 Unit 2 Practice Questions


● 1. Write a program to create an array of 10 numbers and delete the element at a given
position, shifting the rest left.
● 2. Write a function that swaps two integers using call by reference. Show that call by value
would fail to do the same.
● 3. Write a recursive function to compute the nth Fibonacci number.
● 4. Declare a pointer to an integer, print the integer's value using the pointer, then increment
the pointer and explain what address it now holds.
● 5. Create a structure to store a student's roll number, name, and marks. Write a function that
accepts this structure and prints it.
● 6. Explain, with an example, why a static local variable behaves differently from a normal
(auto) local variable across multiple function calls.
● 7. Create an enum for the days of the week and write a program that prints "Weekend" or
"Weekday" based on a chosen day.
● 8. Write a program that passes an array to a function and doubles every element inside it —
verify the change is visible back in main().
UNIT 3 — Solved Lab Programs (matches BCACSN11151 Lab syllabus)
Your official Lab paper (Programming in 'C' Lab) lists these exact categories of programs as the
practical syllabus. One worked example for each is below — study these first since they are the most
direct rehearsal for your practical exam.

3.1 Fundamental Data Types


#include <stdio.h>
int main() {
int a = 10;
float b = 5.5;
char c = 'Z';
printf("int: %d, size: %d bytes\n", a, sizeof(a));
printf("float: %.1f, size: %d bytes\n", b, sizeof(b));
printf("char: %c, size: %d byte\n", c, sizeof(c));
return 0;
}

3.2 Fundamental Operators


#include <stdio.h>
int main() {
int a = 15, b = 4;
printf("Sum: %d\n", a + b);
printf("Modulus: %d\n", a % b);
printf("a > b: %d\n", a > b); // relational -> 1 (true)
printf("a>0 && b>0: %d\n", a > 0 && b > 0); // logical
return 0;
}

3.3 Conditional Program (if / switch)


#include <stdio.h>
int main() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
switch (marks / 10) {
case 10: case 9: printf("Grade A"); break;
case 8: printf("Grade B"); break;
case 7: printf("Grade C"); break;
default: printf("Grade F");
}
return 0;
}

3.4 Loop Constructs — Sum of First N Numbers (all three loop types)
#include <stdio.h>
int main() {
int n = 5, i, sum;

// for loop
sum = 0;
for (i = 1; i <= n; i++) sum += i;
printf("for loop sum: %d\n", sum);

// while loop
sum = 0; i = 1;
while (i <= n) { sum += i; i++; }
printf("while loop sum: %d\n", sum);

// do-while loop
sum = 0; i = 1;
do { sum += i; i++; } while (i <= n);
printf("do-while loop sum: %d\n", sum);

return 0;
}

3.5 Functions — Call by Value vs. Call by Reference


#include <stdio.h>
void swapByValue(int a, int b) {
int t = a; a = b; b = t; // only changes local copies
}
void swapByReference(int *a, int *b) {
int t = *a; *a = *b; *b = t; // changes the originals
}
int main() {
int x = 5, y = 10;
swapByValue(x, y);
printf("After call by value: x=%d y=%d\n", x, y); // unchanged: 5
10
swapByReference(&x, &y);
printf("After call by reference: x=%d y=%d\n", x, y); // swapped: 10
5
return 0;
}

3.6 Structure, Union and Enum Together


#include <stdio.h>
enum grade { A, B, C, FAIL };

struct student {
char name[20];
int rollNo;
enum grade result;
};

int main() {
struct student s1 = {"Rohan", 21, A};
printf("Name: %s, Roll: %d, Grade code: %d\n", [Link], [Link],
[Link]);
return 0;
}
3.7 Pointers, Pointer Arithmetic and Pointer-to-Pointer
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30};
int *p = arr; // p points to arr[0]
int **pp = &p; // pp points to p

printf("*p = %d\n", *p); // 10


p++;
printf("*p after p++ = %d\n", *p); // 20
printf("**pp = %d\n", **pp); // same as *p -> 20
return 0;
}

3.8 Nested Structure


#include <stdio.h>
struct address {
char city[20];
char state[20];
};
struct employee {
char name[20];
struct address addr; // structure nested inside another structure
};
int main() {
struct employee e1 = {"Aman", {"Lucknow", "UP"}};
printf("%s lives in %s, %s\n", [Link], [Link], [Link]);
return 0;
}
Quick Revision Sheet
A one-glance recap for the night before your exam — not a substitute for the units above, just a
memory jog.

Format specifiers
● %d — int %f — float %c — char %s — string %u — unsigned / pointer address

Operator precedence (high to low)


● () → * / % → + - → < > <= >= → == != → && → || → =

Loop choice
● Known number of iterations → for
● Unknown iterations, may run zero times → while
● Unknown iterations, must run at least once → do-while

Storage classes at a glance


● auto — default, local, resets every call
● static — local, but keeps its value between calls
● extern — shared across files
● register — hint to keep it in a CPU register

Common exam traps


● = is assignment, == is comparison — mixing these up silently changes program logic.
● Forgetting & before a variable in scanf().
● Forgetting break in a switch case, causing fall-through.
● 5 / 2 gives 2 (integer division), not 2.5 — cast one operand to float if you need the decimal.
● Array indices run from 0 to (size − 1), never from 1 to size.
● In Turbo C specifically: declare all variables at the top of a block, before any executable
statement.
Appendix A — Beyond This Semester's Syllabus (Optional)
These two topics were in your reference notes but are not part of this semester's official syllabus for
this paper. Kept here briefly in case your teacher touches on them or you want a head start — not
required for this semester's exam.

A.1 File Handling


Files let a program save data permanently — RAM contents are lost when a program ends, but a file on
disk persists.

FILE *ptr;
ptr = fopen("[Link]", "r"); // "r"=read "w"=write "a"=append
fscanf(ptr, "%d", &num); // read from file, like scanf
fclose(ptr); // always close a file after use

A.2 Dynamic Memory Allocation


Normal arrays have a fixed size decided at compile time. Dynamic memory allocation lets a program
request memory while it is actually running, using functions from <stdlib.h>.
● malloc(n) — allocates n bytes of raw memory, returns a pointer to it.
● calloc(n, size) — allocates memory for n elements, each initialised to 0.
● realloc(ptr, newSize) — resizes a previously allocated block.
● free(ptr) — releases memory back to the system once you're done with it.

You might also like