OLD QUESTION SET WITH THEIR SOLUTIONS
An instruction is a basic command given to a computer to perform a specific operation such as arithmetic, data transfer, or logical comparison. It is the smallest unit of a program that the processor can execute.
A program is a set of instructions written in a programming language that directs a computer to perform a specific task or solve a problem. It is executed sequentially (or conditionally) by the CPU.
| Generation | Name | Description | Example |
|---|---|---|---|
| 1GL | Machine Language | Binary instructions (0s and 1s) directly understood by CPU. Machine-dependent, very fast but difficult to write and debug. | 10110000 01100001 |
| 2GL | Assembly Language | Uses mnemonics (MOV, ADD) instead of binary. Requires assembler to convert to machine code. Still hardware-dependent. | MOV AX, 01H |
| 3GL | High-Level Language | English-like syntax, machine-independent. Requires compiler or interpreter. Easy to learn and use. | C, C++, FORTRAN, Java |
| 4GL | Very High-Level Language | Closer to human language. Used for database queries, report generation. Less coding required. | SQL, MATLAB, Python |
| 5GL | Natural / AI Language | Based on solving problems using constraints. Used in AI and expert systems. Programmer defines what to solve, not how. | Prolog, LISP |
Problem analysis is the first and most critical step in software development. Its importance includes:
Step 1: Start
Step 2: Read a number N from the user
Step 3: If N MOD 2 = 0, go to Step 4, else go to Step 5
Step 4: Print "N is Even", go to Step 6
Step 5: Print "N is Odd"
Step 6: Stop
An expression is a combination of operands (variables, constants) and operators that evaluates to a single value. Every expression has a type determined by its operands and operators.
a + b // evaluates to sum
x > y // evaluates to true or false
a = 5 // assignment expression
| Type | Description | Example |
|---|---|---|
| Arithmetic | Involves arithmetic operators; evaluates to a numeric value | a + b, x * 2 - 1 |
| Relational | Compares two values; evaluates to true (1) or false (0) | a > b, x == y |
| Logical | Combines relational expressions using logical operators | a > 0 && b > 0 |
| Assignment | Assigns a value to a variable; returns assigned value | x = 5, a += 3 |
| Bitwise | Operates on bits of integer operands | a & b, x | y, ~a |
| Conditional (Ternary) | Returns one of two values based on condition | a > b ? a : b |
| Comma | Evaluates multiple expressions; returns last value | x = (a=1, b=2, a+b) |
printf() – Displays formatted output to the screen.
Syntax: printf("format string", variable_list);
Example: printf("Sum = %d", a + b);
scanf() – Reads formatted input from the keyboard.
Syntax: scanf("format string", &variable_list);
Example: scanf("%d %f", &n, &x);
getchar() / putchar() – Reads/writes a single character.
char c;
c = getchar(); // reads one character
putchar(c); // prints one character
gets() / puts() – Reads/writes a string.
char name[50];
gets(name); // reads a string (until newline)
puts(name); // prints string followed by newline
| Specifier | Data Type |
|---|---|
| %d | Integer |
| %f | Float |
| %c | Character |
| %s | String |
| %lf | Double |
An if statement inside another if statement. Used when a condition depends on another condition being true first.
if (condition1) {
if (condition2) {
// executes when both condition1 and condition2 are true
} else {
// executes when condition1 true, condition2 false
}
} else {
// executes when condition1 is false
}
A series of if-else if conditions checked one by one. Used for multi-way branching where conditions are mutually exclusive.
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else if (condition3) {
// block 3
} else {
// default block
}
| Feature | Nested if | else if Ladder |
|---|---|---|
| Structure | if inside another if | Sequential if-else if chain |
| Use case | Dependent conditions | Independent, mutually exclusive conditions |
| Readability | Can become complex with deep nesting | More readable for multiple conditions |
| Execution | Inner if checked only if outer if is true | Each condition checked in sequence until one is true |
| Default | else for each level | Single final else handles all unmatched cases |
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
printf("%d is neither prime nor composite.\n", n);
return 0;
}
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
flag = 1;
break;
}
}
if (flag == 1)
printf("%d is a Prime number.\n", n);
else
printf("%d is a Composite number.\n", n);
return 0;
}
Enter a number: 13
13 is a Prime number.
Enter a number: 12
12 is a Composite number.
In call by value, a copy of the actual argument is passed to the function. Changes made inside the function do NOT affect the original variable.
#include <stdio.h>
void square(int x) {
x = x * x; // only local copy is changed
printf("Inside: %d\n", x);
}
int main() {
int a = 5;
square(a);
printf("Outside: %d\n", a); // a remains 5
return 0;
}
// Output:
// Inside: 25
// Outside: 5
In call by reference, the address of the actual argument is passed. Changes made inside the function DO affect the original variable.
#include <stdio.h>
void square(int *x) {
*x = (*x) * (*x); // original variable is changed
printf("Inside: %d\n", *x);
}
int main() {
int a = 5;
square(&a);
printf("Outside: %d\n", a); // a is now 25
return 0;
}
// Output:
// Inside: 25
// Outside: 25
| Feature | Call by Value | Call by Reference |
|---|---|---|
| What is passed | Copy of value | Address of variable |
| Original affected? | No | Yes |
| Memory | Extra copy created | No extra copy |
| Safety | Safer (no side effects) | Risk of unintended changes |
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1)
return 1; // base case
return n * factorial(n - 1); // recursive call
}
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %d\n", n, factorial(n));
return 0;
}
Enter a positive integer: 5
Factorial of 5 = 120
factorial(5)
= 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120
#include <stdio.h>
int main() {
char str[100], rev[100];
int i, len = 0;
printf("Enter a string: ");
scanf("%s", str);
// Find length manually
while (str[len] != '\0')
len++;
// Copy in reverse
for (i = 0; i < len; i++)
rev[i] = str[len - 1 - i];
rev[len] = '\0';
printf("Reversed string: %s\n", rev);
return 0;
}
Enter a string: HELLO
Reversed string: OLLEH
#include <stdio.h>
int main() {
int a[10], i, max, min;
printf("Enter 10 numbers:\n");
for (i = 0; i < 10; i++) {
printf("Number %d: ", i + 1);
scanf("%d", &a[i]);
}
max = a[0];
min = a[0];
for (i = 1; i < 10; i++) {
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
printf("Largest number = %d\n", max);
printf("Smallest number = %d\n", min);
return 0;
}
Enter 10 numbers:
Number 1: 4
Number 2: 7
... (10 inputs)
Largest number = 98
Smallest number = 2
A structure is a user-defined data type in C that groups variables of different data types under a single name. Each variable inside a structure is called a member.
struct Student {
int roll;
char name[50];
float marks;
};
Structures are necessary because they allow related data of different types to be stored and managed together as a single unit. Without structures, each piece of related information would need to be stored in separate variables, making programs harder to manage, read, and maintain. They are especially useful for representing real-world entities like students, employees, or distances.
#include <stdio.h>
struct Distance {
int feet;
float inch;
};
int main() {
struct Distance d1, d2, sum;
printf("Enter first distance:\n");
printf("Feet: "); scanf("%d", &d1.feet);
printf("Inch: "); scanf("%f", &d1.inch);
printf("Enter second distance:\n");
printf("Feet: "); scanf("%d", &d2.feet);
printf("Inch: "); scanf("%f", &d2.inch);
sum.feet = d1.feet + d2.feet;
sum.inch = d1.inch + d2.inch;
// Convert excess inches to feet
if (sum.inch >= 12.0) {
sum.feet += (int)(sum.inch / 12);
sum.inch = sum.inch - (int)(sum.inch / 12) * 12;
}
printf("\nSum = %d feet %.2f inches\n", sum.feet, sum.inch);
return 0;
}
Enter first distance:
Feet: 5
Inch: 9.5
Enter second distance:
Feet: 3
Inch: 4.8
Sum = 9 feet 2.30 inches
Pointer arithmetic refers to arithmetic operations performed on pointer variables. Since pointers hold memory addresses, arithmetic on them moves the pointer by multiples of the size of the data type they point to.
| Operation | Description |
|---|---|
| ptr++ | Move pointer to next element (adds sizeof(type)) |
| ptr-- | Move pointer to previous element |
| ptr + n | Move pointer n elements forward |
| ptr - n | Move pointer n elements backward |
| ptr1 - ptr2 | Number of elements between two pointers |
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to arr[0]
printf("ptr = %d (address: %u)\n", *ptr, ptr);
ptr++;
printf("ptr++ = %d (address: %u)\n", *ptr, ptr);
ptr += 2;
printf("ptr+2 = %d (address: %u)\n", *ptr, ptr);
return 0;
}
// Output (assuming int = 4 bytes):
// ptr = 10 (address: 1000)
// ptr++ = 20 (address: 1004)
// ptr+2 = 40 (address: 1012)
Each increment moves the pointer by 4 bytes (size of int), not just 1 byte.
#include <stdio.h>
int main() {
int a, b;
int *p1, *p2;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
p1 = &a;
p2 = &b;
printf("Sum = %d\n", *p1 + *p2);
printf("Difference = %d\n", *p1 - *p2);
printf("Product = %d\n", *p1 * *p2);
return 0;
}
Enter two numbers: 8 3
Sum = 11
Difference = 5
Product = 24
| Feature | Console I/O | File I/O |
|---|---|---|
| Definition | Input/output via keyboard and screen | Input/output via files stored on disk |
| Functions | scanf(), printf(), gets(), puts() | fscanf(), fprintf(), fgets(), fputs() |
| Persistence | Data lost when program ends | Data persists on disk after program ends |
| Speed | Slower (user interaction) | Faster for large data |
| Capacity | Limited (user input) | Can handle large amounts of data |
| File pointer | Not required | Requires FILE* pointer |
#include <stdio.h>
int main() {
FILE *fp;
char name[50];
int id;
float salary;
int found = 0;
fp = fopen("employee.txt", "r");
if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
printf("Employees with salary > 50000:\n");
printf("%-20s %-10s %-10s\n", "Name", "ID", "Salary");
printf("--------------------------------------\n");
while (fscanf(fp, "%s %d %f", name, &id, &salary) != EOF) {
if (salary > 50000) {
printf("%-20s %-10d %-10.2f\n", name, id, salary);
found = 1;
}
}
if (!found)
printf("No employees found with salary > 50000.\n");
fclose(fp);
return 0;
}
Ram 101 45000
Sita 102 60000
Hari 103 75000
Gita 104 30000
Employees with salary > 50000:
Name ID Salary
--------------------------------------
Sita 102 60000.00
Hari 103 75000.00
| Basis | C | FORTRAN |
|---|---|---|
| Full Name | C Programming Language | FORmula TRANslation |
| Purpose | General purpose / systems programming | Scientific and numerical computing |
| Array Index | Starts at 0 | Starts at 1 (default) |
| String Handling | char arrays with '\0' | CHARACTER data type |
| Case Sensitive | Yes | No (case-insensitive) |
| Pointers | Explicit pointer support | Limited pointer support |
| I/O | printf / scanf | READ / WRITE with FORMAT |
| Comments | // or /* */ | C or ! at start of line (F77/F90) |
C --- 1D Array ---
INTEGER A(10) ! Array of 10 integers (index 1 to 10)
REAL X(5) ! Array of 5 real numbers
C --- 2D Array ---
INTEGER MAT(3,4) ! 3 rows, 4 columns
REAL B(10,10) ! 10x10 matrix
PROGRAM TRANSPOSE
INTEGER A(10,10), T(10,10), M, N, I, J
C Read dimensions
WRITE(*,*) 'Enter number of rows and columns:'
READ(*,*) M, N
C Read matrix elements
WRITE(*,*) 'Enter matrix elements row by row:'
DO 10 I = 1, M
DO 10 J = 1, N
READ(*,*) A(I,J)
10 CONTINUE
C Compute transpose: T(I,J) = A(J,I)
DO 20 I = 1, N
DO 30 J = 1, M
T(I,J) = A(J,I)
30 CONTINUE
20 CONTINUE
C Display transpose
WRITE(*,*) 'Transpose of the matrix:'
DO 40 I = 1, N
DO 50 J = 1, M
WRITE(*,100) T(I,J)
50 CONTINUE
WRITE(*,*)
40 CONTINUE
100 FORMAT(I5,$)
STOP
END
| Basis | System Software | Application Software |
|---|---|---|
| Definition | Software that manages and controls hardware to provide a platform for other software | Software designed to perform specific tasks for the end user |
| Purpose | Manages computer resources and hardware | Fulfills specific user needs or tasks |
| Interaction | Interacts directly with hardware | Interacts with system software, not hardware directly |
| Dependency | Can run independently of application software | Depends on system software to run |
| Examples | OS (Windows, Linux), Device Drivers, Compilers | MS Word, VLC, Chrome, Games |
| User interaction | Minimal direct interaction with users | Designed primarily for user interaction |
C is widely used in simulation for the following reasons:
Testing is the process of executing a program with various inputs to verify that it produces the correct and expected output. The goal is to detect errors, verify functionality, and ensure the program meets its requirements. Testing does not fix errors — it only identifies them.
Types: Unit testing, Integration testing, System testing, Black-box testing, White-box testing.
Debugging is the process of finding, analyzing, and fixing the errors (bugs) discovered during testing. It involves locating the exact source of the error in the code and correcting it so the program runs as expected.
| Testing | Debugging |
|---|---|
| Identifies that an error exists | Finds and fixes the exact error |
| Done by testers or users | Done by developers/programmers |
| Comes before debugging | Follows testing |
Step 1: Start
Step 2: Read N from the user
Step 3: Set sum = 0, i = 1
Step 4: If i > N, go to Step 7
Step 5: sum = sum + i, i = i + 1
Step 6: Go to Step 4
Step 7: Print sum
Step 8: Stop
Precedence determines the order in which operators are evaluated when an expression has more than one operator. Operators with higher precedence are evaluated first.
int x = 2 + 3 * 4;
// * has higher precedence than +
// Evaluated as: 2 + (3 * 4) = 2 + 12 = 14
| Precedence (High to Low) | Operators |
|---|---|
| 1 (Highest) | () [] -> . |
| 2 | ++ -- ! ~ (unary) |
| 3 | * / % |
| 4 | + - |
| 5 | < <= > >= |
| 6 | == != |
| 7 | && |
| 8 | || |
| 9 (Lowest) | = += -= *= /= |
Associativity determines the direction of evaluation when two operators have the same precedence. It can be left-to-right or right-to-left.
// Left-to-right (most operators):
int x = 10 - 3 - 2; // = (10 - 3) - 2 = 5
// Right-to-left (assignment, unary):
int a, b, c;
a = b = c = 5; // = c=5, then b=5, then a=5
Keywords are reserved words in C that have predefined meanings and cannot be used as identifiers (variable names, function names, etc.). C has 32 keywords.
int, float, char, double, void, if, else, for, while, do,
switch, case, break, continue, return, struct, union,
typedef, enum, sizeof, static, extern, auto, register,
const, volatile, signed, unsigned, short, long, goto, default
sum and Sum are different).Valid: sum, _count, total1, MAX_SIZE
Invalid: 1total (starts with digit), int (keyword), my-var (hyphen)
| Basis | Formatted I/O | Unformatted I/O |
|---|---|---|
| Definition | Data is read/written in a specific human-readable format using format specifiers | Data is read/written as raw characters without any formatting |
| Functions | printf(), scanf() | getchar(), putchar(), gets(), puts() |
| Format specifiers | Required (%d, %f, %c, %s) | Not required |
| Data types | Handles multiple data types | Handles only characters and strings |
| Flexibility | More flexible, supports field width and precision | Less flexible |
| Example | printf("Value = %d", x); | putchar('A'); gets(str); |
// Formatted I/O
int n;
float x;
scanf("%d %f", &n, &x);
printf("n=%d, x=%.2f", n, x);
// Unformatted I/O
char c, str[50];
c = getchar(); // reads one character
putchar(c); // prints one character
gets(str); // reads a string
puts(str); // prints a string
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
printf("%d is neither prime nor composite.\n", n);
return 0;
}
for (i = 2; i <= n / 2; i++) {
if (n % i == 0) {
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a Prime number.\n", n);
else
printf("%d is a Composite number.\n", n);
return 0;
}
Enter a number: 17
17 is a Prime number.
Enter a number: 9
9 is a Composite number.
#include <stdio.h>
int main() {
int i, j, n = 5;
for (i = 1; i <= n; i++) {
// Print leading spaces
for (j = i; j < n; j++) {
printf(" ");
}
// Print stars
for (j = 1; j <= (2 * i - 1); j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
A function is a self-contained block of code that performs a specific task. It can be called multiple times from anywhere in the program. Every C program has at least one function: main().
| Type | Description | Example |
|---|---|---|
| Library Functions | Built-in functions provided by C standard library | printf(), sqrt(), strlen() |
| User-defined Functions | Functions defined by the programmer | int add(int a, int b) { ... } |
User-defined functions are further classified by return type and arguments:
#include <stdio.h>
int fibonacci(int n) {
if (n == 0) return 0; // base case
if (n == 1) return 1; // base case
return fibonacci(n - 1) + fibonacci(n - 2); // recursive call
}
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("The %dth Fibonacci term = %d\n", n, fibonacci(n));
return 0;
}
Enter the value of n: 7
The 7th Fibonacci term = 13
fibonacci(5)
= fibonacci(4) + fibonacci(3)
= (fibonacci(3) + fibonacci(2)) + (fibonacci(2) + fibonacci(1))
= ... = 3 + 2 = 5
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21 … (index starts at 0)
A 1D (one-dimensional) array is a linear collection of elements of the same data type stored in contiguous memory locations, accessed using a single index.
int a[5] = {10, 20, 30, 40, 50};
// accessed as a[0], a[1], ..., a[4]
A 2D (two-dimensional) array is an array of arrays that represents data in rows and columns (like a matrix), accessed using two indices: row and column.
int mat[3][4]; // 3 rows, 4 columns
// accessed as mat[i][j]
#include <stdio.h>
int main() {
int a[10][10], t[10][10], m, n, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &m, &n);
printf("Enter matrix elements:\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
// Compute transpose
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
t[j][i] = a[i][j];
printf("Transpose matrix:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
printf("%4d", t[i][j]);
printf("\n");
}
return 0;
}
Enter rows and columns: 2 3
Enter matrix elements:
1 2 3
4 5 6
Transpose matrix:
1 4
2 5
3 6
#include <stdio.h>
int main() {
char str[100];
int len = 0;
printf("Enter a string: ");
scanf("%s", str);
while (str[len] != '\0')
len++;
printf("Length of string = %d\n", len);
return 0;
}
Enter a string: HELLO
Length of string = 5
The loop counts characters until the null terminator '\0' is reached, which marks the end of the string.
A nested structure is a structure that contains another structure as one of its members. This allows grouping of related sub-data within a larger structure.
struct Address {
char city[50];
char district[50];
};
struct Student {
char name[50];
int roll;
float marks;
struct Address addr; // nested structure
};
#include <stdio.h>
#include <string.h>
struct Address {
char city[50];
char district[50];
};
struct Student {
char name[50];
int roll;
float marks;
struct Address addr;
};
int main() {
int n, i, j;
struct Student s[50], temp;
printf("Enter number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Name: "); scanf("%s", s[i].name);
printf("Roll: "); scanf("%d", &s[i].roll);
printf("Marks: "); scanf("%f", &s[i].marks);
printf("City: "); scanf("%s", s[i].addr.city);
printf("District: ");scanf("%s", s[i].addr.district);
}
// Sort by marks (descending) using bubble sort
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (s[j].marks < s[j + 1].marks) {
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
printf("\n%-15s %-6s %-8s %-15s %-15s\n",
"Name", "Roll", "Marks", "City", "District");
printf("--------------------------------------------------------------\n");
for (i = 0; i < n; i++)
printf("%-15s %-6d %-8.2f %-15s %-15s\n",
s[i].name, s[i].roll, s[i].marks,
s[i].addr.city, s[i].addr.district);
return 0;
}
A pointer is a variable that stores the memory address of another variable. It is declared using the * operator and the address-of operator & is used to get the address of a variable.
int a = 10;
int *p = &a; // p stores address of a
printf("%d", *p); // *p dereferences to get value: 10
#include <stdio.h>
void bubbleSort(int *arr, int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (*(arr + j) > *(arr + j + 1)) {
temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
int main() {
int n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d numbers:\n", n);
for (i = 0; i < n; i++)
scanf("%d", arr + i); // using pointer notation
bubbleSort(arr, n);
printf("Sorted in ascending order:\n");
for (i = 0; i < n; i++)
printf("%d ", *(arr + i));
printf("\n");
return 0;
}
Enter number of elements: 5
Enter 5 numbers:
40 10 30 50 20
Sorted in ascending order:
10 20 30 40 50
| Basis | Text File | Binary File |
|---|---|---|
| Storage | Data stored as human-readable ASCII characters | Data stored in binary (0s and 1s) format |
| Readability | Can be opened and read in any text editor | Not human-readable; requires special program |
| End of line | '\n' is translated to OS-specific newline | No translation; stored as-is |
| End of file | EOF marked by special character (Ctrl+Z) | EOF determined by file size |
| Size | Generally larger due to ASCII representation | More compact and efficient |
| Mode | "r", "w", "a" | "rb", "wb", "ab" |
| Example | .txt, .csv, .html | .exe, .jpg, .mp3 |
#include <stdio.h>
int main() {
FILE *src, *dest;
char ch;
src = fopen("source.txt", "r");
if (src == NULL) {
printf("Error: Cannot open source.txt\n");
return 1;
}
dest = fopen("destination.txt", "w");
if (dest == NULL) {
printf("Error: Cannot create destination.txt\n");
fclose(src);
return 1;
}
while ((ch = fgetc(src)) != EOF)
fputc(ch, dest);
printf("File copied successfully.\n");
fclose(src);
fclose(dest);
return 0;
}
File copied successfully.
PROGRAM program_name ! Program header (optional in F77)
C Declaration section
[data type declarations]
C Executable section
[statements]
C Subprogram section (optional)
[SUBROUTINE / FUNCTION definitions]
STOP
END
| Data Type | Description | Example |
|---|---|---|
| INTEGER | Whole numbers | INTEGER N, COUNT |
| REAL | Single-precision floating point | REAL X, PRICE |
| DOUBLE PRECISION | Double-precision floating point | DOUBLE PRECISION D |
| COMPLEX | Complex numbers (real + imaginary) | COMPLEX Z |
| LOGICAL | Boolean values (.TRUE. / .FALSE.) | LOGICAL FLAG |
| CHARACTER | Character strings | CHARACTER*20 NAME |
PROGRAM ARITH_IF
REAL N
WRITE(*,*) 'Enter a number:'
READ(*,*) N
C Arithmetic IF: IF (expression) label1, label2, label3
C Jumps to label1 if expression < 0
C Jumps to label2 if expression = 0
C Jumps to label3 if expression > 0
IF (N) 10, 20, 30
10 WRITE(*,*) 'The number is Negative.'
GO TO 40
20 WRITE(*,*) 'The number is Zero.'
GO TO 40
30 WRITE(*,*) 'The number is Positive.'
40 STOP
END
Enter a number:
-5
The number is Negative.
Enter a number:
0
The number is Zero.
Enter a number:
8
The number is Positive.
Note: Arithmetic IF syntax — IF (expr) L1, L2, L3 — branches to L1 if expr < 0, L2 if expr = 0, L3 if expr > 0. It is unique to FORTRAN.
| Basis | System Software | Application Software |
|---|---|---|
| Definition | Software that manages hardware and provides a platform for other software | Software designed to perform specific tasks for end users |
| Purpose | Manages computer resources | Fulfills specific user needs |
| Interaction | Directly interacts with hardware | Interacts via system software |
| Dependency | Runs independently | Depends on system software |
| Examples | OS (Windows, Linux), Device Drivers, Compilers | MS Word, Chrome, VLC, Games |
| User Interaction | Minimal direct interaction | Designed primarily for user interaction |
Software development follows the Software Development Life Cycle (SDLC):
| Phase | Output |
|---|---|
| Requirement Analysis | SRS document |
| Design | Architecture & flowcharts |
| Coding | Source code |
| Testing | Test reports, bug list |
| Documentation | User/technical manuals |
| Maintenance | Updated software |
An operator is a symbol that instructs the compiler to perform a specific mathematical, relational, logical, or bitwise operation on operands.
int x = 5 + 3; // + is the arithmetic operator
int y = (x > 3); // > is the relational operator
Types: Arithmetic (+, -, *, /, %), Relational (<, >, ==, !=), Logical (&&, ||, !), Assignment (=, +=), Bitwise (&, |, ^), Increment/Decrement (++, --), Conditional (?:), sizeof.
A keyword is a reserved word in C with a predefined meaning that cannot be used as an identifier. C has 32 keywords.
int, float, char, double, void, if, else, for, while, do,
switch, case, break, continue, return, struct, union,
typedef, enum, sizeof, static, extern, auto, register,
const, volatile, signed, unsigned, short, long, goto, default
Step 1: Start
Step 2: Read N from user
Step 3: If N < 0, print "Invalid" and goto Step 8
Step 4: Set fact = 1, i = 1
Step 5: If i > N, goto Step 7
Step 6: fact = fact * i, i = i + 1, goto Step 5
Step 7: Print fact
Step 8: Stop
Syntax: int getch(void); — Header: <conio.h>
Reads a single character from the keyboard without echoing it on screen and without waiting for Enter.
#include <stdio.h>
#include <conio.h>
int main() {
char ch;
printf("Press any key: ");
ch = getch(); // reads char without displaying
printf("\nYou pressed: %c", ch);
return 0;
}
Syntax: char *gets(char *str); — Header: <stdio.h>
Reads a full line (including spaces) from stdin into str until a newline or EOF is encountered. The newline is replaced with '\0'.
#include <stdio.h>
int main() {
char name[50];
printf("Enter full name: ");
gets(name); // reads string with spaces
printf("Hello, %s!\n", name);
return 0;
}
Syntax: int printf(const char *format, ...); — Header: <stdio.h>
Formatted output function. Prints data to stdout using format specifiers (%d, %f, %c, %s, etc.).
#include <stdio.h>
int main() {
int age = 20;
float gpa = 3.85;
char name[] = "Alice";
printf("Name: %s, Age: %d, GPA: %.2f\n", name, age, gpa);
// Output: Name: Alice, Age: 20, GPA: 3.85
return 0;
}
Syntax: int scanf(const char *format, ...); — Header: <stdio.h>
Formatted input function. Reads data from stdin and stores them at the given addresses. Returns the number of items successfully read.
#include <stdio.h>
int main() {
int n;
float x;
char name[30];
printf("Enter name, number, float: ");
scanf("%s %d %f", name, &n, &x);
printf("%s %d %.2f\n", name, n, x);
return 0;
}
| Function | Header | Purpose | Type |
|---|---|---|---|
| getch() | conio.h | Read single char, no echo | Unformatted Input |
| gets() | stdio.h | Read full line with spaces | Unformatted Input |
| printf() | stdio.h | Formatted output to stdout | Formatted Output |
| scanf() | stdio.h | Formatted input from stdin | Formatted Input |
| Basis | while loop | do-while loop |
|---|---|---|
| Condition Check | Checked before loop body executes (entry-controlled) | Checked after loop body executes (exit-controlled) |
| Minimum Executions | May execute 0 times if condition is false initially | Executes at least once regardless of condition |
| Syntax | while(cond){ ... } | do{ ... }while(cond); |
| Semicolon | No semicolon after condition | Semicolon required after while(cond) |
| Use Case | When iterations may be 0 (pre-check needed) | When at least one iteration is guaranteed (e.g., menu) |
// while loop
int i = 5;
while (i < 5) { printf("%d", i); i++; } // prints nothing
// do-while loop
int j = 5;
do { printf("%d", j); j++; } while (j < 5); // prints 5 once
An Armstrong (Narcissistic) number of N digits satisfies: sum of each digit raised to the power N equals the original number.
#include <stdio.h>
#include <math.h>
int main() {
long long num, temp, orig;
int digit, n = 0;
double sum = 0;
printf("Enter a positive number: ");
scanf("%lld", &num);
orig = num;
temp = num;
// Count digits
while (temp != 0) {
n++;
temp /= 10;
}
temp = num;
// Calculate sum of digits^n
while (temp != 0) {
digit = temp % 10;
sum += pow(digit, n);
temp /= 10;
}
if ((long long)sum == orig)
printf("%lld is an Armstrong number.\n", orig);
else
printf("%lld is NOT an Armstrong number.\n", orig);
return 0;
}
Enter a positive number: 1634
1634 is an Armstrong number.
Enter a positive number: 153
153 is an Armstrong number. [1³+5³+3³ = 1+125+27 = 153]
Enter a positive number: 100
100 is NOT an Armstrong number.
In C, an array is always passed to a function by reference (by address) — the function receives a pointer to the first element. This means changes inside the function affect the original array.
// Syntax
return_type function_name(data_type arr[], int size);
// OR equivalently:
return_type function_name(data_type *arr, int size);
& operator needed — the array name already holds the address.void f(int a[][4], int r).#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void display(int arr[], int n) {
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int n, arr[100];
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
bubbleSort(arr, n); // array passed by reference
printf("Sorted array (ascending): ");
display(arr, n);
return 0;
}
Enter number of elements: 6
Enter 6 elements:
45 12 78 3 56 23
Sorted array (ascending): 3 12 23 45 56 78
#include <stdio.h>
int main() {
char str[200];
int len = 0;
printf("Enter a string: ");
gets(str); // reads full line with spaces
while (str[len] != '\0') // count until null terminator
len++;
printf("Length of \"%s\" = %d\n", str, len);
return 0;
}
Enter a string: Hello World
Length of "Hello World" = 11
Enter a string: COMPUTER
Length of "COMPUTER" = 8
The loop increments len for every character until '\0' (null terminator) is found, which marks the end of the string in C. This replicates the behaviour of strlen() from <string.h>.
A function prototype is a declaration of a function that specifies its name, return type, and parameter types before its actual definition. It tells the compiler about the function so it can perform type checking during compilation.
// Prototype (declaration) — usually before main()
int add(int a, int b); // return type + name + parameter types
int main() {
int result = add(3, 5); // compiler checks types using prototype
return 0;
}
// Definition (actual body)
int add(int a, int b) {
return a + b;
}
Why needed?
main() without error.#include <stdio.h>
// Function prototype
int fibonacci(int n);
int main() {
int n, i;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("Fibonacci series: ");
for (i = 0; i < n; i++)
printf("%d ", fibonacci(i));
printf("\n");
return 0;
}
// Recursive function definition
int fibonacci(int n) {
if (n == 0) return 0; // base case
if (n == 1) return 1; // base case
return fibonacci(n-1) + fibonacci(n-2); // recursive case
}
Enter number of terms: 8
Fibonacci series: 0 1 1 2 3 5 8 13
fibonacci(5) = fibonacci(4) + fibonacci(3)
= (fibonacci(3) + fibonacci(2)) + (fibonacci(2) + fibonacci(1))
= ((fibonacci(2)+fibonacci(1)) + (fibonacci(1)+fibonacci(0)))
+ ((fibonacci(1)+fibonacci(0)) + 1)
= ((1+1)+1+0) + (1+0+1) = 3 + 2 = 5 ✓
A nested structure is a structure that contains another structure as one of its members. This allows logically related sub-data to be grouped within a larger structure.
struct Date {
int day, month, year;
};
struct Student {
char name[50];
int roll;
struct Date dob; // nested structure — Date inside Student
};
Accessing nested members:
struct Student s;
s.dob.day = 15; // dot operator chained
s.dob.month = 8;
s.dob.year = 2003;
printf("%s born on %d/%d/%d", s.name, s.dob.day, s.dob.month, s.dob.year);
| Operator | Used With | Syntax |
|---|---|---|
. (dot) | Structure variable | var.member |
-> (arrow) | Structure pointer | ptr->member (equivalent to (*ptr).member) |
#include <stdio.h>
#include <string.h>
struct Address {
char city[50];
char zip[10];
};
struct Employee {
int id;
char name[50];
float salary;
struct Address addr; // nested structure
};
int main() {
// Using dot operator with a structure variable
struct Employee e1;
e1.id = 101;
strcpy(e1.name, "Ramesh Sharma");
e1.salary = 45000.00;
strcpy(e1.addr.city, "Kathmandu");
strcpy(e1.addr.zip, "44600");
printf("=== Using dot (.) operator ===\n");
printf("ID : %d\n", e1.id);
printf("Name : %s\n", e1.name);
printf("Salary : %.2f\n", e1.salary);
printf("City : %s\n", e1.addr.city);
printf("ZIP : %s\n", e1.addr.zip);
// Using arrow operator with a structure pointer
struct Employee e2;
struct Employee *ptr = &e2;
ptr->id = 202;
strcpy(ptr->name, "Sunita Thapa");
ptr->salary = 52000.00;
strcpy(ptr->addr.city, "Pokhara");
strcpy(ptr->addr.zip, "33700");
printf("\n=== Using arrow (->) operator ===\n");
printf("ID : %d\n", ptr->id);
printf("Name : %s\n", ptr->name);
printf("Salary : %.2f\n", ptr->salary);
printf("City : %s\n", ptr->addr.city);
printf("ZIP : %s\n", ptr->addr.zip);
return 0;
}
=== Using dot (.) operator ===
ID : 101
Name : Ramesh Sharma
Salary : 45000.00
City : Kathmandu
ZIP : 44600
=== Using arrow (->) operator ===
ID : 202
Name : Sunita Thapa
Salary : 52000.00
City : Pokhara
ZIP : 33700
Pointer arithmetic involves performing arithmetic operations on pointer variables. The operations are scaled automatically by the size of the data type the pointer points to.
sizeof(type) bytes).#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to first element
int i, n = 5;
printf("Array traversal using pointer arithmetic:\n");
// Using ptr++ to traverse
for (i = 0; i < n; i++) {
printf("arr[%d] = %d (address: %u)\n", i, *ptr, ptr);
ptr++; // moves to next int (adds 4 bytes)
}
// Reset pointer
ptr = arr;
// Pointer + integer
printf("\nptr + 2 points to: %d\n", *(ptr + 2)); // arr[2] = 30
printf("ptr + 4 points to: %d\n", *(ptr + 4)); // arr[4] = 50
// Difference between two pointers
int *p1 = &arr[1];
int *p2 = &arr[4];
printf("\nElements between p1(arr[1]) and p2(arr[4]): %ld\n", p2 - p1);
// Pointer comparison
if (p2 > p1)
printf("p2 is ahead of p1 in memory.\n");
return 0;
}
Array traversal using pointer arithmetic:
arr[0] = 10 (address: 6422280)
arr[1] = 20 (address: 6422284)
arr[2] = 30 (address: 6422288)
arr[3] = 40 (address: 6422292)
arr[4] = 50 (address: 6422296)
ptr + 2 points to: 30
ptr + 4 points to: 50
Elements between p1(arr[1]) and p2(arr[4]): 3
p2 is ahead of p1 in memory.
Each increment adds 4 bytes (size of int), demonstrating that pointer arithmetic is type-aware.
| Basis | Text File | Binary File |
|---|---|---|
| Storage Format | Data stored as human-readable ASCII characters | Data stored in binary (0s and 1s) as in memory |
| Readability | Readable in any text editor (Notepad, vim) | Not human-readable; requires special program |
| Newline | '\n' translated to OS-specific line ending | No translation; data stored as-is |
| EOF | Marked by special character (Ctrl+Z on Windows) | Determined by file size |
| Size | Larger; numbers stored digit-by-digit | Compact; numbers stored as raw bytes |
| Open Mode | "r", "w", "a" | "rb", "wb", "ab" |
| Functions | fprintf(), fscanf(), fgets(), fputs() | fread(), fwrite() |
| Examples | .txt, .csv, .html | .exe, .jpg, .mp3, .bin |
#include <stdio.h>
int main() {
FILE *odd_fp, *even_fp;
int n, num;
odd_fp = fopen("ODD.txt", "w");
even_fp = fopen("EVEN.txt", "w");
if (odd_fp == NULL || even_fp == NULL) {
printf("Error opening files!\n");
return 1;
}
printf("How many integers to enter? ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("Enter positive integer %d: ", i + 1);
scanf("%d", &num);
if (num <= 0) {
printf("Skipping non-positive number.\n");
continue;
}
if (num % 2 != 0)
fprintf(odd_fp, "%d\n", num); // write odd to ODD.txt
else
fprintf(even_fp, "%d\n", num); // write even to EVEN.txt
}
fclose(odd_fp);
fclose(even_fp);
printf("\nOdd numbers written to ODD.txt\n");
printf("Even numbers written to EVEN.txt\n");
return 0;
}
How many integers to enter? 6
Enter positive integer 1: 7
Enter positive integer 2: 12
Enter positive integer 3: 3
Enter positive integer 4: 8
Enter positive integer 5: 15
Enter positive integer 6: 4
Odd numbers written to ODD.txt
Even numbers written to EVEN.txt
ODD.txt contents: 7 EVEN.txt contents: 12
3 8
15 4
The Arithmetic IF is a three-way branching statement unique to FORTRAN. It evaluates an arithmetic expression and transfers control to one of three labeled statements depending on whether the result is negative, zero, or positive.
IF (arithmetic_expression) label1, label2, label3
| Condition | Branches To |
|---|---|
| expression < 0 | label1 |
| expression = 0 | label2 |
| expression > 0 | label3 |
C Example: classify X
IF (X) 10, 20, 30
10 WRITE(*,*) 'Negative'
GOTO 40
20 WRITE(*,*) 'Zero'
GOTO 40
30 WRITE(*,*) 'Positive'
40 CONTINUE
The arithmetic IF is a FORTRAN 77 feature; modern FORTRAN (90+) prefers IF-THEN-ELSE constructs.
A number is a palindrome if it reads the same forwards and backwards (e.g., 121, 1221, 12321).
PROGRAM PALINDROME
INTEGER N, ORIG, REV, DIGIT, TEMP
WRITE(*,*) 'Enter a positive integer:'
READ(*,*) N
C Store original number
ORIG = N
REV = 0
TEMP = N
C Reverse the number
10 IF (TEMP) 30, 30, 20
20 DIGIT = MOD(TEMP, 10)
REV = REV * 10 + DIGIT
TEMP = TEMP / 10
GOTO 10
C Check palindrome
30 IF (ORIG - REV) 40, 50, 40
40 WRITE(*,*) ORIG, ' is NOT a Palindrome.'
GOTO 60
50 WRITE(*,*) ORIG, ' is a Palindrome.'
60 STOP
END
Enter a positive integer:
12321
12321 is a Palindrome.
Enter a positive integer:
1234
1234 is NOT a Palindrome.
Enter a positive integer:
1221
1221 is a Palindrome.
IF (TEMP) 30, 30, 20 — if TEMP ≤ 0 go to 30 (loop ends), else go to 20 (continue reversing).IF (ORIG - REV) 40, 50, 40 — if difference is non-zero → not palindrome (40), if zero → palindrome (50).| Basis | Call by Value | Call by Reference |
|---|---|---|
| What is passed | Copy of actual argument | Address (pointer) of variable |
| Original value | Not modified | Can be modified |
| Memory | Extra memory for copy | No copy; same memory |
| Safety | Safer; protects original | Less safe; original can change |
| Use case | When original must be preserved | When function must modify original |
// Call by Value
void inc(int x) { x++; } // local copy changed
int a=5; inc(a); // a still 5
// Call by Reference
void inc(int *x) { (*x)++; }
int a=5; inc(&a); // a becomes 6
| Basis | break | continue |
|---|---|---|
| Action | Exits (terminates) the loop immediately | Skips remaining body; goes to next iteration |
| Loop status | Loop ends | Loop continues |
| Used in | for, while, do-while, switch | for, while, do-while |
| Effect | Jumps to statement after loop/switch | Jumps to condition check (while/do-while) or update (for) |
// break example
for (i=1; i<=10; i++) {
if (i==5) break; // stops at 5
printf("%d ", i); // prints 1 2 3 4
}
// continue example
for (i=1; i<=5; i++) {
if (i==3) continue; // skip 3
printf("%d ", i); // prints 1 2 4 5
}
The compilation process converts human-readable C source code into an executable machine code through the following stages:
| Stage | Tool | Description |
|---|---|---|
| 1. Source Code | — | Programmer writes code in a .c file (e.g., program.c) |
| 2. Pre-processing | Preprocessor (cpp) | Handles #include, #define, #ifdef directives; expands macros; removes comments. Produces .i file. |
| 3. Compilation | Compiler (cc1) | Converts preprocessed code into assembly language (.s file). Performs syntax and semantic checks. |
| 4. Assembly | Assembler (as) | Converts assembly code into machine code (object file .o). Code is not yet executable. |
| 5. Linking | Linker (ld) | Combines object file(s) with library files (e.g., stdio) to produce the final executable (.exe or a.out). |
| 6. Loading & Execution | Loader / OS | Loads the executable into memory and begins execution. |
Source (.c)
→ Preprocessor → .i
→ Compiler → .s (assembly)
→ Assembler → .o (object)
→ Linker → .exe / a.out (executable)
A variable is a named memory location whose value can change during program execution. A constant is a fixed value that cannot be changed once defined.
/* Variable Declaration in C */
int age; // declare
int age = 20; // declare and initialize
float price = 9.99;
char grade = 'A';
int a, b, c; // multiple variables
/* Constants in C */
// Method 1: #define (macro constant)
#define PI 3.14159
#define MAX 100
// Method 2: const keyword
const float PI = 3.14159;
const int MAX = 100;
| Feature | Variable (C) | Constant (C) |
|---|---|---|
| Value | Can change | Fixed, cannot change |
| Declaration | data_type name; | const data_type name = value; or #define |
| Memory | Allocated in RAM | #define: no memory; const: stored in memory |
In FORTRAN, variables are declared by specifying the data type before the variable name. Constants are defined using the PARAMETER statement.
C Variable Declaration in FORTRAN
INTEGER COUNT, N
REAL PRICE, TOTAL
CHARACTER*20 NAME
LOGICAL FLAG
DOUBLE PRECISION X
C Constants in FORTRAN using PARAMETER
REAL PI
PARAMETER (PI = 3.14159)
INTEGER MAX
PARAMETER (MAX = 100)
C Implicit typing (FORTRAN default):
C Variables starting with I-N are INTEGER
C All others are REAL (unless declared otherwise)
| Feature | C | FORTRAN |
|---|---|---|
| Variable declaration | int x; float y; | INTEGER X / REAL Y |
| Constant definition | #define or const | PARAMETER statement |
| Implicit typing | Not supported | Supported (I–N = INTEGER) |
| Case sensitivity | Case-sensitive | Case-insensitive |
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else if (condition3) {
// block 3
} else {
// default block
}
do {
// loop body (executes at least once)
} while (condition);
#include <stdio.h>
int main() {
int rows; // Total number of rows
int i, j, s;
printf ("Enter the number of rows: ");
scanf ("%d",&rows);
for (i = 1; i <= rows; i++) {
// 1. Print leading spaces for right alignment
// Each number + space takes roughly 3-4 characters
for (s = 1; s <= (rows - i); s++) {
printf(" ");
}
// 2. Print the multiples of i
for (j = 1; j <= i; j++) {
// %3d ensures each number takes up 3 spaces for alignment
printf("%4d", i * j);
}
// 3. Move to the next line
printf("\n");
}
return 0;
}
#include <stdio.h>
int power(int x, int y) {
if (y == 0)
return 1; // base case: x^0 = 1
return x * power(x, y - 1); // recursive case
}
int main() {
int x, y;
printf("Enter base (x): ");
scanf("%d", &x);
printf("Enter exponent (y): ");
scanf("%d", &y);
printf("%d ^ %d = %d\n", x, y, power(x, y));
return 0;
}
Enter base (x): 2
Enter exponent (y): 5
2 ^ 5 = 32
The recursive function uses two rules:
y == 0, return 1 (any number to the power 0 is 1). This stops the recursion.power(x, y) = x * power(x, y-1). The function calls itself with a reduced exponent each time.power(2, 5)
= 2 * power(2, 4)
= 2 * 2 * power(2, 3)
= 2 * 2 * 2 * power(2, 2)
= 2 * 2 * 2 * 2 * power(2, 1)
= 2 * 2 * 2 * 2 * 2 * power(2, 0)
= 2 * 2 * 2 * 2 * 2 * 1
= 32
Each call is pushed onto the call stack until the base case is reached, after which values are returned and multiplied as the stack unwinds.
Both functions are defined in <ctype.h> and operate on individual characters.
| Function | Syntax | Description |
|---|---|---|
| toupper() | int toupper(int c) | Converts a lowercase letter to uppercase. If the character is not a lowercase letter, it is returned unchanged. |
| tolower() | int tolower(int c) | Converts an uppercase letter to lowercase. If the character is not uppercase, it is returned unchanged. |
#include <ctype.h>
char c = 'a';
printf("%c", toupper(c)); // Output: A
char d = 'Z';
printf("%c", tolower(d)); // Output: z
#include <stdio.h>
#include <string.h>
int main() {
int n, i, j;
char countries[50][50], temp[50];
printf("Enter number of countries: ");
scanf("%d", &n);
printf("Enter country names:\n");
for (i = 0; i < n; i++) {
printf("Country %d: ", i + 1);
scanf("%s", countries[i]);
}
// Bubble sort alphabetically
for (i = 0; i < n - 1; i++)
for (j = 0; j < n - i - 1; j++)
if (strcmp(countries[j], countries[j + 1]) > 0) {
strcpy(temp, countries[j]);
strcpy(countries[j], countries[j + 1]);
strcpy(countries[j + 1], temp);
}
printf("\nCountries in alphabetical order:\n");
for (i = 0; i < n; i++)
printf("%s\n", countries[i]);
return 0;
}
Enter number of countries: 4
Country 1: Nepal
Country 2: India
Country 3: China
Country 4: Bhutan
Countries in alphabetical order:
Bhutan
China
India
Nepal
A pointer is declared by placing an asterisk (*) before the variable name. The data type specifies what type of variable the pointer will point to.
data_type *pointer_name;
int *p; // pointer to integer
float *fp; // pointer to float
char *cp; // pointer to character
double *dp; // pointer to double
A pointer is initialized by assigning it the address of a variable using the address-of operator (&). A pointer should never be used without initialization (it would be a dangling/wild pointer).
int a = 10;
int *p = &a; // p now holds address of a
printf("%d", a); // prints value: 10
printf("%u", p); // prints address: e.g. 1000
printf("%d", *p); // dereference: prints value 10
*p = 25; // changes a to 25 via pointer
printf("%d", a); // prints: 25
// NULL pointer (safe initialization when no target yet)
int *ptr = NULL;
Arithmetic on pointers moves the pointer by multiples of the size of the data type it points to.
| Operation | Effect (int pointer, 4 bytes) |
|---|---|
| ptr++ | Address increases by 4 (moves to next int) |
| ptr-- | Address decreases by 4 (moves to previous int) |
| ptr + n | Address increases by n × 4 |
| ptr - n | Address decreases by n × 4 |
| ptr1 - ptr2 | Number of elements between two pointers |
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("%d\n", *ptr); // 10 (address 1000)
ptr++;
printf("%d\n", *ptr); // 20 (address 1004)
ptr += 2;
printf("%d\n", *ptr); // 40 (address 1012)
return 0;
}
Note: Multiplication, division, and addition of two pointers are not valid pointer operations.
#include <stdio.h>
#include <string.h>
#define MAX 10 /* Use 40000 in real case; reduced for demo */
struct karmachari {
long ID_Number;
char Name[50];
float salary;
};
struct karmachari emp[MAX];
void search(int n, float target) {
int i, found = 0;
printf("\nRecords with salary = %.2f:\n", target);
printf("%-12s %-20s %-10s\n", "ID Number", "Name", "Salary");
printf("------------------------------------------\n");
for (i = 0; i < n; i++) {
if (emp[i].salary == target) {
printf("%-12ld %-20s %-10.2f\n",
emp[i].ID_Number,
emp[i].Name,
emp[i].salary);
found = 1;
}
}
if (!found)
printf("No records found with that salary.\n");
}
int main() {
int n, i;
float searchSal;
printf("Enter number of employees (max %d): ", MAX);
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEmployee %d:\n", i + 1);
printf("ID Number (6-digit): ");
scanf("%ld", &emp[i].ID_Number);
printf("Name: ");
scanf("%s", emp[i].Name);
printf("Salary: ");
scanf("%f", &emp[i].salary);
}
printf("\nEnter salary to search: ");
scanf("%f", &searchSal);
search(n, searchSal);
return 0;
}
Enter number of employees (max 10): 3
Employee 1:
ID Number (6-digit): 100001
Name: RamBahadur
Salary: 45000
Employee 2:
ID Number (6-digit): 100002
Name: SitaDevi
Salary: 62000
Employee 3:
ID Number (6-digit): 100003
Name: HariPrasad
Salary: 45000
Enter salary to search: 45000
Records with salary = 45000.00:
ID Number Name Salary
------------------------------------------
100001 RamBahadur 45000.00
100003 HariPrasad 45000.00
Note: In a 16-bit compiler (Turbo C), int is 2 bytes so long is used for 6-digit IDs. For 40,000 records, set #define MAX 40000.
#include <stdio.h>
int isPrime(int n) {
int i;
if (n < 2) return 0;
for (i = 2; i <= n / 2; i++)
if (n % i == 0) return 0;
return 1;
}
int main() {
int n1, n2, i;
char ch;
FILE *src, *dest;
printf("Enter range n1 and n2: ");
scanf("%d %d", &n1, &n2);
/* Step 1: Write primes to Source file */
src = fopen("Source.txt", "w");
if (src == NULL) {
printf("Error creating Source file.\n");
return 1;
}
for (i = n1; i <= n2; i++)
if (isPrime(i))
fprintf(src, "%d\n", i);
fclose(src);
printf("Prime numbers written to Source.txt\n");
/* Step 2: Copy Source to Destination */
src = fopen("Source.txt", "r");
dest = fopen("Destination.txt", "w");
if (src == NULL || dest == NULL) {
printf("Error opening files.\n");
return 1;
}
while ((ch = fgetc(src)) != EOF)
fputc(ch, dest);
fclose(src);
fclose(dest);
printf("Content copied to Destination.txt\n");
/* Step 3: Display Destination file */
dest = fopen("Destination.txt", "r");
if (dest == NULL) {
printf("Error opening Destination file.\n");
return 1;
}
printf("\nContents of Destination.txt:\n");
while ((ch = fgetc(dest)) != EOF)
putchar(ch);
fclose(dest);
return 0;
}
Enter range n1 and n2: 10 30
Prime numbers written to Source.txt
Content copied to Destination.txt
Contents of Destination.txt:
11
13
17
19
23
29
PROGRAM FIBONACCI
INTEGER N, I, A, B, TEMP
WRITE(*,*) 'Enter the number of terms:'
READ(*,*) N
A = 0
B = 1
WRITE(*,*) 'Fibonacci sequence:'
DO 10 I = 1, N
WRITE(*,100) A
TEMP = A + B
A = B
B = TEMP
10 CONTINUE
100 FORMAT(I5)
STOP
END
Fibonacci sequence:
0
1
1
2
3
5
8
13
| Basis | switch Statement | User Defined Function |
|---|---|---|
| Purpose | Multi-way branching based on a single integer/char expression | A reusable block of code performing a specific task |
| Reusability | Not reusable; executes inline | Can be called multiple times from anywhere |
| Return value | Does not return a value | Can return a value using return statement |
| Parameters | No parameters | Can accept arguments |
| Complexity | Suitable for simple selection logic | Suitable for complex, repeatable tasks |
| Example use | Menu selection, day names | Sorting, factorial, searching |
// switch example
switch (day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
default: printf("Other");
}
// User defined function example
int add(int a, int b) { return a + b; }
result = add(3, 5);
#include <stdio.h>
#define MAX 10
void transpose(int a[][MAX], int t[][MAX], int n) {
int i, j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
t[j][i] = a[i][j];
}
void printMatrix(int m[][MAX], int n) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
printf("%4d", m[i][j]);
printf("\n");
}
}
int main() {
int a[MAX][MAX], t[MAX][MAX], n, i, j;
printf("Enter size of matrix (N): ");
scanf("%d", &n);
printf("Enter %dx%d matrix elements:\n", n, n);
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
transpose(a, t, n);
printf("\nOriginal Matrix:\n");
printMatrix(a, n);
printf("\nTranspose Matrix:\n");
printMatrix(t, n);
return 0;
}
Enter size of matrix (N): 3
Enter 3x3 matrix elements:
1 2 3
4 5 6
7 8 9
Original Matrix:
1 2 3
4 5 6
7 8 9
Transpose Matrix:
1 4 7
2 5 8
3 6 9
| Generation | Name | Description | Example |
|---|---|---|---|
| 1GL | Machine Language | Binary instructions (0s and 1s) directly executed by CPU. Machine-dependent, fastest but hardest to write. | 10110000 01100001 |
| 2GL | Assembly Language | Uses mnemonics instead of binary. Requires an assembler. Still hardware-dependent. | MOV AX, 01H |
| 3GL | High-Level Language | English-like syntax, machine-independent. Requires compiler or interpreter. | C, C++, Java, FORTRAN |
| 4GL | Very High-Level Language | Closer to human language. Handles database queries and reports with less code. | SQL, MATLAB, Python |
| 5GL | Natural / AI Language | Uses constraints and logic; programmer defines what to solve, not how. | Prolog, LISP |
| Data Type | Size (32-bit) | Range | Example |
|---|---|---|---|
| int | 4 bytes | -2,147,483,648 to 2,147,483,647 | int age = 20; |
| float | 4 bytes | 3.4E-38 to 3.4E+38 (~6 decimal digits) | float pi = 3.14; |
| double | 8 bytes | 1.7E-308 to 1.7E+308 (~15 decimal digits) | double x = 3.14159; |
| char | 1 byte | -128 to 127 (or 0–255 unsigned) | char c = 'A'; |
| void | 0 bytes | No value | void main() |
Precedence determines the order in which operators are evaluated. Higher precedence operators are evaluated first.
int x = 2 + 3 * 4;
// * has higher precedence than +
// Evaluated as 2 + (3*4) = 14, NOT (2+3)*4 = 20
When operators have equal precedence, associativity decides the direction of evaluation.
// Left-to-right (most operators):
int x = 10 - 3 - 2; // = (10-3)-2 = 5
// Right-to-left (assignment, unary):
int a, b, c;
a = b = c = 5; // c=5, then b=5, then a=5
void main()
{
int n=90;
printf("%10d\n",n);
printf("%-2d\n",n);
printf("%c\n",'A');
printf("%-10d\n",n);
getch();
}void main() {
int n = 90;
printf("%10d\n", n); // right-justify in 10-char field
printf("%-2d\n", n); // left-justify in min 2-char field
printf("%c\n", 'A'); // print character A
printf("%-10d\n", n); // left-justify in 10-char field
getch();
}
90
90
A
90
| Statement | Explanation | Output |
|---|---|---|
| printf("%10d\n", n) | Right-justify 90 in width 10 → 8 spaces then "90" | " 90" |
| printf("%-2d\n", n) | Left-justify in min width 2; "90" is 2 chars so no padding | "90" |
| printf("%c\n", 'A') | %c prints character 'A' | "A" |
| printf("%-10d\n", n) | Left-justify 90 in width 10 → "90" then 8 spaces | "90 " |
| Basis | else-if Ladder | switch Statement |
|---|---|---|
| Expression type | Any relational or logical expression | Only integer or character constant |
| Condition | Can test ranges and complex conditions | Tests equality to constant values only |
| Readability | Harder to read with many conditions | Cleaner for discrete constant values |
| Fall-through | No fall-through | Fall-through occurs without break |
| Default | Final else block | default case |
| Float support | Yes | No |
| Speed | Evaluates each condition sequentially | Faster with jump table for many cases |
#include <stdio.h>
int main() {
int n, original, reversed = 0, remainder, temp;
printf("Enter a number: ");
scanf("%d", &n);
original = n;
temp = n;
while (temp != 0) {
remainder = temp % 10;
reversed = reversed * 10 + remainder;
temp = temp / 10;
}
if (original == reversed)
printf("%d is a Palindrome number.\n", original);
else
printf("%d is NOT a Palindrome number.\n", original);
return 0;
}
Enter a number: 12321
12321 is a Palindrome number.
Enter a number: 12345
12345 is NOT a Palindrome number.
// 1D Array prototype:
return_type functionName(data_type arrayName[], int size);
// or equivalently using pointer:
return_type functionName(data_type *arrayName, int size);
// Example:
void display(int arr[], int n);
// 2D Array prototype (column size MUST be specified):
return_type functionName(data_type arrayName[][COLS], int rows, int cols);
// Example:
void printMatrix(int mat[][10], int rows, int cols);
#include <stdio.h>
#define MAX 10
void colSum(int mat[][MAX], int result[], int rows, int cols) {
int i, j;
for (j = 0; j < cols; j++) {
result[j] = 0;
for (i = 0; i < rows; i++)
result[j] += mat[i][j];
}
}
int main() {
int mat[MAX][MAX], result[MAX];
int rows, cols, i, j;
printf("Enter rows and columns: ");
scanf("%d %d", &rows, &cols);
printf("Enter matrix elements:\n");
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++) {
printf("mat[%d][%d]: ", i, j);
scanf("%d", &mat[i][j]);
}
colSum(mat, result, rows, cols);
printf("\nColumn sums:\n");
for (j = 0; j < cols; j++)
printf("Column %d sum = %d\n", j + 1, result[j]);
return 0;
}
Enter rows and columns: 2 3
mat[0][0]: 1 mat[0][1]: 2 mat[0][2]: 3
mat[1][0]: 4 mat[1][1]: 5 mat[1][2]: 6
Column sums:
Column 1 sum = 5
Column 2 sum = 7
Column 3 sum = 9
#include <stdio.h>
struct Student {
char name[50];
long roll; /* long for 6-digit roll in 16-bit compiler */
float marks[5];
float total;
float percentage;
};
int main() {
int n, i, j;
struct Student s[50];
printf("Enter number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Name: ");
scanf("%s", s[i].name);
printf("Roll Number (6-digit): ");
scanf("%ld", &s[i].roll);
s[i].total = 0;
for (j = 0; j < 5; j++) {
printf("Marks in Subject %d: ", j + 1);
scanf("%f", &s[i].marks[j]);
s[i].total += s[i].marks[j];
}
s[i].percentage = s[i].total / 5.0;
}
printf("\n%-15s %-10s", "Name", "Roll");
for (j = 0; j < 5; j++) printf(" Sub%d", j + 1);
printf(" %8s %10s\n", "Total", "Percentage");
printf("---------------------------------------------------------------\n");
for (i = 0; i < n; i++) {
printf("%-15s %-10ld", s[i].name, s[i].roll);
for (j = 0; j < 5; j++) printf(" %4.1f", s[i].marks[j]);
printf(" %8.2f %9.2f%%\n", s[i].total, s[i].percentage);
}
return 0;
}
Name Roll Sub1 Sub2 Sub3 Sub4 Sub5 Total Percentage
---------------------------------------------------------------
RamSharma 100001 75.0 80.0 65.0 90.0 70.0 380.00 76.00%
SitaDevi 100002 88.0 72.0 91.0 85.0 78.0 414.00 82.80%
Note: In a 16-bit compiler (Turbo C), int is 2 bytes (max 32767), so long is used for 6-digit roll numbers. For 32-bit compilers, int suffices.
| Feature | Call by Value | Call by Reference |
|---|---|---|
| What is passed | A copy of the actual value | The address of the variable |
| Original affected? | No — changes stay local | Yes — changes reflect in caller |
| Memory | Extra memory for copy | No extra copy; same memory used |
| Safety | Safer; no side effects | Risk of unintended modification |
| Syntax | void f(int x) | void f(int *x) |
// Call by Value — original unchanged
void sqVal(int x) {
x = x * x;
printf("Inside: %d\n", x);
}
int main() {
int a = 5;
sqVal(a);
printf("Outside: %d\n", a); // still 5
}
// Call by Reference — original modified
void sqRef(int *x) {
*x = (*x) * (*x);
printf("Inside: %d\n", *x);
}
int main() {
int a = 5;
sqRef(&a);
printf("Outside: %d\n", a); // now 25
}
| Variable | Value Stored | Address |
|---|---|---|
| a | 10 | 6422296 |
| ptr1 | 6422296 (address of a) | 6422292 |
| ptr2 | 6422292 (address of ptr1) | 6422280 |
#include <stdio.h>
int main() {
int a = 10, *ptr1, **ptr2;
ptr1 = &a;
ptr2 = &ptr1;
printf("%d\t%d\n", &a, &a);
// &a = 6422296 &a = 6422296
// Output: 6422296 6422296
printf("%d\t%d\n", &ptr1, ptr1);
// &ptr1 = 6422292 ptr1 = 6422296
// Output: 6422292 6422296
printf("%d\t%d\n", *ptr1, *ptr2);
// *ptr1 = value at 6422296 = 10
// *ptr2 = value at 6422292 = 6422296 (address of a)
// Output: 10 6422296
**ptr2 = 20;
// *ptr2 = ptr1, *ptr1 = a → a becomes 20
printf("%d", a);
// Output: 20
return 0;
}
6422296 6422296
6422292 6422296
10 6422296
20
Note: The original question uses &&a which is invalid in standard C. The correct interpretation based on the table given is that the first printf prints &a and &a (address of a) twice. The output above reflects that correction.
C provides built-in string functions through <string.h> that operate on null-terminated character arrays.
| Function | Syntax | Description |
|---|---|---|
| strlen() | int strlen(char *s) | Returns length of string (excluding '\0') |
| strcpy() | char* strcpy(char *dest, char *src) | Copies src string into dest |
| strcat() | char* strcat(char *dest, char *src) | Appends src to end of dest |
| strcmp() | int strcmp(char *s1, char *s2) | Compares two strings; returns 0 if equal |
| strupr() | char* strupr(char *s) | Converts string to uppercase |
| strlwr() | char* strlwr(char *s) | Converts string to lowercase |
| strrev() | char* strrev(char *s) | Reverses a string |
#include <stdio.h>
int main() {
char s1[100], s2[50];
int i = 0, j = 0;
printf("Enter first string: ");
scanf("%s", s1);
printf("Enter second string: ");
scanf("%s", s2);
// Find end of s1
while (s1[i] != '\0')
i++;
// Append characters of s2 to s1
while (s2[j] != '\0') {
s1[i] = s2[j];
i++;
j++;
}
s1[i] = '\0'; // null-terminate
printf("Concatenated string: %s\n", s1);
return 0;
}
Enter first string: Hello
Enter second string: World
Concatenated string: HelloWorld
#include <stdio.h>
#include <string.h>
struct Book {
char name[100];
float price;
char author[50];
};
int main() {
struct Book b, b2;
FILE *fp;
/* Read record from user */
printf("Enter book name: ");
scanf(" %[^\n]", b.name);
printf("Enter price: ");
scanf("%f", &b.price);
printf("Enter author name: ");
scanf(" %[^\n]", b.author);
/* Write to book.txt */
fp = fopen("book.txt", "w");
if (fp == NULL) {
printf("Error creating file.\n");
return 1;
}
fprintf(fp, "%s\n%.2f\n%s\n", b.name, b.price, b.author);
fclose(fp);
printf("Record saved to book.txt\n");
/* Read back from book.txt */
fp = fopen("book.txt", "r");
if (fp == NULL) {
printf("Error reading file.\n");
return 1;
}
fgets(b2.name, sizeof(b2.name), fp);
fscanf(fp, "%f\n", &b2.price);
fgets(b2.author, sizeof(b2.author), fp);
fclose(fp);
/* Remove trailing newlines */
b2.name[strcspn(b2.name, "\n")] = '\0';
b2.author[strcspn(b2.author, "\n")] = '\0';
printf("\n--- Book Details from book.txt ---\n");
printf("Name : %s\n", b2.name);
printf("Price : %.2f\n", b2.price);
printf("Author : %s\n", b2.author);
return 0;
}
Enter book name: Computer Programming
Enter price: 550.00
Enter author name: Yashavant Kanetkar
Record saved to book.txt
--- Book Details from book.txt ---
Name : Computer Programming
Price : 550.00
Author : Yashavant Kanetkar
| Type | Construct | Description |
|---|---|---|
| Conditional | if, if-else, else-if | Executes block based on condition |
| Multi-way | switch-case | Selects branch based on integer/char value |
| Loop | for | Counter-controlled pre-test loop |
| Loop | while | Condition-controlled pre-test loop |
| Loop | do-while | Post-test loop (executes at least once) |
| Jump | break / continue | Exit loop / skip to next iteration |
| Jump | goto | Unconditional jump to a label |
// C example:
for (i = 1; i <= 5; i++) printf("%d ", i);
if (x > 0) printf("Positive"); else printf("Non-positive");
| Type | Construct | Description |
|---|---|---|
| Conditional | Logical IF | Single-line conditional execution |
| Conditional | IF-THEN-ELSE-END IF | Block conditional (FORTRAN 77+) |
| Conditional | Arithmetic IF | Three-way branch: negative/zero/positive |
| Multi-way | IF-ELSE IF ladder | Multiple conditions (no switch available) |
| Loop | DO loop | Counter-controlled loop with labels |
| Loop | DO WHILE | Condition-controlled loop (FORTRAN 77+) |
| Jump | GO TO / Computed GO TO | Unconditional / indexed jump |
C FORTRAN example:
DO 10 I = 1, 5
WRITE(*,*) I
10 CONTINUE
IF (X .GT. 0) THEN
WRITE(*,*) 'Positive'
END IF
| Feature | C | FORTRAN |
|---|---|---|
| Switch/Multi-way | switch-case available | No switch; uses IF-ELSE IF ladder |
| Loop types | for, while, do-while | DO loop, DO WHILE only |
| Loop control | break, continue | No direct equivalent in FORTRAN 77 |
| Condition operators | ==, !=, >, < | .EQ., .NE., .GT., .LT., .GE., .LE. |
| Arithmetic IF | Not available | Unique 3-way branch statement |
PROGRAM SORT100
INTEGER A(100), N, I, J, TEMP
N = 100
C Read 100 numbers from user
WRITE(*,*) 'Enter 100 numbers:'
DO 10 I = 1, N
READ(*,*) A(I)
10 CONTINUE
C Bubble Sort — ascending order
DO 30 I = 1, N - 1
DO 20 J = 1, N - I
IF (A(J) .GT. A(J + 1)) THEN
TEMP = A(J)
A(J) = A(J + 1)
A(J + 1) = TEMP
END IF
20 CONTINUE
30 CONTINUE
C Display sorted array
WRITE(*,*) 'Sorted numbers in ascending order:'
DO 40 I = 1, N
WRITE(*,100) A(I)
40 CONTINUE
100 FORMAT(I6)
STOP
END
The outer DO loop (label 30) runs N−1 passes. The inner DO loop (label 20) compares adjacent elements A(J) and A(J+1) and swaps them if A(J) > A(J+1). After each pass, the largest unsorted element rises to its correct final position. After N−1 passes the entire array is sorted in ascending order.
| Basis | System Software | Application Software |
|---|---|---|
| Definition | Software that manages hardware resources and provides a platform for running other software | Software designed to perform specific tasks directly for the end user |
| Purpose | Controls and coordinates computer hardware | Fulfills specific user needs or tasks |
| Interaction | Interacts directly with hardware | Interacts through system software |
| Dependency | Can run independently | Depends on system software to run |
| User interaction | Minimal direct user interaction | Designed primarily for user interaction |
| Examples | Windows, Linux, macOS, Compilers, Device Drivers, BIOS | MS Word, Chrome, VLC, Photoshop, Games |
| Development | Written in low-level or system languages (C, Assembly) | Written in high-level languages (C, Java, Python) |
| Step | Tool | Input | Output | Description |
|---|---|---|---|---|
| 1. Pre-processing | Preprocessor (cpp) | program.c | program.i | Expands #include, #define macros; removes comments; processes conditional directives |
| 2. Compilation | Compiler (cc1) | program.i | program.s | Translates C code to assembly language; performs syntax and semantic checks; reports errors |
| 3. Assembly | Assembler (as) | program.s | program.o | Converts assembly instructions to machine code (object file); not yet executable |
| 4. Linking | Linker (ld) | program.o + libraries | program.exe / a.out | Combines object file(s) with standard library files; resolves external references; produces final executable |
| 5. Loading | OS Loader | program.exe | Running process | Loads executable into RAM; allocates memory; begins execution at main() |
Source (.c)
→ Preprocessor → .i (expanded source)
→ Compiler → .s (assembly code)
→ Assembler → .o (object / machine code)
→ Linker → .exe / a.out (executable)
→ Loader → Running program in memory
| Basis | Variable | Constant |
|---|---|---|
| Definition | A named memory location whose value can change during execution | A fixed value that cannot be changed once defined |
| Value | Can be modified at any point in the program | Remains fixed throughout program execution |
| Declaration | int x = 5; (value can be reassigned) | const int X = 5; or #define X 5 |
| Memory | Allocated in RAM; value stored and can be overwritten | #define: no memory; const: stored in read-only area |
| Purpose | Stores values that change (e.g., counters, inputs) | Stores fixed values (e.g., PI, MAX_SIZE) |
int count = 0; // variable — can change
count = count + 1; // valid
const float PI = 3.14; // constant
PI = 3.15; // ERROR: cannot modify a constant
#define MAX 100 // macro constant
#include <stdio.h>
#define PI 3.14159
int main() {
int d;
float area;
printf("Enter the radius of the circular ground (in meters): ");
scanf("%d", &d);
area = PI * d * d;
printf("Area of the circular ground = %.2f square meters\n", area);
return 0;
}
Enter the radius of the circular ground (in meters): 7
Area of the circular ground = 153.94 square meters
Formula used: Area = π × r² where r = d (radius).
Formatted I/O functions in C allow reading and writing data in a specific, human-readable format using format specifiers (e.g., %d, %f, %s). They are defined in <stdio.h>.
Displays formatted output to the standard output (screen).
Syntax: int printf(const char *format, arg1, arg2, ...);
Example:
int age = 20;
float gpa = 3.85;
char name[] = "Ram";
printf("Name: %s, Age: %d, GPA: %.2f\n", name, age, gpa);
// Output: Name: Ram, Age: 20, GPA: 3.85
// Width and alignment:
printf("%10d\n", 42); // Output: " 42" (right-justified)
printf("%-10d\n", 42); // Output: "42 " (left-justified)
printf("%08.2f\n", 3.14);// Output: "00003.14" (zero-padded)
Reads formatted input from the standard input (keyboard). The address-of operator (&) must be used for all variables except strings.
Syntax: int scanf(const char *format, &arg1, &arg2, ...);
Example:
int n;
float x;
char name[50];
printf("Enter name, integer and float: ");
scanf("%s %d %f", name, &n, &x);
printf("Name=%s, n=%d, x=%.2f\n", name, n, x);
// scanf returns the number of successfully read items
// Returns EOF on end of file or error
| Specifier | Data Type | Example |
|---|---|---|
| %d or %i | int | printf("%d", 42); |
| %f | float / double | printf("%.2f", 3.14); |
| %c | char | printf("%c", 'A'); |
| %s | string (char array) | printf("%s", "Hello"); |
| %lf | double (in scanf) | scanf("%lf", &x); |
| %ld | long int | printf("%ld", 1000000L); |
| %e | Scientific notation | printf("%e", 12345.6); |
| %o | Octal | printf("%o", 8); |
| %x | Hexadecimal | printf("%x", 255); |
| Basis | Library Function | User Defined Function |
|---|---|---|
| Definition | Pre-written functions provided by C standard libraries | Functions written by the programmer for specific tasks |
| Availability | Available by including appropriate header files | Must be declared, defined, and called by programmer |
| Code visibility | Source code not visible; only declaration in header | Full source code written and visible |
| Modification | Cannot be modified | Can be modified as needed |
| Header required | Yes (#include <stdio.h>, <math.h>, etc.) | No special header; prototype declared by user |
| Examples | printf(), scanf(), sqrt(), strlen(), pow() | int add(int a, int b), void display() |
// Library function:
#include <math.h>
double result = sqrt(25.0); // returns 5.0
// User defined function:
int add(int a, int b) {
return a + b;
}
int sum = add(3, 4); // returns 7
A function prototype is a declaration of a function that informs the compiler about the function's name, return type, and parameter types before the function is actually defined. It enables forward referencing — calling a function before its full definition.
// Prototype syntax:
return_type function_name(param_type1, param_type2, ...);
// Example:
int add(int, int); // prototype
int main() {
printf("%d", add(3, 4)); // valid — compiler knows signature
}
int add(int a, int b) { return a + b; } // definition later
#include <stdio.h>
int sumN(int n) {
if (n == 0)
return 0; // base case
return n + sumN(n - 1); // recursive case
}
int main() {
int result = sumN(10);
printf("Sum of first 10 natural numbers = %d\n", result);
return 0;
}
Sum of first 10 natural numbers = 55
sumN(10) = 10 + sumN(9)
= 10 + 9 + sumN(8)
= 10 + 9 + 8 + ... + sumN(1)
= 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sumN(0)
= 10 + 9 + ... + 1 + 0 = 55
#include <stdio.h>
#define N 48
int main() {
float marks[N];
float highest, second;
int i;
printf("Enter marks of %d students:\n", N);
for (i = 0; i < N; i++) {
printf("Student %d: ", i + 1);
scanf("%f", &marks[i]);
}
/* Initialize highest and second highest */
if (marks[0] > marks[1]) {
highest = marks[0];
second = marks[1];
} else {
highest = marks[1];
second = marks[0];
}
/* Find highest and second highest */
for (i = 2; i < N; i++) {
if (marks[i] > highest) {
second = highest;
highest = marks[i];
} else if (marks[i] > second && marks[i] != highest) {
second = marks[i];
}
}
printf("\nHighest mark = %.2f\n", highest);
printf("Second highest mark = %.2f\n", second);
return 0;
}
Enter marks of 48 students:
Student 1: 78
Student 2: 95
...
Student 48: 88
Highest mark = 98.00
Second highest mark = 95.00
To copy a string manually, we traverse the source string character by character and copy each character to the destination string until the null terminator '\0' is reached, then append '\0' to the destination.
#include <stdio.h>
int main() {
char source[100], dest[100];
int i = 0;
printf("Enter a string to copy: ");
scanf("%s", source);
/* Copy character by character */
while (source[i] != '\0') {
dest[i] = source[i];
i++;
}
dest[i] = '\0'; /* null-terminate the destination */
printf("Source string : %s\n", source);
printf("Destination string : %s\n", dest);
return 0;
}
Enter a string to copy: KATHMANDU
Source string : KATHMANDU
Destination string : KATHMANDU
The loop runs until source[i] == '\0'. Each character at index i is copied to dest[i]. Finally, dest[i] = '\0' ensures the destination is properly null-terminated.
An array of structure is a collection where each element of the array is a structure variable. It is used to store multiple records of the same type (e.g., 48 students). It combines the power of arrays (multiple elements) with structures (grouped, heterogeneous data).
struct Student s[48]; // array of 48 Student structure variables
// Access: s[0].roll, s[1].name, s[i].marks, etc.
#include <stdio.h>
#define N 48
struct Student {
int roll;
char name[50];
char address[100];
float marks;
};
int main() {
struct Student s[N];
int i, found = 0;
/* Read data for all students */
for (i = 0; i < N; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Roll : "); scanf("%d", &s[i].roll);
printf("Name : "); scanf("%s", s[i].name);
printf("Address : "); scanf("%s", s[i].address);
printf("Marks : "); scanf("%f", &s[i].marks);
}
/* Display students with marks between 50 and 70 */
printf("\n\nStudents with marks between 50 and 70:\n");
printf("%-6s %-15s %-20s %-8s\n", "Roll", "Name", "Address", "Marks");
printf("--------------------------------------------------\n");
for (i = 0; i < N; i++) {
if (s[i].marks >= 50 && s[i].marks <= 70) {
printf("%-6d %-15s %-20s %-8.2f\n",
s[i].roll, s[i].name, s[i].address, s[i].marks);
found = 1;
}
}
if (!found)
printf("No students found with marks between 50 and 70.\n");
return 0;
}
Students with marks between 50 and 70:
Roll Name Address Marks
--------------------------------------------------
3 RamBahadur Kathmandu 65.00
7 SitaDevi Pokhara 58.50
12 HariPrasad Lalitpur 70.00
Pointer arithmetic involves performing arithmetic operations on pointer variables. Since a pointer stores a memory address, arithmetic on it moves the pointer by multiples of the size of the data type it points to.
| Operation | Effect (for int*, size=4 bytes) |
|---|---|
| ptr++ | Address increases by 4 (next int) |
| ptr-- | Address decreases by 4 (previous int) |
| ptr + n | Address increases by n × 4 |
| ptr - n | Address decreases by n × 4 |
| ptr1 - ptr2 | Number of elements between two pointers |
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // points to arr[0]
printf("%d\n", *ptr); // 10 (address: 1000)
ptr++;
printf("%d\n", *ptr); // 20 (address: 1004)
ptr += 2;
printf("%d\n", *ptr); // 40 (address: 1012)
return 0;
}
#include <stdio.h>
#define MAX 10
void transpose(int (*mat)[MAX], int (*trans)[MAX], int m, int n) {
int i, j;
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
*(*(trans + j) + i) = *(*(mat + i) + j);
}
void printMatrix(int (*mat)[MAX], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%4d", *(*(mat + i) + j));
printf("\n");
}
}
int main() {
int mat[MAX][MAX], trans[MAX][MAX];
int m, n, i, j;
printf("Enter rows (m) and columns (n): ");
scanf("%d %d", &m, &n);
printf("Enter matrix elements:\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", *(mat + i) + j);
transpose(mat, trans, m, n);
printf("\nOriginal Matrix (%dx%d):\n", m, n);
printMatrix(mat, m, n);
printf("\nTranspose Matrix (%dx%d):\n", n, m);
printMatrix(trans, n, m);
return 0;
}
Enter rows (m) and columns (n): 2 3
Enter matrix elements:
1 2 3
4 5 6
Original Matrix (2x3):
1 2 3
4 5 6
Transpose Matrix (3x2):
1 4
2 5
3 6
| Basis | Text File | Binary File |
|---|---|---|
| Storage | Data stored as human-readable ASCII characters | Data stored in binary (0s and 1s) format |
| Readability | Can be opened in any text editor | Not human-readable; requires special program |
| Newline | '\n' translated to OS newline (e.g., \r\n) | No translation; stored exactly as-is |
| EOF | Marked by special EOF character (Ctrl+Z) | Determined by file size |
| Size | Larger (ASCII representation) | Compact and efficient |
| Open mode | "r", "w", "a" | "rb", "wb", "ab" |
| Example | .txt, .csv, .html | .exe, .jpg, .mp3, .dat |
Moves the file pointer to a specific position within a file.
Syntax: int fseek(FILE *fp, long offset, int origin);
Parameters:
fp — pointer to the FILE
offset — number of bytes to move from origin
origin — starting position:
SEEK_SET (0) — beginning of file
SEEK_CUR (1) — current position
SEEK_END (2) — end of file
Example:
fseek(fp, 0, SEEK_SET); // move to start of file
fseek(fp, 10, SEEK_CUR); // move 10 bytes forward from current
fseek(fp, -5, SEEK_END); // move 5 bytes before end of file
Resets the file pointer to the beginning of the file. Equivalent to fseek(fp, 0, SEEK_SET).
Syntax: void rewind(FILE *fp);
Example:
FILE *fp = fopen("data.txt", "r");
// ... read some data ...
rewind(fp); // go back to start to read again
// ... read from beginning again ...
#include <stdio.h>
#include <string.h>
#define N 3
struct Movie {
char name[100];
int year;
char language[30];
};
int main() {
struct Movie m[N];
int i, saved = 0;
FILE *fp;
/* Read movie data from user */
for (i = 0; i < N; i++) {
printf("\nMovie %d:\n", i + 1);
printf("Name : "); scanf(" %[^\n]", m[i].name);
printf("Year of Release: "); scanf("%d", &m[i].year);
printf("Language : "); scanf("%s", m[i].language);
}
/* Write English movies to file */
fp = fopen("english_movies.txt", "w");
if (fp == NULL) {
printf("Error creating file.\n");
return 1;
}
fprintf(fp, "%-30s %-6s %-15s\n", "Movie Name", "Year", "Language");
fprintf(fp, "---------------------------------------------\n");
for (i = 0; i < N; i++) {
/* Case-insensitive comparison using strcasecmp or manual check */
char lang[30];
int j;
for (j = 0; m[i].language[j]; j++)
lang[j] = (m[i].language[j] >= 'a') ?
m[i].language[j] - 32 : m[i].language[j];
lang[j] = '\0';
if (strcmp(lang, "ENGLISH") == 0) {
fprintf(fp, "%-30s %-6d %-15s\n",
m[i].name, m[i].year, m[i].language);
saved++;
}
}
fclose(fp);
if (saved > 0)
printf("\n%d English movie(s) saved to english_movies.txt\n", saved);
else
printf("\nNo English movies found.\n");
return 0;
}
Movie 1:
Name : Inception
Year of Release: 2010
Language : English
Movie 2:
Name : Devdas
Year of Release: 2002
Language : Hindi
Movie 3:
Name : Interstellar
Year of Release: 2014
Language : English
2 English movie(s) saved to english_movies.txt
Movie Name Year Language
---------------------------------------------
Inception 2010 English
Interstellar 2014 English
The FORMAT statement in FORTRAN controls the exact layout of input/output data. It specifies field widths, decimal places, spacing, and data types. It is referenced by a statement label in READ or WRITE statements.
WRITE(*,100) X
100 FORMAT(...) ! FORMAT referenced by label 100
Used for integer input/output. Syntax: Iw where w is the total field width.
INTEGER N
N = 42
WRITE(*,100) N
100 FORMAT(I5)
C Output: 42 (right-justified in 5-character field)
Used for real number input/output. Syntax: Fw.d where w is total field width and d is decimal places.
REAL X
X = 3.14159
WRITE(*,200) X
200 FORMAT(F8.3)
C Output: 3.142 (8 chars wide, 3 decimal places)
PROGRAM PRIME
INTEGER N, I, FLAG
WRITE(*,*) 'Enter a number:'
READ(*,*) N
FLAG = 0
IF (N .LE. 1) THEN
FLAG = 1
END IF
DO 10 I = 2, N / 2
IF (MOD(N, I) .EQ. 0) THEN
FLAG = 1
END IF
10 CONTINUE
IF (FLAG .EQ. 0) THEN
WRITE(*,100) N
100 FORMAT(I6, ' is a prime number.')
ELSE
WRITE(*,200) N
200 FORMAT(I6, ' is not a prime number.')
END IF
STOP
END
Enter a number:
7
7 is a prime number.
Enter a number:
9
9 is not a prime number.
A pre-test loop that checks the condition before executing the loop body. If the condition is false initially, the body never executes.
Syntax:
while (condition) {
// body
}
Example:
int i = 1;
while (i <= 5) {
printf("%d ", i); // prints: 1 2 3 4 5
i++;
}
A post-test loop that executes the body first and then checks the condition. The body always executes at least once.
Syntax:
do {
// body
} while (condition);
Example:
int i = 1;
do {
printf("%d ", i); // prints: 1 2 3 4 5
i++;
} while (i <= 5);
| Feature | while | do-while |
|---|---|---|
| Condition check | Before loop body (pre-test) | After loop body (post-test) |
| Minimum executions | 0 (may never run) | At least 1 |
| Semicolon | No semicolon after condition | Semicolon required after while(cond); |
In C, a string is a null-terminated character array (char str[]). C provides string manipulation functions through <string.h>.
| Function | Syntax | Purpose | Example |
|---|---|---|---|
| strlen() | int strlen(char *s) | Returns string length (excluding '\0') | strlen("Hello") → 5 |
| strcpy() | char* strcpy(char *d, char *s) | Copies source to destination | strcpy(d, "Hi") |
| strcat() | char* strcat(char *d, char *s) | Appends source to end of destination | strcat("Hello", " World") |
| strcmp() | int strcmp(char *s1, char *s2) | Compares two strings; 0 if equal | strcmp("abc", "abc") → 0 |
| strrev() | char* strrev(char *s) | Reverses the string in-place | strrev("Hello") → "olleH" |
| strupr() | char* strupr(char *s) | Converts to uppercase | strupr("hello") → "HELLO" |
| strlwr() | char* strlwr(char *s) | Converts to lowercase | strlwr("HELLO") → "hello" |
#include <stdio.h>
#include <string.h>
int main() {
char s1[50] = "Hello";
char s2[50] = "World";
printf("Length : %d\n", strlen(s1)); // 5
printf("Compare: %d\n", strcmp(s1, s2)); // negative (H < W)
strcat(s1, s2);
printf("Concat : %s\n", s1); // HelloWorld
return 0;
}
| Basis | System Software | Application Software |
|---|---|---|
| Definition | Software that manages hardware resources and provides a platform for running other software | Software designed to perform specific tasks for the end user |
| Purpose | Controls and coordinates hardware operations | Fulfills specific user needs |
| Interaction | Interacts directly with hardware | Interacts through system software |
| Dependency | Can run independently | Depends on system software to run |
| Development lang | Low-level: C, Assembly | High-level: Java, Python, C++ |
| User interaction | Minimal direct user interaction | Primarily designed for user interaction |
| Examples | Windows, Linux, macOS, Compilers, Device Drivers, BIOS | MS Word, Chrome, VLC, Photoshop, Games |
| Step | Description |
|---|---|
| 1. Problem Analysis | Clearly understand the problem, identify inputs, expected outputs, and constraints. |
| 2. Algorithm Design | Develop a step-by-step logical solution independent of any programming language. |
| 3. Flowchart | Draw a graphical representation of the algorithm using standard symbols. |
| 4. Coding | Translate the algorithm into a programming language (e.g., C, Python). |
| 5. Compilation | Convert source code to executable; compiler detects syntax errors. |
| 6. Testing & Debugging | Run the program with various inputs; locate and fix logical/runtime errors. |
| 7. Documentation | Write user manuals and add comments in code for future reference. |
| 8. Maintenance | Update and improve the software after deployment. |
A token is the smallest individual unit of a C program that is meaningful to the compiler. Every C program is made up of tokens.
| Token Type | Description | Example |
|---|---|---|
| Keywords | Reserved words with predefined meaning | int, float, if, while, return |
| Identifiers | Names given to variables, functions, arrays | count, sum, main, area |
| Constants | Fixed values that do not change | 10, 3.14, 'A', "Hello" |
| Strings | Sequence of characters in double quotes | "Nepal", "Hello World" |
| Operators | Symbols that perform operations | +, -, *, /, %, ==, && |
| Special Symbols | Punctuation and delimiters | { } ( ) [ ] ; , # |
In C, a variable can be made constant (read-only) using two methods:
// Method 1: const keyword
// Declares a typed constant; stored in memory but read-only
const float PI = 3.14159;
const int MAX = 100;
PI = 3.15; // ERROR: cannot modify a const variable
// Method 2: #define preprocessor directive
// Replaces identifier with value before compilation; no memory allocated
#define PI 3.14159
#define MAX 100
// Example program:
#include <stdio.h>
#define GRAVITY 9.8
int main() {
const int DAYS = 7;
printf("Gravity = %.1f m/s^2\n", GRAVITY);
printf("Days in a week = %d\n", DAYS);
return 0;
}
char str1[50],
str2[50] = {'N','E','P','A','L'};
scanf("%[A-Z]", str1);
printf("%s\n", str1);
printf("%.0.5s\n", str2);
printf("%.5.3s\n", str2);
printf("%-0.3s", str2);#include <stdio.h>
int main() {
char str1[50], str2[50] = {'N', 'E', 'P', 'A', 'L'};
scanf("%[A-Z]", str1);
// %[A-Z] reads only uppercase letters, stops at first non-uppercase
// Input: KATHmanDU → reads "KATH" (stops at 'm' which is lowercase)
printf("%s\n", str1); // Line 1
printf("%.0.5s\n", str2); // Line 2 — non-standard: prints nothing or compiler-specific
printf("%.5.3s\n", str2); // Line 3 — non-standard format
printf("%-0.3s", str2); // Line 4
return 0;
}
| Statement | Format Specifier | Explanation | Output |
|---|---|---|---|
| printf("%s\n", str1) | %s | Prints str1 which contains "KATH" (stops at lowercase 'm') | KATH |
| printf("%.0.5s\n", str2) | %.0.5s | Non-standard. Most compilers treat %.0s as print 0 chars of string → empty line | (empty) |
| printf("%.5.3s\n", str2) | %.5.3s | Non-standard. Last precision .3 applies → prints first 3 chars: "NEP" | NEP |
| printf("%-0.3s", str2) | %-0.3s | Left-justify, print max 3 chars → "NEP" left-aligned | NEP |
KATH
NEP
NEP
Note: %.0.5s and %.5.3s are non-standard format specifiers. Behavior may differ across compilers. In Turbo C / standard GCC, the last precision value typically takes effect.
| Statement | Action | Use case |
|---|---|---|
| break | Immediately terminates the nearest enclosing loop or switch and transfers control to the statement after it | Exit loop early when a condition is met |
| continue | Skips the remainder of the current loop iteration and jumps to the next iteration's condition check | Skip specific values without terminating the loop |
// break example: stop when i == 4
for (i = 1; i <= 10; i++) {
if (i == 4) break;
printf("%d ", i); // Output: 1 2 3
}
// continue example: skip even numbers
for (i = 1; i <= 6; i++) {
if (i % 2 == 0) continue;
printf("%d ", i); // Output: 1 3 5
}
#include <stdio.h>
#include <math.h>
int main() {
double x, term, cosine;
int n;
printf("Enter value of x (in radians): ");
scanf("%lf", &x);
cosine = 1.0; /* first term: x^0/0! = 1 */
term = 1.0;
n = 1;
while (1) {
/* Next term: multiply previous term by -x^2 / (2n)(2n-1) */
term = term * (-x * x) / ((2 * n) * (2 * n - 1));
if (fabs(term) < 1e-6)
break; /* stop when term is negligibly small */
cosine += term;
n++;
}
printf("cos(%.4lf) = %.6lf\n", x, cosine);
printf("Math library cos = %.6lf\n", cos(x));
return 0;
}
/* compile with: gcc program.c -lm */
Enter value of x (in radians): 1.0
cos(1.0000) = 0.540302
Math library cos = 0.540302
The break statement exits the infinite while(1) loop as soon as the absolute value of the current term drops below 10⁻⁶, ensuring sufficient precision.
Declares the function signature to the compiler before the function is defined or called.
Syntax: return_type function_name(param_type1, param_type2, ...);
Example: int add(int, int);
void display(void);
float area(float, float);
Contains the actual body of the function — the statements that execute when the function is called.
Syntax:
return_type function_name(param_type1 param1, param_type2 param2) {
// body
return value; /* omit if void */
}
Example:
int add(int a, int b) {
return a + b;
}
Invokes the function from main() or another function.
Syntax: variable = function_name(arg1, arg2, ...);
function_name(arg1, arg2); /* if void */
Example:
int result = add(3, 5); /* result = 8 */
display(); /* void function call */
Yes — in C, main() can technically be called recursively. Unlike C++, the C standard does not explicitly forbid it. However:
#include <stdio.h>
int count = 0;
int main() {
count++;
if (count < 3) {
printf("Call %d\n", count);
main(); // recursive call to main (legal in C)
}
return 0;
}
// Output: Call 1 Call 2
A recursive function is a function that calls itself during its execution. Every recursive function must have:
/* Factorial using recursion */
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) /* base case */
return 1;
return n * factorial(n - 1); /* recursive case */
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("%d! = %d\n", n, factorial(n));
return 0;
}
Enter a number: 5
5! = 120
factorial(5) = 5 * factorial(4)
= 5 * 4 * factorial(3)
= 5 * 4 * 3 * factorial(2)
= 5 * 4 * 3 * 2 * factorial(1)
= 5 * 4 * 3 * 2 * 1
= 120
Each call is pushed onto the call stack. When the base case n==1 is reached, values unwind back through the stack multiplying at each level.
| Basis | Array | String |
|---|---|---|
| Definition | A collection of elements of the same data type stored in contiguous memory | A character array terminated by a null character '\0' |
| Data type | Can be int, float, char, etc. | Always char type |
| Terminator | No special terminator | Must end with '\0' |
| Declaration | int a[5]; float b[10]; | char str[20]; or char str[] = "Hello"; |
| I/O | Element-by-element with scanf/printf | Entire string with %s or gets()/puts() |
| Functions | No special library | string.h: strlen, strcpy, strcat, etc. |
A multi-dimensional array is an array of arrays. The most common is the 2D array (matrix).
/* Declaration syntax */
data_type array_name[size1][size2]...[sizeN];
/* 2D Array declaration */
int mat[3][4]; /* 3 rows, 4 columns */
float grid[5][5];
/* Declaration with initialization */
int a[2][3] = { {1, 2, 3}, {4, 5, 6} };
/* Accessing elements */
a[0][0] = 1; a[0][1] = 2; a[1][2] = 6;
/* Reading and printing a 2D array */
#include <stdio.h>
int main() {
int mat[3][3], i, j;
printf("Enter 3x3 matrix:\n");
for (i = 0; i < 3; i++)
for (j = 0; j < 3; j++)
scanf("%d", &mat[i][j]);
printf("Matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++)
printf("%4d", mat[i][j]);
printf("\n");
}
return 0;
}
3D arrays can be declared as int cube[2][3][4]; and accessed as cube[i][j][k].
#include <stdio.h>
#include <string.h>
void sortDescending(char str[]) {
int len = strlen(str);
int i, j;
char temp;
/* Bubble sort in descending order */
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - i - 1; j++) {
if (str[j] < str[j + 1]) { /* swap if left < right */
temp = str[j];
str[j] = str[j + 1];
str[j + 1] = temp;
}
}
}
}
int main() {
char str[100];
printf("Enter a string: ");
scanf("%s", str);
sortDescending(str);
printf("Sorted in descending order: %s\n", str);
return 0;
}
Enter a string: exam
Sorted in descending order: xmea
Enter a string: Nepal
Sorted in descending order: plonea
Note: Sorting is based on ASCII values. Uppercase letters (65–90) have lower ASCII values than lowercase (97–122), so mixed-case strings sort uppercase after lowercase in descending order.
When declaring a pointer, the data type specifies the type of variable the pointer points to. It determines:
ptr++ on an int* advances by 4 bytes; on a char* by 1 byte.int *p; // p points to int; *p reads 4 bytes
char *c; // c points to char; *c reads 1 byte
float *f; // f points to float; *f reads 4 bytes
double *d; // d points to double; *d reads 8 bytes
void *v; // generic pointer — cannot be dereferenced directly
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x, y;
printf("Enter two integers: ");
scanf("%d %d", &x, &y);
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap : x = %d, y = %d\n", x, y);
return 0;
}
Enter two integers: 10 20
Before swap: x = 10, y = 20
After swap : x = 20, y = 10
#include <stdio.h>
int frequency(int *arr, int n, int key) {
int i, count = 0;
for (i = 0; i < n; i++) {
if (*(arr + i) == key) /* pointer notation */
count++;
}
return count;
}
int main() {
int arr[100], n, key, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
scanf("%d", arr + i); /* arr+i is address of arr[i] */
printf("Enter the number to search: ");
scanf("%d", &key);
int freq = frequency(arr, n, key);
printf("Frequency of %d = %d\n", key, freq);
return 0;
}
Enter number of elements: 6
Enter 6 elements:
3 5 3 7 3 8
Enter the number to search: 3
Frequency of 3 = 3
In C, the name of an array is a constant pointer to its first element. Therefore arr and &arr[0] hold the same address. The following equivalences always hold:
| Array notation | Pointer notation | Meaning |
|---|---|---|
| arr[i] | *(arr + i) | Value at index i |
| &arr[i] | arr + i | Address of element i |
| arr[0] | *arr | First element |
In the program above, arr + i is used in scanf and *(arr + i) in the comparison — both are equivalent to arr[i] and &arr[i] respectively.
Opens a file and returns a FILE pointer. Returns NULL if the file cannot be opened.
Syntax: FILE* fopen(const char *filename, const char *mode);
Modes:
"r" — open for reading (file must exist)
"w" — open for writing (creates new or truncates)
"a" — open for appending
"rb" — read binary
"wb" — write binary
Example:
FILE *fp = fopen("data.txt", "w");
if (fp == NULL) { printf("Error!"); }
Closes an open file, flushes the buffer, and releases the FILE pointer.
Syntax: int fclose(FILE *fp);
Returns 0 on success, EOF on failure.
Example: fclose(fp);
#include <stdio.h>
#include <string.h>
#define N 10
struct Book {
char name[100];
float price;
char author[50];
};
int main() {
struct Book b;
int i, found = 0;
FILE *fp, *fp2;
/* Step 1: Read N records and write to book.dat (binary) */
fp = fopen("book.dat", "wb");
if (fp == NULL) { printf("Error creating book.dat\n"); return 1; }
printf("Enter details of %d books:\n", N);
for (i = 0; i < N; i++) {
printf("\nBook %d:\n", i + 1);
printf("Name : "); scanf(" %[^\n]", b.name);
printf("Price : "); scanf("%f", &b.price);
printf("Author : "); scanf(" %[^\n]", b.author);
fwrite(&b, sizeof(struct Book), 1, fp);
}
fclose(fp);
printf("\nRecords saved to book.dat\n");
/* Step 2: Read from book.dat, search "Gotterfried", copy matches */
fp = fopen("book.dat", "rb");
fp2 = fopen("gotterfried.dat", "wb");
if (fp == NULL || fp2 == NULL) {
printf("Error opening files.\n");
return 1;
}
printf("\nSearching for author 'Gotterfried'...\n");
while (fread(&b, sizeof(struct Book), 1, fp) == 1) {
if (strcmp(b.author, "Gotterfried") == 0) {
fwrite(&b, sizeof(struct Book), 1, fp2);
printf("Found: %s by %s (Rs %.2f)\n", b.name, b.author, b.price);
found++;
}
}
fclose(fp);
fclose(fp2);
if (found)
printf("\n%d record(s) copied to gotterfried.dat\n", found);
else
printf("No records found for author 'Gotterfried'.\n");
return 0;
}
Records saved to book.dat
Searching for author 'Gotterfried'...
Found: Data Structures by Gotterfried (Rs 750.00)
1 record(s) copied to gotterfried.dat
| Data Type | Description | Declaration Example |
|---|---|---|
| INTEGER | Whole numbers (positive, negative, zero) | INTEGER N, COUNT |
| REAL | Single-precision floating-point numbers | REAL X, PRICE |
| DOUBLE PRECISION | Double-precision floating-point (more digits) | DOUBLE PRECISION D |
| COMPLEX | Complex numbers with real and imaginary parts | COMPLEX Z |
| LOGICAL | Boolean values: .TRUE. or .FALSE. | LOGICAL FLAG |
| CHARACTER | Character strings of fixed length | CHARACTER*20 NAME |
Implicit typing: By default, variables starting with I–N are INTEGER; all others are REAL. This can be overridden with explicit declarations or IMPLICIT NONE.
PROGRAM PALINDROME
INTEGER N, ORIGINAL, REVERSED, REMAINDER, TEMP
WRITE(*,*) 'Enter a positive number:'
READ(*,*) N
ORIGINAL = N
REVERSED = 0
TEMP = N
C Reverse the digits using DO WHILE
10 IF (TEMP .GT. 0) THEN
REMAINDER = MOD(TEMP, 10)
REVERSED = REVERSED * 10 + REMAINDER
TEMP = TEMP / 10
GO TO 10
END IF
C Compare original with reversed using Arithmetic IF
IF (ORIGINAL - REVERSED) 20, 30, 20
20 WRITE(*,100) ORIGINAL
100 FORMAT(I8, ' is NOT a palindrome.')
GO TO 40
30 WRITE(*,200) ORIGINAL
200 FORMAT(I8, ' is a palindrome.')
40 STOP
END
Enter a positive number:
12321
12321 is a palindrome.
Enter a positive number:
12345
12345 is NOT a palindrome.
Associativity determines the direction of evaluation when two or more operators of the same precedence appear in an expression. It can be left-to-right or right-to-left.
| Associativity | Operators | Example & Result |
|---|---|---|
| Left-to-Right | +, -, *, /, %, <, >, ==, &&, || | 10 - 3 - 2 = (10-3)-2 = 5 |
| Right-to-Left | =, +=, -=, *=, unary -, !, ~, ++, -- | a = b = c = 5 → c=5, b=5, a=5 |
/* Left-to-right example */
int x = 20 / 4 / 2; // = (20/4)/2 = 5/2 = 2
/* Right-to-left example (assignment) */
int a, b, c;
a = b = c = 10; // c=10, b=10, a=10
/* Right-to-left (unary) */
int n = 5;
int m = -n; // unary minus applied right-to-left: m = -5
/* Mixed: same precedence */
int y = 2 * 3 * 4; // left-to-right: (2*3)*4 = 24
In an entry control loop, the condition is checked before the loop body executes. If the condition is false initially, the body never executes (zero iterations possible).
// C entry control loops: for and while
for (i = 1; i <= 5; i++)
printf("%d ", i); // Output: 1 2 3 4 5
int n = 0;
while (n > 0)
printf("Never executes"); // condition false from start
In an exit control loop, the loop body executes first and the condition is checked after. The body always executes at least once regardless of the condition.
// C exit control loop: do-while
int n = 0;
do {
printf("Executes once even though n=0\n");
} while (n > 0);
// Output: Executes once even though n=0
| Feature | Entry Control (for / while) | Exit Control (do-while) |
|---|---|---|
| Condition checked | Before body (pre-test) | After body (post-test) |
| Minimum executions | 0 (may never run) | At least 1 |
| Use case | When execution count may be 0 | When body must run at least once (e.g., menus) |
A program is a set of instructions written in a programming language that a computer can execute to perform a specific task or solve a problem. Programs are stored in memory and executed by the CPU.
| Type | Description | Examples |
|---|---|---|
| Machine Language (1st Gen) | Consists of binary code (0s and 1s) directly understood by the CPU. Fastest execution but very difficult to write and understand. | Binary instructions: 10110000 01100001 |
| Assembly Language (2nd Gen) | Uses symbolic mnemonics (ADD, MOV, SUB) instead of binary. Requires an assembler to convert to machine code. Machine-dependent. | MOV AX, 01H; ADD AX, BX |
| High-Level Language (3rd Gen) | Uses English-like syntax, easy to read and write. Machine-independent. Requires compiler or interpreter to translate. | C, C++, Java, Python, FORTRAN |
| 4th Generation Language (4GL) | Closer to human language; designed for specific purposes like database querying. Requires less code to accomplish tasks. | SQL, MATLAB, R |
| 5th Generation Language (5GL) | Based on artificial intelligence and natural language constraints. Used in AI and expert systems. | Prolog, LISP, OPS5 |
An algorithm is a finite, ordered set of well-defined, unambiguous instructions that solve a problem or perform a computation in a finite amount of time. It is language-independent and serves as a blueprint for writing a program.
Properties of a good algorithm: Input, Output, Definiteness, Finiteness, Effectiveness.
The ternary operator (also called the conditional operator) is the only operator in C that takes three operands. It is a shorthand for the if-else statement.
Syntax: condition ? expression_if_true : expression_if_false;
Example:
#include <stdio.h>
int main() {
int a = 10, b = 20, max;
max = (a > b) ? a : b; /* if a > b, max = a; else max = b */
printf("Maximum = %d\n", max); /* Output: Maximum = 20 */
/* Nested ternary */
int n = 0;
char *result = (n > 0) ? "Positive" : (n < 0) ? "Negative" : "Zero";
printf("%s\n", result); /* Output: Zero */
return 0;
}
Preprocessor directives are instructions processed by the C preprocessor before actual compilation begins. They begin with the # symbol and do not end with a semicolon.
| Directive | Purpose |
|---|---|
| #include | Includes header files (e.g., #include <stdio.h>) |
| #define | Defines macros/constants (e.g., #define PI 3.14) |
| #ifdef / #ifndef | Conditional compilation |
| #undef | Undefines a previously defined macro |
Keywords are reserved words in C that have a predefined meaning to the compiler. They cannot be used as variable names or identifiers. C has 32 keywords.
Examples of C keywords:
int float double char void
if else while for do
switch case break continue return
struct union typedef sizeof const
auto static extern register goto
int a,b;
double c = 123.55667788;
char str[] = "I enjoy programming";
scanf("%3d%2d", &a, &b);
printf("a = %5\n b=%-7d",a,b);
printf("\n%u%10.7s",str);
printf("\n%u%10.3f",c);
printf("\n%u%-10.6f",c);#include <stdio.h>
int main() {
int a, b;
double c = 123.55667788;
char str[] = "I enjoy programming";
scanf("%3d%2d", &a, &b);
// Input: 123456 789
// %3d reads first 3 digits → a = 123
// %2d reads next 2 digits → b = 45
// (remaining "6 789" is left in buffer)
printf("a = %5\n b=%-7d", a, b);
// %5 is invalid (no type), likely prints "a = " then nothing / garbage
// %-7d prints b=45 left-justified in 7-char field → "45 "
printf("\n%u%10.7s", str);
// %u with char array prints the address of str (varies per run)
// %10.7s prints first 7 chars of str right-justified in 10 chars
// First 7 chars of "I enjoy programming" = "I enjoy"
// Printed as: " I enjoy" (3 spaces + 7 chars)
printf("\n%u%10.3f", c);
// %u again prints address (varies)
// %10.3f: prints c=123.55667788 rounded to 3 decimal places
// in field width 10 → " 123.557"
printf("\n%u%-10.6f", c);
// %u prints address (varies)
// %-10.6f: prints c to 6 decimal places, left-justified in 10 chars
// → "123.556677"
return 0;
}
| Statement | Format | Explanation | Output |
|---|---|---|---|
| scanf("%3d%2d", &a, &b) | — | a = 123 (first 3 digits), b = 45 (next 2 digits) | a=123, b=45 |
| printf("a = %5\n b=%-7d",a,b) | %5 (invalid), %-7d | %5 without type is invalid; b=45 left-justified in 7 chars | a = [?] b=45 |
| printf("\n%u%10.7s",str) | %u, %10.7s | Address of str + first 7 chars right-padded in 10-width field | [addr] I enjoy |
| printf("\n%u%10.3f",c) | %u, %10.3f | Address + c formatted to 3 decimals in width 10 | [addr] 123.557 |
| printf("\n%u%-10.6f",c) | %u, %-10.6f | Address + c to 6 decimals left-aligned in width 10 | [addr]123.556677 |
Note: %u used with a char array or double is undefined behavior — it prints the address or garbage. The exact address values vary per run/machine. %5 without a type specifier is also invalid.
| Basis | Formatted I/O | Unformatted I/O |
|---|---|---|
| Definition | Reads/writes data in a specific format using format specifiers | Reads/writes raw characters or strings without format control |
| Format specifiers | Uses %d, %f, %c, %s etc. | Does not use format specifiers |
| Data type | Can handle int, float, double, char, string | Handles only characters and strings |
| Functions | printf(), scanf(), fprintf(), fscanf() | getchar(), putchar(), gets(), puts(), getche(), getch() |
| Header | stdio.h | stdio.h / conio.h |
| Flexibility | Highly flexible with width, precision control | Limited — no formatting options |
Reads a single character from the keyboard with echo (character is displayed on screen) and returns it immediately without waiting for Enter. Defined in conio.h (Turbo C / Windows).
Syntax: int getche(void);
Example:
#include <conio.h>
char ch = getche(); /* reads one char, echoes it, returns immediately */
Reads a single character from standard input (keyboard). Waits for the user to press Enter. The character is echoed on screen. Defined in stdio.h.
Syntax: int getchar(void);
Example:
#include <stdio.h>
char ch = getchar(); /* waits for Enter, then reads one char */
Reads formatted input from standard input according to the format string. Returns the number of items successfully read.
Syntax: int scanf(const char *format, address_list);
Example:
#include <stdio.h>
int n;
float x;
char name[50];
scanf("%d", &n); /* read integer */
scanf("%f", &x); /* read float */
scanf("%s", name); /* read string (no & needed for arrays) */
scanf("%d %f", &n, &x); /* read multiple values */
Iteration refers to the repeated execution of a block of statements as long as a given condition is true. In C, iteration is implemented using loop constructs: for, while, and do-while. Each repeated execution of the loop body is called one iteration.
The break statement immediately terminates the nearest enclosing loop (or switch) and transfers control to the first statement after the loop.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i == 5)
break; /* exit loop when i equals 5 */
printf("%d ", i);
}
printf("\nLoop ended.");
return 0;
}
/* Output: 1 2 3 4
Loop ended. */
The continue statement skips the remaining statements in the current iteration and jumps to the condition check of the next iteration. The loop does not terminate.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++) {
if (i % 2 == 0)
continue; /* skip even numbers */
printf("%d ", i);
}
return 0;
}
/* Output: 1 3 5 7 9 */
| Statement | Action | Loop continues? |
|---|---|---|
| break | Exits the loop entirely | No |
| continue | Skips current iteration, moves to next | Yes |
#include <stdio.h>
/* Custom string length function */
int strLen(char str[]) {
int len = 0;
while (str[len] != '\0')
len++;
return len;
}
int main() {
char word[100];
int i, len, isPalin = 1;
printf("Enter a word: ");
scanf("%s", word);
len = strLen(word);
/* Compare characters from both ends */
for (i = 0; i < len / 2; i++) {
if (word[i] != word[len - 1 - i]) {
isPalin = 0;
break;
}
}
if (isPalin)
printf("\"%s\" is a palindrome.\n", word);
else
printf("\"%s\" is NOT a palindrome.\n", word);
return 0;
}
Enter a word: madam
"madam" is a palindrome.
Enter a word: hello
"hello" is NOT a palindrome.
Enter a word: racecar
"racecar" is a palindrome.
| Step | Description |
|---|---|
| 1. Find length | Custom strLen() counts characters until '\0' |
| 2. Compare ends | Compare word[0] with word[len-1], word[1] with word[len-2], etc. |
| 3. Mismatch found | If any pair differs, set isPalin = 0 and break |
| 4. Result | If isPalin remains 1 after the loop, the word is a palindrome |
A function header (also called function prototype or function signature) is the first line of a function definition that specifies its return type, name, and parameter list — without the function body.
Syntax: return_type function_name(parameter_list)
Example:
int add(int a, int b) /* function header */
{
return a + b; /* function body */
}
The function header tells the compiler: what the function returns, what it is named, and what arguments it accepts.
Parameters are variables listed in the function header that receive values when the function is called. There are two types:
| Type | Description |
|---|---|
| Formal Parameters | Variables declared in the function definition that receive the passed values. Exist only within the function scope. |
| Actual Parameters (Arguments) | The real values or variables passed to the function at the time of calling. |
| Method | Description | Example |
|---|---|---|
| Pass by Value | A copy of the actual value is passed. Changes inside the function do NOT affect the original variable. | void show(int x) { x = 10; } — original unchanged |
| Pass by Reference (Pointer) | The address of the variable is passed. Changes inside the function AFFECT the original variable. | void change(int *x) { *x = 10; } — original modified |
/* Example demonstrating both */
#include <stdio.h>
void byValue(int n) {
n = 100; /* does not affect original */
}
void byReference(int *n) {
*n = 100; /* modifies original */
}
int main() {
int a = 5, b = 5;
byValue(a);
byReference(&b);
printf("a = %d\n", a); /* Output: a = 5 (unchanged) */
printf("b = %d\n", b); /* Output: b = 100 (changed) */
return 0;
}
#include <stdio.h>
/* Calculates sum of digits of n */
int digitSum(int n) {
if (n == 0)
return 0;
return (n % 10) + digitSum(n / 10);
}
/* Recursively reduces until single digit */
int singleDigit(int n) {
if (n < 10)
return n; /* base case: already single digit */
int sum = digitSum(n);
printf("%d => ", sum);
return singleDigit(sum); /* recursive case */
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
printf("%d => ", n);
int result = singleDigit(n);
printf("%d\n", result);
printf("Single digit result: %d\n", result);
return 0;
}
Enter a number: 9785
9785 => 29 => 11 => 2
Single digit result: 2
Enter a number: 999
999 => 27 => 9
Single digit result: 9
singleDigit(9785)
digitSum(9785) = 9+7+8+5 = 29
singleDigit(29)
digitSum(29) = 2+9 = 11
singleDigit(11)
digitSum(11) = 1+1 = 2
singleDigit(2) → 2 < 10, return 2 ✓
An array is a collection of a fixed number of elements of the same data type stored in contiguous memory locations, accessed using a common name and an index.
/* Declaration syntax */
data_type array_name[size];
int marks[5]; /* array of 5 integers */
float temp[10]; /* array of 10 floats */
int scores[5] = {90, 85, 78, 92, 88}; /* initialized array */
/* Accessing elements */
scores[0] = 90; scores[1] = 85; /* index starts from 0 */
| Reason | Explanation |
|---|---|
| Handling Multiple Values | Without arrays, storing 100 student marks would require 100 separate variables. Arrays reduce this to one declaration: int marks[100]; |
| Loop-based Processing | Arrays can be traversed using loops, enabling batch operations like sum, average, search, and sort efficiently. |
| Contiguous Memory | Elements are stored sequentially, allowing fast indexed access in O(1) time. |
| Passing to Functions | An entire collection can be passed to a function using the array name (as a pointer). |
| Matrix Operations | 2D arrays are essential for matrix representation and mathematical operations. |
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "HELLO";
int len = strlen(str); /* len = 5 */
int i, j;
/* Upper half: print increasing number of characters */
for (i = 1; i <= len; i++) {
for (j = 0; j < i; j++)
printf("%c", str[j]);
printf("\n");
}
/* Lower half: print decreasing number of characters (skip full row) */
for (i = len - 1; i >= 1; i--) {
for (j = 0; j < i; j++)
printf("%c", str[j]);
printf("\n");
}
return 0;
}
H
HE
HEL
HELL
HELLO
HELL
HEL
HE
H
| Part | Loop | Characters Printed |
|---|---|---|
| Upper half (including middle) | i = 1 to 5 | 1, 2, 3, 4, 5 characters |
| Lower half | i = 4 down to 1 | 4, 3, 2, 1 characters |
Yes, arrays and pointers are closely related in C. The name of an array is a constant pointer to its first element. That is, arr is equivalent to &arr[0] — both hold the address of the first element.
| Array Notation | Pointer Notation | Meaning |
|---|---|---|
| arr | &arr[0] | Address of first element |
| arr[i] | *(arr + i) | Value of element at index i |
| &arr[i] | arr + i | Address of element at index i |
| arr[0] | *arr | First element's value |
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; /* ptr points to first element of arr */
int i;
printf("Using array notation:\n");
for (i = 0; i < 5; i++)
printf("arr[%d] = %d\n", i, arr[i]);
printf("\nUsing pointer notation:\n");
for (i = 0; i < 5; i++)
printf("*(ptr + %d) = %d\n", i, *(ptr + i));
printf("\nAddresses:\n");
for (i = 0; i < 5; i++)
printf("&arr[%d] = %p | ptr+%d = %p\n", i, &arr[i], i, ptr+i);
printf("\nDirect comparison:\n");
printf("arr = %p\n", arr);
printf("&arr[0]= %p\n", &arr[0]);
printf("ptr = %p\n", ptr);
return 0;
}
Using array notation:
arr[0] = 10 arr[1] = 20 arr[2] = 30 arr[3] = 40 arr[4] = 50
Using pointer notation:
*(ptr+0) = 10 *(ptr+1) = 20 *(ptr+2) = 30 *(ptr+3) = 40 *(ptr+4) = 50
arr = 0x7ffd1234 &arr[0] = 0x7ffd1234 ptr = 0x7ffd1234
Note: While a pointer variable can be reassigned (ptr++), the array name is a constant pointer and cannot be incremented (arr++ is illegal).
A structure is a user-defined data type in C that allows grouping of variables of different data types under a single name. Each variable in a structure is called a member.
Syntax:
struct structure_name {
data_type member1;
data_type member2;
...
};
struct Student {
int rollNo;
char name[50];
float marks;
};
#include <stdio.h>
#define N 5
/* Inner structure */
struct ServiceYear {
int durationInYear;
};
/* Outer structure with nested ServiceYear */
struct Faculty {
int staffID;
char name[50];
char address[100];
struct ServiceYear serviceYear;
};
int main() {
struct Faculty f[N];
int i;
/* Input */
for (i = 0; i < N; i++) {
printf("\nEnter details of Faculty %d:\n", i + 1);
printf("Staff ID : ");
scanf("%d", &f[i].staffID);
printf("Name : ");
scanf(" %[^\n]", f[i].name);
printf("Address : ");
scanf(" %[^\n]", f[i].address);
printf("Service Duration (years): ");
scanf("%d", &f[i].serviceYear.durationInYear);
}
/* Display faculties with service duration > 10 and < 30 */
printf("\n--- Faculty with service duration between 10 and 30 years ---\n");
printf("%-10s %-20s %-30s %-10s\n", "Staff ID", "Name", "Address", "Duration");
printf("----------------------------------------------------------------------\n");
int found = 0;
for (i = 0; i < N; i++) {
int dur = f[i].serviceYear.durationInYear;
if (dur > 10 && dur < 30) {
printf("%-10d %-20s %-30s %-10d\n",
f[i].staffID, f[i].name, f[i].address, dur);
found++;
}
}
if (found == 0)
printf("No faculty found with service duration between 10 and 30 years.\n");
return 0;
}
--- Faculty with service duration between 10 and 30 years ---
Staff ID Name Address Duration
----------------------------------------------------------------------
1001 Ram Sharma Kathmandu 15
1003 Sita Rai Pokhara 22
Data stored in variables and arrays exists only during program execution (in RAM) and is lost when the program ends. File handling allows us to store data permanently on disk so it can be retrieved later.
| Mode | Description | File must exist? |
|---|---|---|
| "r" | Open for reading only. File must exist; returns NULL if not found. | Yes |
| "w" | Open for writing. Creates a new file or truncates (empties) existing file. | No |
| "a" | Open for appending. Data is written at the end. Creates file if not found. | No |
| "r+" | Open for both reading and writing. File must exist. | Yes |
| "w+" | Open for reading and writing. Creates new or truncates existing. | No |
| "a+" | Open for reading and appending. Creates file if not found. | No |
| "rb" | Open binary file for reading only. | Yes |
| "wb" | Open binary file for writing (create/truncate). | No |
| "ab" | Open binary file for appending. | No |
| "rb+" / "r+b" | Open binary file for reading and writing. | Yes |
FILE *fp = fopen("data.txt", "r"); /* open for reading */
if (fp == NULL)
printf("File not found!");
fclose(fp);
fseek() is used to move the file position indicator (cursor) to a specified location within a file, enabling random access to any record without reading all previous records.
Syntax: int fseek(FILE *fp, long offset, int origin);
Parameters:
fp — file pointer
offset — number of bytes to move (can be negative)
origin — starting position:
SEEK_SET (0) → from beginning of file
SEEK_CUR (1) → from current position
SEEK_END (2) → from end of file
Examples:
fseek(fp, 0, SEEK_SET); /* go to beginning */
fseek(fp, 0, SEEK_END); /* go to end */
fseek(fp, sizeof(struct), SEEK_SET); /* jump to 2nd record */
fseek(fp, -sizeof(struct), SEEK_CUR);/* go back one record */
#include <stdio.h>
#define N 5
struct Student {
char name[50];
int rollNo;
int age;
};
int main() {
struct Student s[N];
int i;
FILE *fp;
/* Input student data */
printf("Enter details of %d students:\n", N);
for (i = 0; i < N; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Name : ");
scanf(" %[^\n]", s[i].name);
printf("Roll No : ");
scanf("%d", &s[i].rollNo);
printf("Age : ");
scanf("%d", &s[i].age);
}
/* Write to STUDENT.DAT in binary mode */
fp = fopen("STUDENT.DAT", "wb");
if (fp == NULL) {
printf("Error: Cannot create STUDENT.DAT\n");
return 1;
}
for (i = 0; i < N; i++)
fwrite(&s[i], sizeof(struct Student), 1, fp);
fclose(fp);
printf("\nData successfully written to STUDENT.DAT\n");
/* Verify: Read back and display */
fp = fopen("STUDENT.DAT", "rb");
if (fp == NULL) { printf("Cannot open file.\n"); return 1; }
printf("\n--- Records in STUDENT.DAT ---\n");
printf("%-5s %-20s %-5s\n", "Roll", "Name", "Age");
printf("------------------------------\n");
struct Student temp;
while (fread(&temp, sizeof(struct Student), 1, fp) == 1)
printf("%-5d %-20s %-5d\n", temp.rollNo, temp.name, temp.age);
fclose(fp);
return 0;
}
Data successfully written to STUDENT.DAT
--- Records in STUDENT.DAT ---
Roll Name Age
------------------------------
101 Ram Sharma 20
102 Sita Rai 21
103 Hari Thapa 19
104 Gita Poudel 22
105 Mohan KC 20
The X format descriptor is used to insert horizontal blank spaces in output or skip characters in input.
Syntax: nX (where n = number of spaces)
Example:
WRITE(*,100) 10, 20
100 FORMAT(I3, 5X, I3)
C Output: " 10 20" (5 spaces between the two numbers)
C In READ, nX skips n characters in input:
READ(*,200) A, B
200 FORMAT(F5.2, 3X, F5.2)
C Skips 3 characters between the two float fields
The T format descriptor (Tab) moves the output/input position to an absolute column number, like a tab stop.
Syntax: Tn (where n = column number, starting from 1)
Example:
WRITE(*,300) 'NAME', 'AGE', 'CITY'
300 FORMAT(T1, A4, T10, A3, T20, A4)
C NAME starts at col 1, AGE at col 10, CITY at col 20
WRITE(*,400) 'Ram', 25, 'Kathmandu'
400 FORMAT(T1, A10, T12, I5, T20, A15)
C Fields positioned at absolute columns
| Feature | Unconditional GOTO | Computed GOTO |
|---|---|---|
| Syntax | GO TO label | GO TO (L1, L2, L3, ...), expression |
| Destination | Always jumps to the same fixed label | Jumps to one of several labels based on the value of an integer expression |
| Condition | No condition — always transfers | Depends on integer value (1=L1, 2=L2, ...) |
| Flexibility | Less flexible | More flexible — acts like a switch/case |
| Example | GO TO 50 | GO TO (10, 20, 30), I |
C Unconditional GOTO:
GO TO 100 ! always jumps to statement 100
100 WRITE(*,*) 'Arrived here'
C Computed GOTO (jumps to 10 if I=1, 20 if I=2, 30 if I=3):
I = 2
GO TO (10, 20, 30), I
10 WRITE(*,*) 'ONE'
GO TO 40
20 WRITE(*,*) 'TWO' ! this executes
GO TO 40
30 WRITE(*,*) 'THREE'
40 CONTINUE
PROGRAM SORTARRAY
INTEGER N, I, J, TEMP
INTEGER ARR(20)
WRITE(*,*) 'Enter number of elements (max 20):'
READ(*,*) N
WRITE(*,*) 'Enter', N, 'elements:'
DO 10 I = 1, N
READ(*,*) ARR(I)
10 CONTINUE
C Bubble Sort - Ascending Order
DO 30 I = 1, N-1
DO 20 J = 1, N-I
IF (ARR(J) .GT. ARR(J+1)) THEN
TEMP = ARR(J)
ARR(J) = ARR(J+1)
ARR(J+1) = TEMP
END IF
20 CONTINUE
30 CONTINUE
WRITE(*,*) 'Ascending Order:'
DO 40 I = 1, N
WRITE(*,'(I5)',ADVANCE='NO') ARR(I)
40 CONTINUE
WRITE(*,*)
C Reverse the array for Descending Order
DO 50 I = 1, N/2
TEMP = ARR(I)
ARR(I) = ARR(N+1-I)
ARR(N+1-I) = TEMP
50 CONTINUE
WRITE(*,*) 'Descending Order:'
DO 60 I = 1, N
WRITE(*,'(I5)',ADVANCE='NO') ARR(I)
60 CONTINUE
WRITE(*,*)
STOP
END
Enter number of elements (max 20):
5
Enter 5 elements:
40 10 30 20 50
Ascending Order:
10 20 30 40 50
Descending Order:
50 40 30 20 10
| Trend | Description |
|---|---|
| Artificial Intelligence & ML | AI/ML is being integrated into almost all software — from recommendation engines to smart assistants (e.g., ChatGPT, GitHub Copilot). |
| Cloud Computing | Software is deployed on cloud platforms (AWS, Azure, GCP) enabling scalability, remote access, and reduced hardware dependency. |
| Internet of Things (IoT) | Software now communicates with embedded devices — smart home, wearables, industrial sensors. |
| DevOps & CI/CD | Continuous Integration and Continuous Deployment pipelines speed up software delivery and reliability. |
| Mobile-first Development | Software is increasingly designed for smartphones first, with cross-platform frameworks like Flutter and React Native. |
| Cybersecurity Focus | Security is built into software from the start (DevSecOps), with end-to-end encryption and zero-trust models. |
| Agile & Microservices | Large monolithic applications are broken into small, independent microservices for flexibility and easier maintenance. |
| Feature | Description |
|---|---|
| Functionality | The software must perform all intended tasks correctly and completely as per user requirements. |
| Reliability | Should work consistently without failure under expected conditions. Minimal downtime and error rate. |
| Usability | User-friendly interface that requires minimal training. Intuitive navigation and clear feedback. |
| Efficiency | Optimal use of system resources (CPU, memory, disk) while delivering fast response times. |
| Maintainability | Code should be easy to read, modify, and debug. Well-documented and modular design. |
| Portability | Ability to run on different hardware, operating systems, or environments with minimal changes. |
| Security | Protection against unauthorized access, data breaches, and vulnerabilities. |
| Scalability | Ability to handle increased load (users, data) without degradation in performance. |
| Error Type | Description | Example |
|---|---|---|
| Syntax Error | Violation of grammar rules of the programming language. Detected by the compiler. | Missing semicolon, unmatched parentheses: printf("Hello" |
| Logical Error | Program compiles and runs but produces wrong output due to incorrect logic. | Using + instead of * in a multiplication formula |
| Runtime Error | Error that occurs during execution, causing the program to crash or behave unexpectedly. | Division by zero, accessing out-of-bounds array index |
| Semantic Error | Code is syntactically correct but has unintended meaning. | Assigning wrong data type or using uninitialized variable |
| Linker Error | Occurs when the linker cannot find the definition of a referenced function or variable. | Calling a function that is declared but never defined |
Preprocessor directives are instructions processed by the C preprocessor before actual compilation begins. They start with the # symbol and do not end with a semicolon. They perform tasks like file inclusion, macro substitution, and conditional compilation.
| Directive | Purpose | Example |
|---|---|---|
| #include | Includes a header file into the source code | #include <stdio.h> |
| #define | Defines a macro or constant | #define PI 3.14159 |
| #ifdef / #ifndef | Conditional compilation | #ifdef DEBUG ... #endif |
| #undef | Undefines a previously defined macro | #undef PI |
| #pragma | Machine-specific or compiler-specific instructions | #pragma warning(disable:4996) |
The compilation process converts C source code into an executable program through the following stages:
+------------------+
| Source Code | (.c file written by programmer)
| (program.c) |
+------------------+
|
v [PREPROCESSOR]
+------------------+
| Preprocessed | Expands #include, #define, macros
| Source Code | Removes comments
+------------------+
|
v [COMPILER]
+------------------+
| Assembly Code | Converts C code to assembly language
| (program.asm) | Checks syntax and semantic errors
+------------------+
|
v [ASSEMBLER]
+------------------+
| Object Code | Converts assembly to machine code (binary)
| (program.obj) | Not yet executable (unresolved references)
+------------------+
|
v [LINKER]
+------------------+
| Executable File | Links object code with library files
| (program.exe) | Resolves all function references
+------------------+
|
v [LOADER]
+------------------+
| Execution | Loads program into RAM and runs it
| (Output) |
+------------------+
| Stage | Tool | Input | Output |
|---|---|---|---|
| 1. Preprocessing | Preprocessor | .c file | Expanded .c file |
| 2. Compilation | Compiler | Expanded .c | Assembly (.asm) |
| 3. Assembly | Assembler | .asm file | Object file (.obj) |
| 4. Linking | Linker | .obj + libraries | Executable (.exe) |
| 5. Loading | Loader/OS | .exe file | Program in memory (runs) |
Problem analysis is the first and most critical step in programming. Without it, we risk writing code that solves the wrong problem or is inefficient.
A token is the smallest individual unit in a C program that is meaningful to the compiler. Every C program is made up of tokens.
Types of tokens in C: Keywords, Identifiers, Constants, Strings, Operators, Special Symbols.
Example: int sum = a + b;
Tokens: int | sum | = | a | + | b | ;
(keyword)(id)(op)(id)(op)(id)(special)
An expression is a combination of variables, constants, and operators that evaluates to a single value. Expressions can be arithmetic, relational, logical, or assignment-based.
Examples:
a + b /* arithmetic expression — evaluates to sum */
a > b /* relational expression — evaluates to 1 or 0 */
a && b /* logical expression */
x = 5 * 2 /* assignment expression — evaluates to 10 */
++i /* unary expression */
An identifier is a name given by the programmer to variables, functions, arrays, or other user-defined entities. Identifiers must follow these rules:
int, float are not valid identifiers).sum and Sum are different identifiers.Valid identifiers: sum, _count, marks2, firstName, MAX_SIZE
Invalid identifiers: 2marks (starts with digit), int (keyword), my-name (hyphen)
A control statement is a statement that determines the order in which other statements are executed in a program. By default, C executes statements sequentially. Control statements alter this flow based on conditions or loops.
| Category | Statements | Description |
|---|---|---|
| Conditional / Decision-Making | if, if-else, if-else if ladder, nested if, switch-case | Execute a block of code only when a specified condition is true. Choose between alternate paths. |
| Looping / Iteration | while, do-while, for | Repeatedly execute a block of statements as long as a condition holds true. |
| Jump / Transfer | break, continue, goto, return | Transfer control to another part of the program unconditionally or based on a condition. |
/* Quick Examples */
/* Conditional */
if (a > b) printf("a is greater");
else printf("b is greater");
/* Looping */
for (i = 1; i <= 5; i++)
printf("%d ", i); /* prints: 1 2 3 4 5 */
/* Jump */
for (i = 0; i < 10; i++) {
if (i == 5) break; /* exit loop at i=5 */
if (i % 2 == 0) continue; /* skip even numbers */
printf("%d ", i);
}
Prints formatted output to the standard output (screen). Defined in stdio.h.
Syntax: int printf(const char *format, argument_list);
Examples:
printf("Hello World\n"); /* prints a string */
printf("a = %d\n", a); /* prints integer */
printf("x = %5.2f\n", x); /* prints float with width and precision */
printf("%s is %d years old\n", name, age);
Reads formatted input from the standard input (keyboard). Returns number of successfully read items. Defined in stdio.h.
Syntax: int scanf(const char *format, address_list);
Examples:
scanf("%d", &n); /* read integer */
scanf("%f", &x); /* read float */
scanf("%s", name); /* read string (array, no & needed) */
scanf("%d %f", &n, &x); /* read multiple values */
Reads a single character from standard input. Waits for the Enter key to be pressed. Character is echoed on screen. Defined in stdio.h.
Syntax: int getchar(void);
Example:
#include <stdio.h>
char ch;
ch = getchar(); /* user types a char and presses Enter */
printf("You entered: %c", ch);
Reads a single character from the keyboard without echo (character is NOT displayed on screen) and returns immediately without waiting for Enter. Defined in conio.h (Turbo C/Windows).
Syntax: int getch(void);
Example:
#include <conio.h>
char ch;
ch = getch(); /* reads immediately, no echo, no Enter needed */
| Function | Header | Echo? | Waits for Enter? | Type |
|---|---|---|---|---|
| printf() | stdio.h | — | — | Formatted Output |
| scanf() | stdio.h | Yes | Yes | Formatted Input |
| getchar() | stdio.h | Yes | Yes | Unformatted Input |
| getch() | conio.h | No | No | Unformatted Input |
char ch='G'; int g=10; float gravity=9.81; printf("%d%d%%f\n"); printf("%10d\n",g); printf("%3c\n",ch); printf("%3f\n",gravity); printf("%-10.1f%d\n",gravity,g);#include <stdio.h>
int main() {
char ch = 'G';
int g = 10;
float gravity = 9.81;
printf("%d%d%%f\n"); /* line 1 */
printf("%10d\n", g); /* line 2 */
printf("%3c\n", ch); /* line 3 */
printf("%3f\n", gravity); /* line 4 */
printf("%-10.1f%d\n", gravity, g); /* line 5 */
return 0;
}
| Statement | Format Explanation | Output |
|---|---|---|
printf("%d%d%%f\n"); |
%d%d with no arguments — undefined behavior (garbage values); %% prints literal %; then literal f |
[garbage][garbage]%f |
printf("%10d\n", g); |
%10d — print g=10 right-aligned in a field of width 10 |
10 |
printf("%3c\n", ch); |
%3c — print ch='G' right-aligned in field of width 3 (2 spaces + G) |
G |
printf("%3f\n", gravity); |
%3f — print gravity=9.81 with default 6 decimal places; width 3 is less than the number's width so it's ignored |
9.810000 |
printf("%-10.1f%d\n", gravity, g); |
%-10.1f — left-align gravity to 1 decimal in width 10; then %d prints g=10 |
9.8 10 |
[garbage values]%f
10
G
9.810000
9.8 10
Note: Line 1 (printf("%d%d%%f\n")) invokes undefined behavior since no arguments are supplied for %d%d. On most compilers, garbage values or 0 are printed.
gets() reads a line of characters from standard input (keyboard) into a character array until a newline (\n) or EOF is encountered. The newline is replaced by a null character (\0). Defined in stdio.h.
Note: gets() is considered unsafe (no bounds checking); use fgets() in modern C.
Syntax: char *gets(char *str);
Example:
#include <stdio.h>
char name[50];
printf("Enter name: ");
gets(name); /* reads full line including spaces */
printf("Hello, %s\n", name);
putchar() writes a single character to the standard output (screen). It returns the character written, or EOF on error. Defined in stdio.h.
Syntax: int putchar(int character);
Example:
#include <stdio.h>
char ch = 'A';
putchar(ch); /* prints: A */
putchar('\n'); /* prints a newline */
putchar(65); /* prints: A (ASCII 65) */
scanf() reads formatted input from standard input according to the format string. Returns the number of items successfully read. Defined in stdio.h.
Syntax: int scanf(const char *format, address_list);
Example:
#include <stdio.h>
int n;
float x;
char name[50];
scanf("%d", &n); /* read integer */
scanf("%f", &x); /* read float */
scanf("%s", name); /* read string (no & for arrays) */
scanf("%d %f", &n, &x); /* read multiple values at once */
#include <stdio.h>
int main() {
int n, i;
double x, term, cosVal;
printf("Enter value of x (in radians): ");
scanf("%lf", &x);
printf("Enter number of terms: ");
scanf("%d", &n);
cosVal = 0.0;
term = 1.0; /* first term is 1 (x^0 / 0!) */
for (i = 1; i <= n; i++) {
cosVal += term;
/* Next term = -term * x^2 / ((2i-1) * 2i) */
term = -term * x * x / ((2 * i - 1) * (2 * i));
}
printf("\ncos(%.2f) = %.6f\n", x, cosVal);
return 0;
}
Enter value of x (in radians): 0
Enter number of terms: 5
cos(0.00) = 1.000000
Enter value of x (in radians): 1.5708
Enter number of terms: 10
cos(1.57) = 0.000007 (approximately 0, since cos(π/2) ≈ 0)
| Term Number (i) | Expression | Sign |
|---|---|---|
| 1 | 1 (= x⁰/0!) | + |
| 2 | x²/2! | − |
| 3 | x⁴/4! | + |
| 4 | x⁶/6! | − |
| n | x^(2n-2) / (2n-2)! | alternating |
Each new term is derived from the previous: term_new = -term_prev × x² / ((2i-1) × 2i)
A function declaration (prototype) informs the compiler about the function's return type, name, and parameter types before it is defined or called.
/* Function declaration (prototype) */
int add(int a, int b); /* declared before main() */
int main() {
printf("%d\n", add(3, 4)); /* called here */
return 0;
}
int add(int a, int b) { /* defined after main() */
return a + b;
}
| Basis | Formal Parameter | Actual Parameter |
|---|---|---|
| Definition | Variable declared in the function definition that receives values | Actual values or variables passed when calling the function |
| Location | In the function header/definition | In the function call |
| Scope | Local to the function | Exists in the calling function |
| Memory | Allocated when function is called, freed when it returns | Exists in the caller's memory space |
| Example | void show(int x, int y) — x and y are formal | show(a, b) — a and b are actual |
#include <stdio.h>
/* Returns the nth term: 1, 11, 111, 1111, ... */
long long nthTerm(int n) {
if (n == 1)
return 1; /* base case: 1st term is 1 */
return nthTerm(n - 1) * 10 + 1; /* e.g., 11 = 1*10+1, 111 = 11*10+1 */
}
/* Recursively prints and sums all terms */
long long seriesSum(int n) {
if (n == 0)
return 0;
long long term = nthTerm(n);
printf("Term %d = %lld\n", n, term);
return term + seriesSum(n - 1);
}
int main() {
int n;
printf("Enter number of terms: ");
scanf("%d", &n);
printf("\nSeries:\n");
long long sum = seriesSum(n);
printf("\nSum of %d terms = %lld\n", n, sum);
return 0;
}
Enter number of terms: 5
Series:
Term 5 = 11111
Term 4 = 1111
Term 3 = 111
Term 2 = 11
Term 1 = 1
Sum of 5 terms = 12345
nthTerm(1) = 1
nthTerm(2) = 1 * 10 + 1 = 11
nthTerm(3) = 11 * 10 + 1 = 111
nthTerm(4) = 111 * 10 + 1 = 1111
An array of strings is a two-dimensional character array where each row stores one string (character array). It is used to store multiple strings under a single variable name.
Syntax: char array_name[rows][max_length];
Example:
char fruits[5][20] = {"Apple", "Banana", "Mango", "Orange", "Grape"};
/* Accessing and printing */
#include <stdio.h>
int main() {
char fruits[5][20] = {"Apple", "Banana", "Mango", "Orange", "Grape"};
int i;
for (i = 0; i < 5; i++)
printf("%s\n", fruits[i]);
return 0;
}
/* Output:
Apple
Banana
Mango
Orange
Grape
*/
Here, fruits[0] stores "Apple", fruits[1] stores "Banana", etc. Each string can hold up to 19 characters plus the null terminator '\0'.
| Basis | Array | Pointer |
|---|---|---|
| Definition | A collection of elements of the same type stored in contiguous memory | A variable that stores the memory address of another variable |
| Declaration | int arr[5]; | int *ptr; |
| Memory Allocation | Allocated at compile time (static) | Can be allocated dynamically at runtime |
| Reassignment | Array name is a constant pointer; cannot be reassigned (arr++ is illegal) | Pointer can be reassigned to point to different locations (ptr++ is valid) |
| Size | sizeof(arr) returns total bytes of the array | sizeof(ptr) returns size of the pointer (4 or 8 bytes) |
| Initialization | Can be initialized at declaration: int arr[] = {1,2,3}; | Must be assigned an address: ptr = arr; |
| Accessing elements | arr[i] | *(ptr + i) or ptr[i] |
#include <stdio.h>
#define MAX 100
/* Function to display the array */
void display(int arr[], int n) {
int i;
printf("Array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
/* Function to insert element at given position */
int insertElement(int arr[], int n, int element, int pos) {
int i;
/* Validate position (1-based indexing) */
if (pos < 1 || pos > n + 1) {
printf("Invalid position! Position must be between 1 and %d.\n", n + 1);
return n; /* array unchanged */
}
/* Shift elements to the right from the end to pos */
for (i = n; i >= pos; i--)
arr[i] = arr[i - 1];
/* Insert the new element at position (convert to 0-based) */
arr[pos - 1] = element;
return n + 1; /* new size */
}
int main() {
int arr[MAX], n, element, pos;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
int i;
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("\nBefore insertion: ");
display(arr, n);
printf("\nEnter the element to insert: ");
scanf("%d", &element);
printf("Enter the position to insert at (1 to %d): ", n + 1);
scanf("%d", &pos);
n = insertElement(arr, n, element, pos);
printf("\nAfter insertion: ");
display(arr, n);
return 0;
}
Enter number of elements: 5
Enter 5 elements:
10 20 30 40 50
Before insertion: Array: 10 20 30 40 50
Enter the element to insert: 25
Enter the position to insert at (1 to 6): 3
After insertion: Array: 10 20 25 30 40 50
| Step | Description |
|---|---|
| 1. Validate position | Position must be between 1 and n+1 (inclusive) |
| 2. Shift right | All elements from position pos to n are shifted one place to the right |
| 3. Insert | New element placed at arr[pos-1] (0-based) |
| 4. Update size | Return n+1 as the new array size |
A void pointer (also called a generic pointer) is a special type of pointer declared with the void keyword. It can hold the address of any data type (int, float, char, struct, etc.) without needing to specify the type at declaration. However, it cannot be dereferenced directly — it must be cast to the appropriate type before accessing the value.
Syntax: void *pointer_name;
/* Key Properties:
- Can point to any data type
- Cannot be dereferenced without casting
- Cannot use pointer arithmetic without casting
- Commonly used in generic functions (like malloc, memcpy)
*/
#include <stdio.h>
int main() {
int inum = 42;
float fnum = 3.14;
char ch = 'A';
void *vptr; /* void pointer */
/* Point to int */
vptr = &inum;
printf("Integer value: %d\n", *(int *)vptr); /* cast to int* before dereferencing */
/* Point to float */
vptr = &fnum;
printf("Float value: %.2f\n", *(float *)vptr); /* cast to float* */
/* Point to char */
vptr = &ch;
printf("Char value: %c\n", *(char *)vptr); /* cast to char* */
return 0;
}
/* Output:
Integer value: 42
Float value: 3.14
Char value: A
*/
Use Case: malloc() returns a void * so it can allocate memory for any type: int *p = (int *) malloc(5 * sizeof(int));
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
/* Function to read matrix */
void readMatrix(int (*mat)[MAX], int rows, int cols, char name) {
int i, j;
printf("Enter elements of Matrix %c (%dx%d):\n", name, rows, cols);
for (i = 0; i < rows; i++)
for (j = 0; j < cols; j++)
scanf("%d", *(mat + i) + j); /* pointer notation */
}
/* Function to display matrix */
void displayMatrix(int (*mat)[MAX], int rows, int cols) {
int i, j;
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++)
printf("%5d", *(*(mat + i) + j)); /* pointer dereference */
printf("\n");
}
}
/* Function to multiply matrices */
void multiplyMatrix(int (*A)[MAX], int (*B)[MAX], int (*C)[MAX],
int m, int n, int p, int q) {
int i, j, k;
/* Matrix multiplication is possible only if n == p */
if (n != p) {
printf("Calculation cannot be performed!\n");
printf("(Columns of A = %d) != (Rows of B = %d)\n", n, p);
return;
}
/* Initialize result matrix C to 0 */
for (i = 0; i < m; i++)
for (j = 0; j < q; j++)
*(*(C + i) + j) = 0;
/* Multiply: C[i][j] = sum of A[i][k] * B[k][j] */
for (i = 0; i < m; i++)
for (j = 0; j < q; j++)
for (k = 0; k < n; k++)
*(*(C + i) + j) += *(*(A + i) + k) * *(*(B + k) + j);
printf("\nProduct Matrix C (%dx%d):\n", m, q);
displayMatrix(C, m, q);
}
int main() {
int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX];
int m, n, p, q;
printf("Enter dimensions of Matrix A (rows cols): ");
scanf("%d %d", &m, &n);
printf("Enter dimensions of Matrix B (rows cols): ");
scanf("%d %d", &p, &q);
readMatrix(A, m, n, 'A');
readMatrix(B, p, q, 'B');
printf("\nMatrix A (%dx%d):\n", m, n);
displayMatrix(A, m, n);
printf("\nMatrix B (%dx%d):\n", p, q);
displayMatrix(B, p, q);
multiplyMatrix(A, B, C, m, n, p, q);
return 0;
}
Matrix A (2x3): Matrix B (3x2):
1 2 3 7 8
4 5 6 9 10
11 12
Product Matrix C (2x2):
58 64
139 154
Calculation cannot be performed!
(Columns of A = 3) != (Rows of B = 2)
A nested structure is a structure that contains another structure as one of its members. This allows grouping of related data hierarchically, making complex real-world entities easier to model.
/* Example of Nested Structure */
struct Date {
int day, month, year;
};
struct Employee {
int empID;
char name[50];
struct Date birthDate; /* nested structure */
float salary;
};
struct Employee e;
e.empID = 101;
e.birthDate.day = 15; /* accessing nested member */
e.birthDate.month = 8;
e.birthDate.year = 1995;
#include <stdio.h>
#include <string.h>
#define N 5
struct Student {
int id;
char name[50];
char address[100];
};
/* Function to sort students alphabetically by name (Bubble Sort) */
void sortByName(struct Student s[], int n) {
int i, j;
struct Student temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (strcmp(s[j].name, s[j+1].name) > 0) {
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
}
/* Function to display students */
void display(struct Student s[], int n) {
int i;
printf("\n%-5s %-20s %-30s\n", "ID", "Name", "Address");
printf("------------------------------------------------------\n");
for (i = 0; i < n; i++)
printf("%-5d %-20s %-30s\n", s[i].id, s[i].name, s[i].address);
}
int main() {
struct Student s[N];
int i;
/* Input */
for (i = 0; i < N; i++) {
printf("\nEnter details of Student %d:\n", i + 1);
printf("ID : ");
scanf("%d", &s[i].id);
printf("Name : ");
scanf(" %[^\n]", s[i].name);
printf("Address : ");
scanf(" %[^\n]", s[i].address);
}
printf("\nBefore Sorting:");
display(s, N);
/* Sort by name */
sortByName(s, N);
printf("\nAfter Sorting (Alphabetical by Name):");
display(s, N);
return 0;
}
Before Sorting:
ID Name Address
------------------------------------------------------
3 Ram Sharma Kathmandu
1 Hari Thapa Pokhara
5 Anita Rai Biratnagar
2 Sita Poudel Chitwan
4 Bishnu KC Butwal
After Sorting (Alphabetical by Name):
ID Name Address
------------------------------------------------------
5 Anita Rai Biratnagar
4 Bishnu KC Butwal
1 Hari Thapa Pokhara
3 Ram Sharma Kathmandu
2 Sita Poudel Chitwan
#include <stdio.h>
#include <string.h>
#define N 10
struct Employee {
char empName[50];
float salary;
char post[30];
};
int main() {
struct Employee emp[N];
int i;
FILE *fp;
/* ---- Input employee records ---- */
printf("Enter details of %d employees:\n", N);
for (i = 0; i < N; i++) {
printf("\nEmployee %d:\n", i + 1);
printf("Name : ");
scanf(" %[^\n]", emp[i].empName);
printf("Salary : ");
scanf("%f", &emp[i].salary);
printf("Post : ");
scanf(" %[^\n]", emp[i].post);
}
/* ---- Write to employee.dat (binary mode) ---- */
fp = fopen("employee.dat", "wb");
if (fp == NULL) {
printf("Error: Cannot create employee.dat\n");
return 1;
}
for (i = 0; i < N; i++)
fwrite(&emp[i], sizeof(struct Employee), 1, fp);
fclose(fp);
printf("\nData written to employee.dat successfully.\n");
/* ---- Read back and search for "manager" (case-insensitive) ---- */
fp = fopen("employee.dat", "rb");
if (fp == NULL) {
printf("Error: Cannot open employee.dat\n");
return 1;
}
struct Employee temp;
int found = 0;
printf("\n--- Employees with post 'manager' ---\n");
printf("%-5s %-20s %-12s %-15s\n", "No.", "Name", "Salary", "Post");
printf("----------------------------------------------\n");
i = 1;
while (fread(&temp, sizeof(struct Employee), 1, fp) == 1) {
/* Convert post to lowercase for case-insensitive comparison */
char postLower[30];
int k;
for (k = 0; temp.post[k]; k++)
postLower[k] = (temp.post[k] >= 'A' && temp.post[k] <= 'Z')
? temp.post[k] + 32 : temp.post[k];
postLower[k] = '\0';
if (strstr(postLower, "manager") != NULL) {
printf("%-5d %-20s %-12.2f %-15s\n", i, temp.empName, temp.salary, temp.post);
found++;
}
i++;
}
fclose(fp);
if (found == 0)
printf("No employee found with post 'manager'.\n");
else
printf("\nTotal manager(s) found: %d\n", found);
return 0;
}
Data written to employee.dat successfully.
--- Employees with post 'manager' ---
No. Name Salary Post
----------------------------------------------
2 Sita Rai 75000.00 Manager
7 Ram Thapa 82000.00 Senior Manager
Total manager(s) found: 2
| Function | Purpose |
|---|---|
| fopen("employee.dat", "wb") | Create/open file for binary writing |
| fwrite() | Write a struct record to the file |
| fopen("employee.dat", "rb") | Open file for binary reading |
| fread() | Read one struct record at a time |
| strstr() | Search for substring "manager" in the post field |
| fclose() | Close the file after operations |
In FORTRAN, the FORMAT statement controls how data is read from input or written to output. Format descriptors specify the type, width, and precision of each field.
| Descriptor | Type | Syntax | Description | Example |
|---|---|---|---|---|
| I | Integer | Iw | Integer in field of width w | I5 → right-justified integer in 5 columns |
| F | Real (Fixed) | Fw.d | Floating-point with w total width, d decimal places | F8.3 → e.g., " 12.345" |
| E | Real (Scientific) | Ew.d | Exponential (scientific) notation | E12.4 → e.g., " 0.1235E+02" |
| A | Character | Aw or A | Character string of width w | A10 → 10-character string field |
| L | Logical | Lw | Logical value (.TRUE. or .FALSE.) in width w | L3 → prints T or F |
| X | Blank/Space | nX | Insert n blank spaces in output or skip n chars in input | 5X → 5 blank spaces |
| T | Tab | Tn | Move to absolute column n (tabbing) | T15 → position cursor at column 15 |
| / | Newline | / | Move to next record (new line) | FORMAT(I5 / F8.2) → two lines |
C FORMAT Examples:
WRITE(*,100) 42, 3.14159, 'Hello'
100 FORMAT(I5, F8.3, 5X, A5)
C Output: " 42 3.142 Hello"
WRITE(*,200) 'Name', 'Score'
200 FORMAT(T1, A10, T15, A5)
C Output: "Name Score" (tabbed at columns 1 and 15)
| Data Type | Keyword | Description | Example |
|---|---|---|---|
| Integer | INTEGER | Whole numbers (positive, negative, zero). Default 4 bytes. | INTEGER N; N = 100 |
| Real | REAL | Single-precision floating-point numbers. Default 4 bytes. | REAL X; X = 3.14 |
| Double Precision | DOUBLE PRECISION | Double-precision floating-point (8 bytes). More accurate than REAL. | DOUBLE PRECISION PI; PI = 3.14159265358979 |
| Complex | COMPLEX | Complex numbers with real and imaginary parts. | COMPLEX Z; Z = (3.0, 4.0) → 3+4i |
| Logical | LOGICAL | Boolean values: .TRUE. or .FALSE. | LOGICAL FLAG; FLAG = .TRUE. |
| Character | CHARACTER | String of characters with specified length. | CHARACTER*20 NAME; NAME = 'Ram Sharma' |
C FORTRAN Data Type Declaration Examples:
INTEGER COUNT, I, J
REAL TEMP, RATE
DOUBLE PRECISION RESULT
COMPLEX Z1, Z2
LOGICAL FLAG
CHARACTER*30 FNAME, LNAME
| Category | Description | Examples |
|---|---|---|
| System Software | Manages and controls hardware; provides a platform for other software to run | Operating System (Windows, Linux), Device Drivers, BIOS, Firmware |
| Application Software | Designed to help users perform specific tasks | MS Word, Excel, VLC Player, Chrome, Photoshop |
| Programming Software / Tools | Used by developers to create, debug, and maintain programs | Compilers, Interpreters, Assemblers, IDEs (VS Code, Dev-C++) |
| Utility Software | Performs maintenance tasks for the computer system | Antivirus, Disk Cleaner, File Compressor (WinZip), Backup tools |
| Embedded Software | Software embedded within hardware devices for specific functions | Washing machine controller, ATM software, Microwave firmware |
| Basis | High Level Language | Low Level Language |
|---|---|---|
| Definition | Closer to human language; uses English-like syntax | Closer to machine language; uses binary or mnemonics |
| Types | 3GL (C, Java, Python), 4GL (SQL), 5GL (Prolog) | Machine Language (1GL), Assembly Language (2GL) |
| Readability | Easy to read, write and understand | Difficult to read and understand |
| Machine Dependency | Machine-independent; portable across platforms | Machine-dependent; specific to hardware |
| Execution Speed | Slower (needs translation) | Faster (directly or near-directly executed) |
| Translator | Compiler or Interpreter | Assembler (for Assembly); none for Machine Language |
| Examples | C, C++, Java, Python, FORTRAN | Binary code (00110001), MOV AX, BX |
+-------------------------+
| Source Code (.c) | Written by programmer in high-level language
+-------------------------+
|
v [PREPROCESSOR]
+-------------------------+
| Preprocessed Code | - Expands #include, #define macros
| (Expanded Source) | - Removes comments
+-------------------------+
|
v [COMPILER]
+-------------------------+
| Assembly Code (.asm) | - Translates HLL to assembly
| | - Checks syntax and semantic errors
+-------------------------+
|
v [ASSEMBLER]
+-------------------------+
| Object Code (.obj) | - Converts assembly to binary machine code
| | - Unresolved external references remain
+-------------------------+
|
v [LINKER]
+-------------------------+
| Executable File (.exe) | - Links object code with libraries
| | - Resolves all function/variable references
+-------------------------+
|
v [LOADER]
+-------------------------+
| Program in Memory | - OS loads executable into RAM
| (Execution / Output) | - CPU executes instructions
+-------------------------+
| Stage | Tool | Input | Output |
|---|---|---|---|
| Preprocessing | Preprocessor | .c file | Expanded source |
| Compilation | Compiler | Expanded source | Assembly (.asm) |
| Assembly | Assembler | .asm | Object file (.obj) |
| Linking | Linker | .obj + libraries | Executable (.exe) |
| Loading | Loader | .exe | Running program |
| Error Type | Description | When Detected | Example |
|---|---|---|---|
| Syntax Error | Violation of grammar rules of the language | Compile time | Missing ;, unmatched {, wrong keyword |
| Logical Error | Program runs but gives wrong result due to incorrect logic | Runtime (by testing) | Using + instead of * |
| Runtime Error | Error that occurs during execution, crashing the program | Runtime | Division by zero, null pointer dereference |
| Semantic Error | Syntactically correct code with unintended meaning | Compile/Runtime | Using uninitialized variable, wrong type |
| Linker Error | Linker cannot resolve references to functions or variables | Link time | Calling undefined function |
Preprocessing directives are instructions beginning with # that are processed by the C preprocessor before compilation. They do not end with a semicolon.
| Directive | Type | Purpose | Example |
|---|---|---|---|
| #include | File Inclusion | Includes header/library files | #include <stdio.h> |
| #define | Macro Definition | Defines constants or macros | #define PI 3.14159 |
| #undef | Macro Removal | Undefines a previously defined macro | #undef PI |
| #ifdef / #ifndef | Conditional Compilation | Compiles code block only if macro is/isn't defined | #ifdef DEBUG ... #endif |
| #if / #else / #endif | Conditional Compilation | Conditional inclusion of code sections | #if MAX > 100 ... #endif |
| #pragma | Special Instructions | Compiler-specific directives | #pragma once |
Algorithm: REVERSE_NUMBER
Step 1: START
Step 2: Read the number N
Step 3: Set rev = 0
Step 4: WHILE N > 0 do:
a. digit = N mod 10
b. rev = rev * 10 + digit
c. N = N / 10 (integer division)
Step 5: Print rev
Step 6: STOP
+----------+
| START |
+----------+
|
v
+------------------+
| Read number N |
+------------------+
|
v
+------------------+
| rev = 0 |
+------------------+
|
v
+--------------------+
| Is N > 0 ? |---No----> +--------------+
+--------------------+ | Print rev |
| Yes +--------------+
v |
+------------------------+ v
| digit = N % 10 | +--------+
| rev = rev * 10+digit | | STOP |
| N = N / 10 | +--------+
+------------------------+
|
+-----(loop back to "Is N > 0?")
| Iteration | N | digit | rev |
|---|---|---|---|
| 1 | 1234 | 4 | 4 |
| 2 | 123 | 3 | 43 |
| 3 | 12 | 2 | 432 |
| 4 | 1 | 1 | 4321 |
| 5 | 0 | — | 4321 (stop) |
%.2f allow exact control over decimal places, making numeric output readable (e.g., displaying currency as 1234.56).%10d align columns in tabular output, essential for reports and tables.printf) to output any data type correctly.- flag (e.g., %-10s) enables left-aligned text for better readability.%e or %g formats large/small numbers in scientific notation for engineering/scientific applications.Quadratic equation: ax² + bx + c = 0
Discriminant: D = b² - 4ac
#include <stdio.h>
#include <math.h>
int main() {
double a, b, c, D;
double root1, root2, realPart, imagPart;
printf("Enter coefficients a, b, c of ax^2 + bx + c = 0:\n");
printf("a = "); scanf("%lf", &a);
printf("b = "); scanf("%lf", &b);
printf("c = "); scanf("%lf", &c);
if (a == 0) {
printf("Not a quadratic equation (a cannot be 0).\n");
return 1;
}
D = b * b - 4 * a * c;
printf("\nDiscriminant D = %.4f\n", D);
if (D > 0) {
/* Two distinct real roots */
root1 = (-b + sqrt(D)) / (2 * a);
root2 = (-b - sqrt(D)) / (2 * a);
printf("Two distinct real roots:\n");
printf(" Root 1 = %+.4f\n", root1);
printf(" Root 2 = %+.4f\n", root2);
}
else if (D == 0) {
/* Two equal real roots */
root1 = -b / (2 * a);
printf("Two equal real roots:\n");
printf(" Root 1 = Root 2 = %+.4f\n", root1);
}
else {
/* Two complex / imaginary roots */
realPart = -b / (2 * a);
imagPart = sqrt(-D) / (2 * a);
printf("Two complex (imaginary) roots:\n");
printf(" Root 1 = %+.4f + %.4fi\n", realPart, imagPart);
printf(" Root 2 = %+.4f - %.4fi\n", realPart, imagPart);
}
return 0;
}
/* Case 1: Two real roots — a=1, b=-5, c=6 */
D = 1.0000
Root 1 = +3.0000
Root 2 = +2.0000
/* Case 2: Equal roots — a=1, b=-4, c=4 */
D = 0.0000
Root 1 = Root 2 = +2.0000
/* Case 3: Imaginary roots — a=1, b=2, c=5 */
D = -16.0000
Root 1 = -1.0000 + 2.0000i
Root 2 = -1.0000 - 2.0000i
default case gracefully handles unexpected input without requiring an extra else condition.break, execution falls through to the next case — useful when multiple cases share the same action.| Basis | switch-case | if-else ladder |
|---|---|---|
| Expression type | Works only with integer or character constants | Works with any Boolean condition (ranges, floats, strings) |
| Readability | Cleaner for multiple fixed values | Can become complex and hard to read for many conditions |
| Speed | Faster (jump table optimization) | Slower (each condition evaluated sequentially) |
| Duplicate case | Duplicate case values not allowed | Any overlapping conditions can be used |
| Range check | Cannot directly check ranges (a < x < b) | Can check ranges and complex conditions easily |
| Default | Has default keyword | Uses final else block |
| Use case | Menu selection, day/month name, grade display | Range-based logic, complex conditions |
#include <stdio.h>
int main() {
int i, sum = 0;
for (i = 1; i <= 100; i++) {
/* Divisible by 5 AND NOT divisible by 3 */
if (i % 5 == 0 && i % 3 != 0) {
sum += i;
printf("%d ", i); /* print qualifying numbers */
}
}
printf("\n\nSum of numbers (divisible by 5, not by 3) from 1 to 100 = %d\n", sum);
return 0;
}
5 10 20 25 35 40 50 55 65 70 80 85 95 100
Sum of numbers (divisible by 5, not by 3) from 1 to 100 = 635
Note: Numbers like 15, 30, 45, 60, 75, 90 are excluded because they are divisible by both 5 and 3.
A function declaration (also called a prototype) tells the compiler the function's return type, name, and the types of its parameters — without the function body. It ends with a semicolon.
Syntax: return_type function_name(parameter_type_list);
Examples:
int add(int a, int b); /* returns int, takes two ints */
float average(float arr[], int n); /* returns float */
void display(void); /* no return, no parameters */
double power(double base, int exp);
/* Function Declaration vs Definition */
int add(int a, int b); /* declaration (prototype) */
int add(int a, int b) { /* definition (has body) */
return a + b;
}
int return type by default, which can cause errors for functions returning other types.#include <stdio.h>
/* Function prototype */
int sumRecursive(int n);
int main() {
int n, result;
printf("Enter a positive integer n: ");
scanf("%d", &n);
if (n < 1) {
printf("Please enter a positive integer.\n");
return 1;
}
result = sumRecursive(n);
printf("Sum of numbers from 1 to %d = %d\n", n, result);
return 0;
}
/* Recursive function: sum of 1 to n */
int sumRecursive(int n) {
if (n == 1)
return 1; /* base case */
return n + sumRecursive(n - 1); /* recursive case */
}
Enter a positive integer n: 5
Sum of numbers from 1 to 5 = 15
Enter a positive integer n: 10
Sum of numbers from 1 to 10 = 55
sumRecursive(5)
= 5 + sumRecursive(4)
= 4 + sumRecursive(3)
= 3 + sumRecursive(2)
= 2 + sumRecursive(1)
= 1 ← base case
= 2 + 1 = 3
= 3 + 3 = 6
= 4 + 6 = 10
= 5 + 10 = 15 ✓
In C, a 1D array is passed to a function by passing the name of the array, which acts as a pointer to its first element. The size must also be passed separately since the function doesn't know the array's size on its own.
/* Method 1: Using array notation */
void display(int arr[], int n) { ... }
/* Method 2: Using pointer notation (equivalent) */
void display(int *arr, int n) { ... }
/* Calling the function */
int marks[5] = {90, 85, 78, 92, 88};
display(marks, 5); /* 'marks' is passed — no & needed */
The name of an array in a function call represents the address of the first element of the array (i.e., &arr[0]). It is a constant pointer. This means:
display(marks, 5) is equivalent to display(&marks[0], 5).#include <stdio.h>
/* Single function to find both largest and smallest */
/* Results returned via pointer parameters */
void findLargestSmallest(int arr[], int n, int *largest, int *smallest) {
int i;
*largest = arr[0];
*smallest = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] > *largest)
*largest = arr[i];
if (arr[i] < *smallest)
*smallest = arr[i];
}
}
int main() {
int arr[100], n, largest, smallest;
int i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
/* Pass array to function */
findLargestSmallest(arr, n, &largest, &smallest);
/* Display result in calling (main) function */
printf("\nArray elements: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\nLargest element = %d\n", largest);
printf("Smallest element = %d\n", smallest);
return 0;
}
Enter number of elements: 6
Enter 6 elements:
45 12 78 34 90 5
Array elements: 45 12 78 34 90 5
Largest element = 90
Smallest element = 5
A structure is a user-defined data type that groups variables of different types under a single name using the struct keyword.
/* Syntax: Structure Definition */
struct structure_name {
data_type member1;
data_type member2;
...
};
/* Method 1: Declare variable separately */
struct Point {
int x;
int y;
};
struct Point p1, p2; /* variable declaration */
/* Method 2: Declare at definition */
struct Rectangle {
float length;
float width;
} r1, r2;
/* Method 3: Using typedef for convenience */
typedef struct {
char name[50];
int age;
} Person;
Person p; /* no 'struct' keyword needed */
/* Accessing members using dot operator */
p1.x = 10;
p1.y = 20;
p.age = 25;
#include <stdio.h>
#include <string.h>
#define MAX 100
#define SUBJECTS 5
struct Student {
char name[50];
int rollNo;
char program[30];
float marks[SUBJECTS];
float total;
};
int main() {
struct Student s[MAX];
int count = 0, i, j;
char choice;
printf("=== Student Record Entry ===\n");
printf("Press 'e' to stop entering records.\n\n");
while (1) {
printf("Enter details for Student %d:\n", count + 1);
printf(" Name : ");
scanf(" %[^\n]", s[count].name);
/* Check if user wants to exit */
if (strcmp(s[count].name, "e") == 0 || strcmp(s[count].name, "E") == 0)
break;
printf(" Roll No : ");
scanf("%d", &s[count].rollNo);
printf(" Program : ");
scanf(" %[^\n]", s[count].program);
s[count].total = 0;
for (j = 0; j < SUBJECTS; j++) {
printf(" Marks in Subject %d: ", j + 1);
scanf("%f", &s[count].marks[j]);
s[count].total += s[count].marks[j];
}
count++;
printf("Press 'e' then Enter to stop, or press Enter to continue: ");
scanf(" %c", &choice);
if (choice == 'e' || choice == 'E')
break;
printf("\n");
}
/* Display all student details */
printf("\n============================================================\n");
printf(" STUDENT DETAILS \n");
printf("============================================================\n");
printf("%-4s %-15s %-6s %-12s %-6s %-6s %-6s %-6s %-6s %-8s\n",
"No.", "Name", "Roll", "Program",
"S1", "S2", "S3", "S4", "S5", "Total");
printf("------------------------------------------------------------\n");
for (i = 0; i < count; i++) {
printf("%-4d %-15s %-6d %-12s ",
i+1, s[i].name, s[i].rollNo, s[i].program);
for (j = 0; j < SUBJECTS; j++)
printf("%-6.1f ", s[i].marks[j]);
printf("%-8.1f\n", s[i].total);
}
printf("============================================================\n");
printf("Total students entered: %d\n", count);
return 0;
}
============================================================
STUDENT DETAILS
============================================================
No. Name Roll Program S1 S2 S3 S4 S5 Total
------------------------------------------------------------
1 Ram Sharma 101 BCE 78.0 85.0 90.0 72.0 88.0 413.0
2 Sita Rai 102 BCT 92.0 76.0 81.0 89.0 95.0 433.0
============================================================
Total students entered: 2
A pointer is a variable that stores the memory address of another variable rather than a direct value. Pointers enable dynamic memory allocation, efficient array manipulation, and passing variables by reference.
Syntax: data_type *pointer_name;
int x = 10;
int *ptr = &x; /* ptr holds address of x */
printf("%d\n", x); /* prints value: 10 */
printf("%p\n", ptr); /* prints address of x */
printf("%d\n", *ptr); /* dereference: prints 10 */
*ptr = 25; /* changes x to 25 via pointer */
In C, an array name is a constant pointer to its first element. Array subscript notation and pointer arithmetic are interchangeable.
| Array Notation | Pointer Notation | Meaning |
|---|---|---|
| arr | &arr[0] | Address of first element |
| arr[i] | *(arr + i) | Value at index i |
| &arr[i] | arr + i | Address of element i |
| *arr | arr[0] | First element's value |
int arr[4] = {10, 20, 30, 40};
int *ptr = arr;
/* Both notations are equivalent */
printf("%d\n", arr[2]); /* 30 */
printf("%d\n", *(ptr + 2)); /* 30 */
printf("%d\n", *(arr + 2)); /* 30 */
printf("%d\n", ptr[2]); /* 30 */
/* Difference: pointer can be incremented, array name cannot */
ptr++; /* valid: ptr now points to arr[1] */
/* arr++; is ILLEGAL — arr is a constant pointer */
#include <stdio.h>
/* Custom strcpy using pointer arguments */
void myStrcpy(char *dest, const char *src) {
/* Copy each character from src to dest until null terminator */
while (*src != '\0') {
*dest = *src; /* copy character */
dest++; /* advance destination pointer */
src++; /* advance source pointer */
}
*dest = '\0'; /* append null terminator to destination */
}
int main() {
char source[100], destination[100];
printf("Enter source string: ");
scanf(" %[^\n]", source);
/* Before copy */
printf("\nBefore myStrcpy:\n");
printf(" source = \"%s\"\n", source);
printf(" destination = \"%s\" (empty)\n", destination);
myStrcpy(destination, source);
/* After copy */
printf("\nAfter myStrcpy:\n");
printf(" source = \"%s\"\n", source);
printf(" destination = \"%s\"\n", destination);
return 0;
}
Enter source string: Hello Nepal
Before myStrcpy:
source = "Hello Nepal"
destination = "" (empty)
After myStrcpy:
source = "Hello Nepal"
destination = "Hello Nepal"
| Step | *src | *dest | Action |
|---|---|---|---|
| 1 | 'H' | 'H' | Copy 'H', advance both |
| 2 | 'i' | 'i' | Copy 'i', advance both |
| 3 | '\0' | — | Exit loop, write '\0' to dest |
The fopen() function is used to open a file. It takes the filename and a mode string as arguments and returns a FILE * pointer (or NULL on failure).
Syntax: FILE *fp = fopen("filename", "mode");
| Mode | Description | File Exists? | File Missing? |
|---|---|---|---|
"r" | Open for reading only | Opens normally | Returns NULL |
"w" | Open for writing only (truncates/creates) | Truncated (emptied) | New file created |
"a" | Open for appending (writes at end) | Appends at end | New file created |
"r+" | Open for reading and writing | Opens normally | Returns NULL |
"w+" | Open for reading and writing (truncates/creates) | Truncated | New file created |
"a+" | Open for reading and appending | Appends at end | New file created |
"rb" | Open binary file for reading | Opens normally | Returns NULL |
"wb" | Open binary file for writing | Truncated | New file created |
"ab" | Open binary file for appending | Appends | New file created |
#include <stdio.h>
#include <string.h>
int main() {
char str[500];
char filename[] = "output.txt";
FILE *fp;
char ch;
/* Step 1: Read a string from user */
printf("Enter a string to write to file:\n");
scanf(" %[^\n]", str);
/* Step 2: Write the string to the file */
fp = fopen(filename, "w"); /* open in write mode */
if (fp == NULL) {
printf("Error: Cannot create file '%s'\n", filename);
return 1;
}
fprintf(fp, "%s\n", str); /* write string to file */
fclose(fp);
printf("\nString successfully written to '%s'.\n", filename);
/* Step 3: Read the file and display its content */
fp = fopen(filename, "r"); /* open in read mode */
if (fp == NULL) {
printf("Error: Cannot open file '%s'\n", filename);
return 1;
}
printf("\nContent of '%s':\n", filename);
printf("-----------------------------\n");
while ((ch = fgetc(fp)) != EOF)
putchar(ch); /* print each character to screen */
printf("-----------------------------\n");
fclose(fp);
return 0;
}
Enter a string to write to file:
Hello! This is Computer Programming CT401.
String successfully written to 'output.txt'.
Content of 'output.txt':
-----------------------------
Hello! This is Computer Programming CT401.
-----------------------------
| Function | Purpose |
|---|---|
| fopen(name, mode) | Opens a file in the given mode; returns FILE pointer |
| fprintf(fp, format, ...) | Writes formatted data to the file |
| fgetc(fp) | Reads one character from the file |
| fclose(fp) | Closes the file and flushes the buffer |
| EOF | End-of-file marker returned by fgetc when file ends |
| Data Type | Keyword | Size | Description | Example |
|---|---|---|---|---|
| Integer | INTEGER | 4 bytes (default) | Stores whole numbers (positive, negative, zero). No decimal point. | INTEGER N; N = 100 |
| Real | REAL | 4 bytes | Single-precision floating-point number. About 6–7 significant digits. | REAL X; X = 3.14 |
| Double Precision | DOUBLE PRECISION | 8 bytes | Double-precision floating-point. About 15–16 significant digits. More accurate than REAL. | DOUBLE PRECISION PI; PI = 3.14159265358979D0 |
| Complex | COMPLEX | 8 bytes | Stores complex numbers with real and imaginary parts. | COMPLEX Z; Z = (3.0, 4.0) — represents 3+4i |
| Logical | LOGICAL | 4 bytes | Stores Boolean values: .TRUE. or .FALSE. | LOGICAL FLAG; FLAG = .TRUE. |
| Character | CHARACTER | 1 byte per char | Stores strings/characters. Length specified with *n. | CHARACTER*20 NAME; NAME = 'Ram Sharma' |
C FORTRAN Data Type Declaration Examples:
INTEGER COUNT, I, J, N
REAL TEMP, RATE, AREA
DOUBLE PRECISION RESULT, PI
COMPLEX Z1, Z2
LOGICAL FLAG, FOUND
CHARACTER*30 FNAME, LNAME
CHARACTER*1 GRADE
PROGRAM PALINDROME
C Check if a number entered by user is palindrome
INTEGER N, ORIG, REV, DIGIT
WRITE(*,*) 'Enter a positive integer:'
READ(*,*) N
ORIG = N
REV = 0
C Reverse the number
10 IF (N .GT. 0) THEN
DIGIT = MOD(N, 10)
REV = REV * 10 + DIGIT
N = N / 10
GO TO 10
END IF
C Compare original with reversed
IF (ORIG .EQ. REV) THEN
WRITE(*,*) ORIG, ' is a PALINDROME.'
ELSE
WRITE(*,*) ORIG, ' is NOT a palindrome.'
END IF
STOP
END
Enter a positive integer:
12321
12321 is a PALINDROME.
Enter a positive integer:
1234
1234 is NOT a palindrome.
| Iteration | N | DIGIT (N mod 10) | REV |
|---|---|---|---|
| 1 | 121 | 1 | 1 |
| 2 | 12 | 2 | 12 |
| 3 | 1 | 1 | 121 |
| 4 | 0 | — | stop |
ORIG = 121 = REV = 121 → PALINDROME
CHAPTERWISE MOST REPEATED QUESTIONS WITH THEIR SOLUTIONS
An instruction is a single operation command that directs the computer to perform a specific task (e.g., add two numbers, store a value in memory).
A program is a finite, ordered set of instructions written in a programming language that directs the computer to solve a specific problem.
| Generation | Name | Example | Features |
|---|---|---|---|
| 1GL | Machine Language | 0101 1001... | Binary (0s & 1s); directly executed by CPU; machine-dependent; very fast but hard to write |
| 2GL | Assembly Language | MOV AX, 5 | Mnemonic codes; needs assembler to convert; machine-dependent; faster than high-level |
| 3GL | High-Level Language | C, FORTRAN, Pascal | Human-readable; needs compiler/interpreter; machine-independent; portable |
| 4GL | Very High-Level Language | SQL, MATLAB | Domain-specific; minimal code for complex tasks; used in databases and reports |
| 5GL | AI / Natural Language | Prolog, LISP | Based on logic/constraints; used in AI and expert systems |
| Basis | System Software | Application Software |
|---|---|---|
| Definition | Manages hardware and provides platform for other software | Performs specific tasks for end-users |
| Examples | OS (Windows, Linux), Device Drivers, Compilers | MS Word, Photoshop, Games, Web Browser |
| Purpose | Controls computer resources | Solves user problems |
| User Interaction | Runs in background, minimal direct interaction | Directly used by end-users |
| Dependency | Can run without application software | Depends on system software to run |
| Language | Written in low-level/system languages (C, Assembly) | Written in high-level languages |
An algorithm is a finite, ordered, and unambiguous set of instructions designed to solve a specific problem in a finite amount of time and resources.
Testing is the process of running a program with various input data to check whether the output is correct and the program behaves as expected.
Debugging is the process of identifying, locating, and fixing errors (bugs) in a program.
| Error Type | Description | Example |
|---|---|---|
| Syntax Error | Violation of language grammar rules; detected by compiler | Missing semicolon, wrong keyword |
| Runtime Error | Occurs during execution; causes program to crash | Division by zero, null pointer |
| Logical Error | Program runs but gives wrong output; hardest to find | Using + instead of *, wrong condition |
| Semantic Error | Syntactically correct but wrong meaning | int age = "twenty"; |
An expression is a combination of operands (variables, constants) and operators that evaluates to a single value. Every expression has a type and a value.
| Type | Description | Example |
|---|---|---|
| Arithmetic | Produces a numeric value | a + b * c |
| Relational | Compares two values; produces 0 or 1 | a > b, x == y |
| Logical | Combines boolean conditions | a && b, !x |
| Assignment | Assigns value to a variable | x = 5, a += 3 |
| Conditional (Ternary) | Selects value based on condition | a > b ? a : b |
| Bitwise | Operates on individual bits | a & b, x | y |
| Comma | Evaluates multiple expressions left to right | (a=5, b=10, a+b) |
| Function | Syntax | Description |
|---|---|---|
| printf() | printf("format", vars); | Formatted output to screen. Supports %d, %f, %s, %c etc. |
| scanf() | scanf("format", &vars); | Reads formatted input. Uses & for non-string variables. |
| Function | Syntax | Description |
|---|---|---|
| getch() | ch = getch(); | Reads single char; no echo; no Enter needed. (conio.h) |
| getche() | ch = getche(); | Reads single char; echoes it; no Enter needed. (conio.h) |
| getchar() | ch = getchar(); | Reads single char; echoes; waits for Enter. (stdio.h) |
| putchar() | putchar(ch); | Prints a single character to screen. |
| gets() | gets(str); | Reads a full string including spaces until Enter. (deprecated) |
| puts() | puts(str); | Prints string and adds newline automatically. |
#include <stdio.h>
int main() {
int age;
char name[50];
printf("Enter name: ");
scanf("%s", name); // reads one word
printf("Enter age: ");
scanf("%d", &age);
printf("Name: %s, Age: %d\n", name, age);
return 0;
}
Operator precedence determines the order in which operators are evaluated in an expression when multiple operators are present.
Example: In 2 + 3 * 4, multiplication has higher precedence than addition, so result = 2 + 12 = 14 (not 20).
Associativity determines the order of evaluation when two operators of the same precedence appear in an expression.
8 - 3 - 2 = (8-3)-2 = 3a = b = 5 → a = (b = 5)| Precedence | Operators | Associativity |
|---|---|---|
| 1 (Highest) | () [] . -> | Left to Right |
| 2 | ! ~ ++ -- (unary) * & | Right to Left |
| 3 | * / % | Left to Right |
| 4 | + - | Left to Right |
| 5 | < <= > >= | Left to Right |
| 6 | == != | Left to Right |
| 7 | && | Left to Right |
| 8 | || | Left to Right |
| 9 (Lowest) | = += -= *= /= | Right to Left |
| Basis | Formatted I/O | Unformatted I/O |
|---|---|---|
| Definition | Input/output with specific format specifiers | Input/output without format specifiers |
| Functions | printf(), scanf(), fprintf(), fscanf() | getch(), getche(), getchar(), gets(), puts(), putchar() |
| Data Types | Can handle int, float, char, string with %d, %f, %c, %s | Mainly handles single characters or strings |
| Control | Full control over format, width, precision | No format control |
| Header | stdio.h | stdio.h, conio.h |
| Example | printf("%5.2f", x); | ch = getch(); |
| Basis | Nested if | else-if Ladder |
|---|---|---|
| Structure | if inside another if; forms tree structure | if followed by multiple else-if; linear chain |
| Use | For multi-level conditions depending on each other | For mutually exclusive conditions (one OR another) |
| Readability | Becomes complex with deep nesting | More readable for multiple choices |
if (a > 0) {
if (a % 2 == 0)
printf("Positive Even");
else
printf("Positive Odd");
} else {
printf("Negative");
}
if (marks >= 90) printf("A+");
else if (marks >= 80) printf("A");
else if (marks >= 70) printf("B");
else if (marks >= 60) printf("C");
else printf("Fail");
#include <stdio.h>
int main() {
int n, i, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
isPrime = 0; // 0 and 1 are not prime
} else {
for (i = 2; i * i <= n; i++) {
if (n % i == 0) {
isPrime = 0;
break;
}
}
}
if (isPrime)
printf("%d is PRIME\n", n);
else
printf("%d is COMPOSITE\n", n);
return 0;
}
An Armstrong number (Narcissistic number) is a number where the sum of each digit raised to the power of the total number of digits equals the number itself. E.g., 153 = 1³+5³+3³ = 153.
#include <stdio.h>
#include <math.h>
int main() {
int n, temp, digit, digits = 0, sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
temp = n;
// Count digits
while (temp != 0) { digits++; temp /= 10; }
temp = n;
// Sum of (each digit)^digits
while (temp != 0) {
digit = temp % 10;
sum += (int)pow(digit, digits);
temp /= 10;
}
if (sum == n)
printf("%d is an Armstrong number\n", n);
else
printf("%d is NOT an Armstrong number\n", n);
return 0;
}
Immediately exits the loop or switch statement. Program continues after the loop.
for (i=1; i<=10; i++) {
if (i == 5) break; // exits when i=5
printf("%d ", i); // prints 1 2 3 4
}
Skips the rest of the current loop iteration and moves to the next iteration.
for (i=1; i<=5; i++) {
if (i == 3) continue; // skips i=3
printf("%d ", i); // prints 1 2 4 5
}
| while | do-while |
|---|---|
| Entry-controlled loop | Exit-controlled loop |
| Condition checked before execution | Condition checked after execution |
| Body may execute 0 times | Body executes at least once |
| while (cond) { body; } | do { body; } while (cond); |
| Basis | Call by Value | Call by Reference |
|---|---|---|
| What is passed | Copy of the actual value | Address (reference) of the variable |
| Effect on original | Original variable NOT changed | Original variable IS changed |
| How | Normal parameters | Pointer parameters (using & and *) |
| Memory | Extra memory for copy | No extra memory (uses same location) |
void change(int x) {
x = 100; // only local copy is changed
}
int main() {
int a = 10;
change(a);
printf("%d", a); // Output: 10 (unchanged)
return 0;
}
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 5, b = 10;
swap(&a, &b);
printf("a=%d b=%d", a, b); // Output: a=10 b=5
return 0;
}
#include <stdio.h>
long long factorial(int n) {
if (n == 0 || n == 1) // base case
return 1;
return n * factorial(n - 1); // recursive call
}
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %lld\n", n, factorial(n));
return 0;
}
#include <stdio.h>
int fib(int n) {
if (n == 0) return 0; // base case
if (n == 1) return 1; // base case
return fib(n-1) + fib(n-2); // recursive case
}
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
printf("Fibonacci(%d) = %d\n", n, fib(n));
/* To print full series: */
printf("Series: ");
for(int i=0; i<=n; i++)
printf("%d ", fib(i));
return 0;
}
A function prototype declares the function's name, return type, and parameter types to the compiler before the function is actually defined (used). This allows calling the function before its definition.
/* Syntax */
return_type function_name(parameter_type_list);
/* Example */
int add(int, int); // prototype
int main() {
printf("%d", add(3,4)); // called before definition
}
int add(int a, int b) { // definition
return a + b;
}
#include <stdio.h>
int main() {
char str[100];
int i, len = 0;
printf("Enter a string: ");
gets(str);
// Find length manually
while (str[len] != '\0') len++;
// Print in reverse
printf("Reversed: ");
for (i = len - 1; i >= 0; i--)
printf("%c", str[i]);
printf("\n");
return 0;
}
#include <stdio.h>
int main() {
int a[10], i, max, min;
printf("Enter 10 numbers:\n");
for (i = 0; i < 10; i++)
scanf("%d", &a[i]);
max = min = a[0];
for (i = 1; i < 10; i++) {
if (a[i] > max) max = a[i];
if (a[i] < min) min = a[i];
}
printf("Largest = %d\n", max);
printf("Smallest = %d\n", min);
return 0;
}
#include <stdio.h>
int main() {
char str[100];
int len = 0;
printf("Enter string: ");
gets(str);
while (str[len] != '\0')
len++;
printf("Length = %d\n", len);
return 0;
}
#include <stdio.h>
int main() {
int m, n, i, j, a[10][10];
printf("Enter rows and columns: ");
scanf("%d %d", &m, &n);
printf("Enter matrix elements:\n");
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
printf("Transpose:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
printf("%d\t", a[j][i]); // note: a[j][i]
printf("\n");
}
return 0;
}
A structure is a user-defined data type in C that allows grouping of different data types under a single name. Unlike arrays (which store same-type elements), structures can store elements of different types.
#include <stdio.h>
struct Distance {
int feet;
float inch;
};
int main() {
struct Distance d1, d2, sum;
printf("Enter d1 (feet inch): ");
scanf("%d %f", &d1.feet, &d1.inch);
printf("Enter d2 (feet inch): ");
scanf("%d %f", &d2.feet, &d2.inch);
sum.feet = d1.feet + d2.feet;
sum.inch = d1.inch + d2.inch;
// Carry over excess inches
if (sum.inch >= 12.0) {
sum.feet += 1;
sum.inch -= 12.0;
}
printf("Sum = %d feet %.2f inches\n", sum.feet, sum.inch);
return 0;
}
A nested structure is a structure that contains another structure as one of its members. It allows modeling complex hierarchical data relationships.
#include <stdio.h>
#include <string.h>
struct Address {
char city[50];
char district[50];
};
struct Student {
char name[50];
int roll;
float marks;
struct Address addr; // nested structure
};
int main() {
int n, i, j;
printf("Enter number of students: ");
scanf("%d", &n);
struct Student s[n];
for (i = 0; i < n; i++) {
printf("Name: "); scanf("%s", s[i].name);
printf("Roll: "); scanf("%d", &s[i].roll);
printf("Marks: "); scanf("%f", &s[i].marks);
printf("City: "); scanf("%s", s[i].addr.city);
}
// Bubble sort by marks (descending)
struct Student temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (s[j].marks < s[j+1].marks) {
temp = s[j]; s[j] = s[j+1]; s[j+1] = temp;
}
}
}
printf("\nStudents in order of marks:\n");
for (i = 0; i < n; i++)
printf("%s\t%d\t%.2f\t%s\n", s[i].name, s[i].roll, s[i].marks, s[i].addr.city);
return 0;
}
Pointer arithmetic allows performing mathematical operations on pointers. The operations are scaled by the size of the data type being pointed to.
| Operation | Description |
|---|---|
| ptr++ | Moves pointer to next element (adds sizeof(type) bytes) |
| ptr-- | Moves pointer to previous element |
| ptr + n | Points to nth element ahead |
| ptr2 - ptr1 | Number of elements between two pointers |
| *ptr | Dereference: access the value at pointer address |
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to arr[0]
printf("*ptr = %d\n", *ptr); // 10
ptr++;
printf("After ++ = %d\n", *ptr); // 20
printf("ptr+2 = %d\n", *(ptr+2)); // 40
// If int is 4 bytes: address increases by 4 each step
printf("Address: %u\n", (unsigned)ptr);
printf("Next: %u\n", (unsigned)(ptr+1)); // +4
return 0;
}
#include <stdio.h>
int main() {
int a, b, *p1, *p2;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
p1 = &a; p2 = &b;
printf("Sum = %d\n", *p1 + *p2);
printf("Difference = %d\n", *p1 - *p2);
printf("Product = %d\n", *p1 * *p2);
return 0;
}
| Basis | Console I/O | File I/O |
|---|---|---|
| Medium | Keyboard (input) and Screen (output) | Files on disk (permanent storage) |
| Functions | printf(), scanf(), getch() | fprintf(), fscanf(), fread(), fwrite() |
| Persistence | Data lost when program ends | Data saved permanently |
| Speed | Slower (depends on user) | Faster for large data |
| Requires | No file opening/closing | fopen() and fclose() required |
#include <stdio.h>
int main() {
FILE *fp;
char name[50];
int id;
float salary;
fp = fopen("employee.txt", "r");
if (fp == NULL) {
printf("File not found!\n");
return 1;
}
printf("Employees with salary > 50000:\n");
while (fscanf(fp, "%s %d %f", name, &id, &salary) != EOF) {
if (salary > 50000)
printf("Name: %s, ID: %d, Salary: %.2f\n", name, id, salary);
}
fclose(fp);
return 0;
}
| Basis | Text File | Binary File |
|---|---|---|
| Storage | Stores data as readable ASCII characters | Stores data in binary (0s and 1s) |
| Readability | Can be opened in any text editor | Not human-readable; looks like garbage |
| Size | Usually larger | Smaller, more efficient |
| Functions | fprintf(), fscanf(), fgets(), fputs() | fread(), fwrite() |
| New Line | '\n' converted to OS-specific (CRLF on Windows) | No conversion; stored as-is |
| Extension | .txt, .csv | .bin, .dat, .exe |
#include <stdio.h>
int main() {
FILE *src, *dest;
char ch;
src = fopen("source.txt", "r");
dest = fopen("destination.txt", "w");
if (src == NULL || dest == NULL) {
printf("Error opening file!\n");
return 1;
}
while ((ch = fgetc(src)) != EOF)
fputc(ch, dest);
printf("File copied successfully!\n");
fclose(src);
fclose(dest);
return 0;
}
| Basis | C | FORTRAN |
|---|---|---|
| Full Name | C Programming Language | FORmula TRANslation |
| Purpose | General purpose / systems | Scientific and numerical computing |
| Array Index | Starts at 0 | Starts at 1 (default) |
| String Handling | char arrays with '\0' | CHARACTER data type |
| Case Sensitive | Yes | No (case-insensitive) |
| Pointers | Explicit pointer support | Limited pointer support |
| I/O | printf/scanf | READ/WRITE with FORMAT |
| Comments | // or /* */ | C or ! at start of line (in F77/F90) |
C 1D Array:
INTEGER A(10) ! Array of 10 integers (index 1 to 10)
REAL X(5) ! Array of 5 reals
C 2D Array:
INTEGER MAT(3,4) ! 3 rows, 4 columns
REAL B(10,10) ! 10x10 matrix
PROGRAM TRANSPOSE
INTEGER A(10,10), T(10,10), M, N, I, J
WRITE(*,*) 'Enter rows and columns:'
READ(*,*) M, N
WRITE(*,*) 'Enter matrix elements:'
DO 10 I = 1, M
DO 10 J = 1, N
READ(*,*) A(I,J)
10 CONTINUE
WRITE(*,*) 'Transpose matrix:'
DO 20 I = 1, N
DO 30 J = 1, M
T(I,J) = A(J,I)
WRITE(*,100) T(I,J)
30 CONTINUE
WRITE(*,*)
20 CONTINUE
100 FORMAT(I5,$)
STOP
END
The Arithmetic IF evaluates an arithmetic expression and branches to one of three labels based on whether the result is negative, zero, or positive.
Syntax: IF (expression) label1, label2, label3
label1 if expression < 0label2 if expression = 0label3 if expression > 0 PROGRAM NUMCHECK
INTEGER N
WRITE(*,*) 'Enter a number:'
READ(*,*) N
IF (N) 10, 20, 30
10 WRITE(*,*) 'Number is NEGATIVE'
GOTO 40
20 WRITE(*,*) 'Number is ZERO'
GOTO 40
30 WRITE(*,*) 'Number is POSITIVE'
40 STOP
END
Syntax: IF (logical expression) statement — executes statement only if true.
IF (N .LT. 0) WRITE(*,*) 'Negative'
IF (N .EQ. 0) WRITE(*,*) 'Zero'
IF (N .GT. 0) WRITE(*,*) 'Positive'
FORTRAN relational operators: .EQ. .NE. .LT. .LE. .GT. .GE.
PROGRAM PALINDROME
INTEGER N, TEMP, REV, DIGIT
WRITE(*,*) 'Enter a number:'
READ(*,*) N
TEMP = N
REV = 0
10 IF (TEMP .EQ. 0) GOTO 20
DIGIT = MOD(TEMP, 10)
REV = REV * 10 + DIGIT
TEMP = TEMP / 10
GOTO 10
20 IF (REV .EQ. N) THEN
WRITE(*,*) N, 'is PALINDROME'
ELSE
WRITE(*,*) N, 'is NOT a palindrome'
END IF
STOP
END
PROGRAM program_name ← Program heading
C Comment line ← Comments (C in column 1)
C Declaration section:
INTEGER/REAL/CHARACTER... ← Variable declarations
C Executable section:
READ (*,*) ... ← Input
[computation statements] ← Processing
WRITE (*,*) ... ← Output
STOP ← Stop execution
END ← End of program
FORTRAN is column-based: Columns 1-5 = statement labels; Column 6 = continuation character; Columns 7-72 = statements.
| Data Type | Declaration | Example |
|---|---|---|
| Integer | INTEGER X | Whole numbers |
| Real | REAL X | Floating point (single precision) |
| Double Precision | DOUBLE PRECISION X | Higher precision float |
| Complex | COMPLEX Z | Complex numbers (a+bi) |
| Logical | LOGICAL FLAG | .TRUE. or .FALSE. |
| Character | CHARACTER*20 NAME | String of characters |
PROGRAM FIBONACCI
INTEGER N, I, A, B, TEMP
WRITE(*,*) 'Enter the number of terms:'
READ(*,*) N
A = 0
B = 1
WRITE(*,*) 'Fibonacci sequence:'
DO 10 I = 1, N
WRITE(*,100) A
TEMP = A + B
A = B
B = TEMP
10 CONTINUE
100 FORMAT(I5)
STOP
END
Fibonacci sequence:
0
1
1
2
3
5
8
13
| Type | Construct | Description |
|---|---|---|
| Conditional | if, if-else, else if | Executes block based on condition |
| Multi-way | switch-case | Selects branch based on value of expression |
| Loop | for | Counter-controlled iteration |
| Loop | while | Pre-test condition loop |
| Loop | do-while | Post-test condition loop (executes at least once) |
| Jump | break | Exits loop or switch immediately |
| Jump | continue | Skips current iteration, continues loop |
| Jump | goto | Unconditional jump to a label |
/* Example: for loop in C */
for (i = 1; i <= 10; i++) {
printf("%d\n", i);
}
| Type | Construct | Description |
|---|---|---|
| Conditional | IF (logical IF) | Single-line conditional execution |
| Conditional | IF-THEN-ELSE-END IF | Block conditional (FORTRAN 77+) |
| Multi-way | IF-ELSE IF ladder | Multiple condition checking (no switch) |
| Loop | DO loop | Counter-controlled iteration with label |
| Loop | DO WHILE | Condition-controlled loop (FORTRAN 77+) |
| Jump | GO TO | Unconditional jump to a statement label |
| Jump | Computed GO TO | Jumps to one of several labels based on index |
| Stop | STOP | Terminates program execution |
C Example: DO loop in FORTRAN
DO 10 I = 1, 10
WRITE(*,*) I
10 CONTINUE
C Example: IF-THEN-ELSE in FORTRAN
IF (A .GT. B) THEN
WRITE(*,*) 'A is greater'
ELSE
WRITE(*,*) 'B is greater'
END IF
| Feature | C | FORTRAN |
|---|---|---|
| Switch/Multi-way | switch-case available | No switch; uses IF-ELSE IF ladder |
| Loop syntax | for, while, do-while | DO loop and DO WHILE only |
| Loop control | break, continue | No direct equivalent in FORTRAN 77 |
| Goto | goto (rarely used) | GO TO with statement labels (common in F77) |
| Condition syntax | ==, !=, >, < | .EQ., .NE., .GT., .LT., .GE., .LE. |
The FORMAT statement in FORTRAN is used to specify the exact layout and appearance of input/output data. It controls how data is read from or written to a device by defining field widths, decimal places, spacing, and data types. It is always used with READ and WRITE statements via a statement label.
WRITE(*,100) X
100 FORMAT(...) ! FORMAT is referenced by label 100
Used for integer input/output. Syntax: Iw where w is the total field width.
INTEGER N
N = 42
WRITE(*,100) N
100 FORMAT(I5)
C Output: 42 (right-justified in 5 character wide field)
Used for real (floating-point) input/output. Syntax: Fw.d where w is total field width and d is number of decimal places.
REAL X
X = 3.14159
WRITE(*,200) X
200 FORMAT(F8.3)
C Output: 3.142 (8 chars wide, 3 decimal places)
PROGRAM PRIME
INTEGER N, I, FLAG
WRITE(*,*) 'Enter a number:'
READ(*,*) N
FLAG = 0
IF (N .LE. 1) THEN
FLAG = 1
END IF
DO 10 I = 2, N/2
IF (MOD(N, I) .EQ. 0) THEN
FLAG = 1
END IF
10 CONTINUE
IF (FLAG .EQ. 0) THEN
WRITE(*,*) N, 'is a prime number.'
ELSE
WRITE(*,*) N, 'is not a prime number.'
END IF
STOP
END
Enter a number:
7
7 is a prime number.