Programming C
Programming C
Programming with C Output Object/machine code Directly executes • To share data between programs
UG-CBCS II-SEM | Both Papers (2023-24 & 2026 OLD) Call by Value vs Call by Reference: Common File Functions:
>> PAPER 1 — 2023-24 Feature Call by Value Call by Reference Function Purpose
>> Q1(a) Write an algorithm and draw a flowchart to find the What is passed Copy of the value Address of the variable fopen() Open a file
area of a circle of a given Original value changed? No Yes fclose() Close a file
How to use Normal variable Pointer variable (&, *) fprintf() Write to file
radius. Example: fscanf() Read from file
Algorithm:
#include <stdio.h> feof() Check end of file
Step 1: Start // Call by Value Example:
Step 2: Read the value of radius (r) void callByValue(int x) { #include <stdio.h>
Step 3: Calculate area = 3.14159 × r × r x = x + 10; // Change not reflected outside int main() {
Step 4: Print area } FILE *f;
Step 5: Stop // Call by Reference f = fopen("[Link]", "w"); // Open for writing
Flowchart: void callByRef(int *x) { fprintf(f, "Hello World"); // Write to file
[START] *x = *x + 10; // Change IS reflected outside fclose(f); // Close file
| } return 0;
[Read radius r] int main() { }
| int a = 5, b = 5; Command Line Arguments: These are values passed to the program when it is
[area = 3.14159 * r * r] callByValue(a); run
| printf("Call by Value: a = %d\n", a); // Output: 5 (unchanged) from the terminal/command prompt.
[Print area] callByRef(&b); #include <stdio.h>
| printf("Call by Reference: b = %d\n", b); // Output: 15 int main(int argc, char *argv[]) {
[STOP] (changed) printf("Number of arguments: %d\n", argc);
C Program: return 0; printf("Program name: %s\n", argv[0]);
} printf("First argument: %s\n", argv[1]);
#include <stdio.h>
int main() {
>> Q2(c) Write a program to reverse the digits of a 3-digit return 0;
float r, area; number using a for loop. }
printf("Enter radius: "); #include <stdio.h> • argc = number of arguments (always at least 1)
scanf("%f", &r); int main() { • argv[] = array of argument strings
area = 3.14159 * r * r; int n, rev = 0, digit; • Run as: ./program Hello → argv[1] = "Hello"
printf("Area of circle = %.2f", area); printf("Enter a 3-digit number: "); >> Q4(a) What is an Array? Explain memory allocation for 1D
return 0; scanf("%d", &n); array of size 5.
} for (; n > 0; n = n / 10) {
What is an Array? An array is a collection of same type variables stored in
>> Q1(b) What is the purpose of printf() and scanf()? Why and digit = n % 10;
continuous
when do we use #include rev = rev * 10 + digit;
memory locations, accessed using an index.
}
directive? Example: int a[5]; stores 5 integers.
printf("Reversed number = %d", rev);
printf(): Memory Allocation for int a[5]:
return 0;
• printf() is used to print/display output on the screen. • Size of int = 4 bytes
}
• Example: printf("Hello"); prints Hello on screen.
Example: Input: 123 → Output: 321 • Total memory = 5 × 4 = 20 bytes
• We can print text, numbers, variables using it. • Memory is continuous (one after another)
• Example: printf("Sum = %d", sum);
>> Q3(a) What are Structures? Declaration, Definition, and
Index: a[0] a[1] a[2] a[3] a[4]
scanf(): difference between Array Address: 1000 1004 1008 1012 1016
• scanf() is used to take input from the user (keyboard). of Structures vs Structure of Arrays. |--4--|--4--|--4--|--4--|--4--|
• Example: scanf("%d", &n); reads an integer from user. What is a Structure? A structure is a user-defined data type in C that groups • Base address = 1000 (assumed)
#include directive: different • Address of a[i] = Base address + i × size of data type
• #include is a preprocessor directive used to include a header file in our types of variables under one name. Declaration:
program before compilation. Example: A student has name (string), age (int), marks (float) — all int a[5]; // Declares array of 5 integers
• We use it when we need built-in functions that are stored in header files. different types but int b[5] = {1,2,3,4,5}; // With initialization
• Example: related. >> Q4(b) Program to add two 1D arrays and store result in third
o #include <stdio.h> → needed for printf() and scanf() Declaration: array.
o #include <math.h> → needed for sqrt(), pow() etc. struct Student {
o #include <string.h> → needed for string functions #include <stdio.h>
int rollno; int main() {
• It is written at the top of every C program, before the main() function. char name[20]; int a[5] = {1, 2, 3, 4, 5};
>> Q1(c) Write an algorithm and flowchart to find the sum of float marks; int b[5] = {4, 8, 7, 2, 6};
digits of an n-digit }; int c[5];
number. Definition (Creating a variable): for (int i = 0; i < 5; i++) {
struct Student s1; // One student c[i] = a[i] + b[i];
Algorithm:
struct Student s[50]; // Array of 50 students }
Step 1: Start Array of Structures vs Structure of Arrays:
Step 2: Read the number (n) printf("Array A: ");
Array of Structures Structure of Arrays for (int i = 0; i < 5; i++)
Step 3: Set sum = 0 Each element is a complete structure Each field is stored in a separate array
Step 4: While n > 0, do: printf("%d ", a[i]);
struct Student s[10] Separate arrays: name[], age[], marks[] printf("\nArray B: ");
digit = n % 10 Easy to manage records Hard to manage related data for (int i = 0; i < 5; i++)
sum = sum + digit Commonly used Rarely used printf("%d ", b[i]);
n = n / 10 Array of Structures Example: printf("\nArray C (Sum): ");
Step 5: Print sum struct Student { for (int i = 0; i < 5; i++)
Step 6: Stop int rollno; printf("%d ", c[i]);
Flowchart: char name[20]; return 0;
[START] }; }
| struct Student s[10]; // 10 student records Output:
[Read number n] >> Q3(b) Structure for Student Data with functions. Array A: 1 2 3 4 5
[sum = 0] #include <stdio.h> Array B: 4 8 7 2 6
| #include <string.h> Array C: 5 10 10 6 11
[Is n > 0?] --NO--> [Print sum] --> [STOP] struct Student { >> Q4(c) What is a Pointer? Difference from regular variable,
| YES int rollno; use in functions,
[digit = n % 10] char name[30];
char dept[20]; advantages.
[sum = sum + digit]
char course[20]; What is a Pointer? A pointer is a variable that stores the memory address of
[n = n / 10]
int year; another
|
}; variable.
(loop back)
struct Student s[50]; int a = 10;
C Program: int *p = &a; // p stores address of a
int n;
#include <stdio.h> // Function (i): Print names of students who joined in a printf("%d", *p); // prints 10 (value at address)
int main() { particular year Pointer vs Regular Variable:
int n, sum = 0, digit; void printByYear(int yr) { Regular Variable Pointer Variable
printf("Enter a number: "); printf("Students who joined in %d:\n", yr); Stores a value (like 10) Stores an address (like 1000)
scanf("%d", &n); for (int i = 0; i < n; i++) { int a = 10; int *p = &a;
while (n > 0) { if (s[i].year == yr) a gives value directly *p gives value at address
digit = n % 10; printf("%s\n", s[i].name); No special symbol needed Uses * and &
sum = sum + digit; } Using Pointer to Pass to Function:
n = n / 10; } #include <stdio.h>
} // Function (ii): Print data of student by roll number void addTen(int *x) {
printf("Sum of digits = %d", sum); void printByRoll(int roll) { *x = *x + 10; // changes original value
return 0; for (int i = 0; i < n; i++) { }
} if (s[i].rollno == roll) { int main() {
>> Q2(a) Write essential attributes of a function. Write a printf("Roll: %d\n", s[i].rollno); int a = 5;
function to check if a number printf("Name: %s\n", s[i].name); addTen(&a);
is odd or even. printf("Dept: %s\n", s[i].dept); printf("a = %d", a); // Output: 15
Essential Attributes (Features) of a Function: printf("Course: %s\n", s[i].course); return 0;
printf("Year: %d\n", s[i].year); }
1. Function Name – Every function has a unique name (e.g., add, check)
return; Advantages of Pointers as Function Arguments:
2. Return Type – The data type of the value the function returns (e.g., int, void)
} 1. Changes to the variable inside the function are reflected outside (call by
3. Parameters – Input values passed to the function
} reference)
4. Function Body – The set of statements inside the function
printf("Student not found.\n");
5. Return Statement – Used to return a value from the function 2. Saves memory — no copy is made
}
6. Function Declaration (Prototype) – Tells the compiler about the function before 3. Useful for returning multiple values
int main() {
it is used 4. Efficient for passing arrays and strings to functions
printf("Enter number of students: ");
Function to check odd or even: scanf("%d", &n); >> PAPER 2 — 2026 (OLD)
#include <stdio.h> for (int i = 0; i < n; i++) { >> Q1(a) What is an Algorithm? Characteristics of a good
void checkOddEven(int n) { printf("Enter roll, name, dept, course, year:\n"); algorithm. Fibonacci series
if (n % 2 == 0) scanf("%d %s %s %s %d",
printf("%d is Even", n); algorithm.
&s[i].rollno, s[i].name, s[i].dept,
else What is an Algorithm? An algorithm is a step-by-step method to solve a problem.
s[i].course, &s[i].year);
printf("%d is Odd", n); It is
}
} written in simple English (not code) before writing an actual program.
int yr;
int main() { Characteristics of a Good Algorithm:
printf("Enter year to search: ");
int num; 1. Clear and simple – each step should be easy to understand
scanf("%d", &yr);
printf("Enter a number: "); printByYear(yr); 2. Input – should have zero or more inputs
scanf("%d", &num); int roll; 3. Output – must produce at least one output
checkOddEven(num); printf("Enter roll number to search: "); 4. Finite – must end after a fixed number of steps
return 0; scanf("%d", &roll); 5. Effective – each step must be doable and practical
} printByRoll(roll); 6. Unambiguous – no step should have double meaning
>> Q2(b) Difference between Interpreter and Compiler. Call by return 0; Algorithm for Fibonacci Series up to N terms:
Value vs Call by } Step 1: Start
Reference. >> Q3(c) File Handling in C and Command Line Arguments. Step 2: Read N (number of terms)
Compiler vs Interpreter: File Handling in C: File handling means reading from and writing to files stored Step 3: Set a = 0, b = 1, count = 2
Feature Compiler Interpreter on Step 4: Print a and b
Translates the whole program at once Yes No (line by line) disk. Step 5: While count < N, do:
Speed Faster execution Slower Why is it used? c=a+b
Error detection After whole translation Line by line • To save data permanently (even after program ends) Print c
Example C, C++ Python, BASIC • To read/write large amounts of data a=b
b=c
Programming with C | UG-CBCS II-SEM | 2023-24 & 2026 OLD | Page 2/2
count = count + 1 if (i == 5) }
Step 6: Stop break; // Loop stops at i=5 >> Q4(b) Difference between Structure and Union. Employee
C Program: printf("%d ", i); Salary Program.
#include <stdio.h> }
Structure vs Union:
int main() { // Output: 1 2 3 4
continue statement: Feature Structure Union
int n, a = 0, b = 1, c;
• Skips the current iteration and moves to the next one. Keyword struct union
printf("Enter number of terms: ");
• The loop does not exit; it just skips that step. Feature Structure Union
scanf("%d", &n);
printf("%d %d ", a, b); for (int i = 1; i <= 10; i++) {
Separate memory for each Shared memory (largest
for (int i = 2; i < n; i++) { if (i == 5) Memory
c = a + b; continue; // Skips printing 5 member member)
printf("%d ", c); printf("%d ", i); All members
a = b; } Yes, at the same time Only one at a time
b = c; // Output: 1 2 3 4 6 7 8 9 10 accessible?
} >> Q3(a) Call by Value vs Call by Reference. Can a function Size Sum of all members Size of largest member
return 0; return multiple values? Example:
} Call by Value:
struct S { int a; float b; }; // Size = 4 + 4 = 8 bytes
>> Q1(b) What is Precedence and Associativity of Operators? • A copy of the variable is passed.
union U { int a; float b; }; // Size = 4 bytes (largest)
Precedence: Precedence tells which operator is calculated first when there are Employee Salary Program:
• Original variable is NOT changed.
multiple operators in an expression. #include <stdio.h>
Call by Reference:
Example: 2 + 3 * 4 Here * has higher precedence than +, so: 3 * 4 = 12 struct Employee {
• The address of the variable is passed using pointers. char name[30];
first, then 2 + 12 = • Original variable IS changed. int age;
14 #include <stdio.h> float basic;
Associativity: When two operators have the same precedence, associativity tells void byValue(int x) { x = 100; } };
us void byRef(int *x) { *x = 100; } int main() {
the direction — left to right or right to left. int main() { struct Employee e[10];
Arithmetic Operator Associativity (Left to Right): int a = 10, b = 10; float da, hra, total;
5 - 3 + 2 → (5 - 3) + 2 = 4 (Left to Right) byValue(a); for (int i = 0; i < 10; i++) {
Logical Operator Associativity: printf("By Value: %d\n", a); // 10 (unchanged) printf("Enter name, age, basic salary:\n");
&& and || → Left to Right byRef(&b); scanf("%s %d %f", e[i].name, &e[i].age, &e[i].basic);
! → Right to Left printf("By Ref: %d\n", b); // 100 (changed) }
Example: 1 && 0 || 1 → (1 && 0) || 1 → 0 || 1 → 1 return 0; printf("\nName\t\tAge\tTotal Salary\n");
} for (int i = 0; i < 10; i++) {
Precedence Table (High to Low): Can a function return multiple values? A function in C can return only one value da = 0.10 * e[i].basic;
Operator Type Associativity directly using return. However, we can return multiple values using pointers (call hra = 0.05 * e[i].basic;
() [] Bracket Left to Right by total = e[i].basic + da + hra;
! ++ -- Unary Right to Left reference): printf("%s\t\t%d\t%.2f\n", e[i].name, e[i].age, total);
Operator Type Associativity #include <stdio.h> }
* / % Multiply Left to Right void sumDiff(int a, int b, int *s, int *d) { return 0;
+ - Add/Sub Left to Right *s = a + b; }
< > <= >= Relational Left to Right *d = a - b; >> Q4(c) Text vs Binary Files. Program to count alphabets,
== != Equality Left to Right }
&& Logical AND Left to Right
digits, vowels, and words in
int main() {
`` a file.
int s, d;
= Assignment Right to Left sumDiff(10, 4, &s, &d); Text File vs Binary File:
>> Q1(c) Range of Data Types and Primary Data Types in C. printf("Sum = %d, Diff = %d", s, d); Feature Text File Binary File
// Output: Sum = 14, Diff = 6 Data stored as Characters (ASCII) Binary (0s and 1s)
Primary Data Types in C:
return 0; Human readable Yes No
Data Type Size Range Use
} Examples .txt, .c, .html .exe, .jpg, .mp3
int 2 or 4 bytes -32768 to 32767 (2 bytes) Whole numbers
>> Q3(b) Storage Classes: auto, static, external. Opened with fopen("file","r") fopen("file","rb")
float 4 bytes 3.4e-38 to 3.4e+38 Decimal numbers
double 8 bytes 1.7e-308 to 1.7e+308 Large decimals Storage classes define the scope (where it can be used) and lifetime (how long it New line handling Converted (\n, \r\n) No conversion
char 1 byte -128 to 127 Single character exists) Program to count alphabets, digits, vowels, and words:
void 0 bytes No value Functions with no return of a variable. #include <stdio.h>
Examples: #include <ctype.h>
1. auto (Automatic):
int a = 100; int main() {
• Default storage class for local variables FILE *f;
float b = 3.14; • Exists only inside the function
double c = 99999.9999; char ch, prev = ' ';
• Value is lost when function ends int alpha = 0, digit = 0, vowel = 0, words = 0;
char d = 'A';
void func() { f = fopen("[Link]", "r");
Modifiers: auto int x = 10; // same as: int x = 10;
• unsigned int → 0 to 65535 if (f == NULL) {
printf("%d", x); printf("File not found.");
• long int → larger range than int } return 1;
• short int → smaller range 2. static: }
>> Q2(a) Types of Looping Statements. Difference between • Variable retains its value even after the function ends while ((ch = fgetc(f)) != EOF) {
while and do-while. • Initialized only once if (isalpha(ch)) alpha++;
Types of Loops in C: void count() { if (isdigit(ch)) digit++;
1. for loop static int c = 0; char lower = tolower(ch);
2. while loop c++; if (lower == 'a' || lower == 'e' || lower == 'i' ||
3. do-while loop printf("Count = %d\n", c); lower == 'o' || lower == 'u')
while vs do-while: } vowel++;
Feature while loop do-while loop int main() { // Count words: a word starts after a space/newline
Condition check Before the loop body After the loop body count(); // Count = 1 if ((ch != ' ' && ch != '\n') &&
Minimum execution 0 times (if condition false) At least 1 time always count(); // Count = 2 (prev == ' ' || prev == '\n'))
Syntax while(cond) { } do { } while(cond); count(); // Count = 3 words++;
while loop example: return 0; prev = ch;
} }
int i = 1;
while (i <= 5) { 3. extern (External): fclose(f);
printf("%d ", i); • Used to access a variable defined in another file or outside the function printf("Alphabets : %d\n", alpha);
i++; • Shares variable across multiple files printf("Digits : %d\n", digit);
} extern int x; // x is declared somewhere else printf("Vowels : %d\n", vowel);
printf("%d", x); printf("Words : %d\n", words);
// Output: 1 2 3 4 5
do-while loop example: Summary Table: return 0;
Storage Class Scope Lifetime Default Value }
int i = 1;
do { auto Local (function) Function Garbage
printf("%d ", i); static Local Entire program 0
i++; extern Global Entire program 0
} while (i <= 5); register Local Function Garbage
// Output: 1 2 3 4 5 >> Q3(c) Advantages of Pointers over Arrays. Function to
// Even if condition is false at start, it runs ONCE concatenate two strings
for loop example: using pointers.
for (int i = 1; i <= 5; i++) { Advantages of Pointers over Arrays:
printf("%d ", i);
1. Pointers can be changed to point anywhere; arrays are fixed
}
2. Pointers are faster for accessing elements
>> Q2(b) Find and explain output of the following code
3. Dynamic memory allocation is done using pointers
snippets. 4. Pointers can traverse strings and arrays more efficiently
Code (i): 5. Pointer arithmetic allows easy navigation of memory
void main () { Function to concatenate two strings using pointers:
int fun (int); #include <stdio.h>
int i = fun(10); void concat(char *s1, char *s2) {
printf("%d\n", --i); // Move s1 pointer to the end of s1
} while (*s1 != '\0')
int fun(int i) { s1++;
return (i++); // Copy s2 into s1 from the end
} while (*s2 != '\0') {
Explanation: *s1 = *s2;
• fun(10) is called → inside fun, i++ means return current value (10) THEN s1++;
increment s2++;
• So fun(10) returns 10 }
• i = 10 *s1 = '\0'; // End the string
• --i = pre-decrement → i becomes 9 before printing }
• Output: 9 int main() {
Code (ii): char str1[50] = "Hello ";
void main() { char str2[] = "World";
int i = 4, j = -1, k = 0, w, x, y, z; concat(str1, str2);
w = i || j || k; printf("Result: %s", str1); // Output: Hello World
x = i && j && k; return 0;
y = i || j && k; }
z = i && j || k; >> Q4(a) Define TimeStruct and display time in 16:40:30 format.
printf("%d %d %d %d\n", w, x, y, z); #include <stdio.h>
} struct TimeStruct {
Explanation: int hour;
• w = 4 || -1 || 0 → 4 is non-zero = TRUE → w = 1 int minute;
• x = 4 && -1 && 0 → 0 is false → x = 0 int second;
};
• y = 4 || (-1 && 0) → && first: -1 && 0 = 0; then 4 || 0 = 1 → y = 1
int main() {
• z = (4 && -1) || 0 → && first: 4 && -1 = 1; then 1 || 0 = 1 → z = 1
struct TimeStruct t;
Output: 1 0 1 1 [Link] = 16;
>> Q2(c) Role of break and continue in a loop. [Link] = 40;
break statement: [Link] = 30;
• Immediately exits the loop when encountered. printf("Time: %02d:%02d:%02d\n", [Link], [Link], [Link]);
• Used when we want to stop the loop based on a condition. // Output: Time: 16:40:30
for (int i = 1; i <= 10; i++) { return 0;