0% found this document useful (0 votes)
42 views35 pages

CP QB Ans

The document provides a comprehensive overview of C programming concepts, including algorithms, flowcharts, and various programming tasks. It covers topics such as data types, control structures, and specific C programs for tasks like calculating sums, averages, and checking conditions. Additionally, it includes examples of using loops, switch statements, and functions to demonstrate fundamental programming techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views35 pages

CP QB Ans

The document provides a comprehensive overview of C programming concepts, including algorithms, flowcharts, and various programming tasks. It covers topics such as data types, control structures, and specific C programs for tasks like calculating sums, averages, and checking conditions. Additionally, it includes examples of using loops, switch statements, and functions to demonstrate fundamental programming techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

C PROGRAMMING QB ANS

-Himalee Patil

Module 1: INTRODUCTION TO ALGORITHM AND


FLOWCHART

Q: Write an algorithm to find sum of two numbers.


A:

1. Start
2. Read two numbers A and B
3. Sum = A + B
4. Display Sum
5. Stop

Q: Differentiate between Low-Level language and High-Level language


A:

• Low-Level: Close to hardware, difficult to understand (e.g., Assembly).


• High-Level: Human-readable, easier to code (e.g., C, Python).

Q: Define the flowchart. Draw the flowchart “to find the given number is even or odd.”
A:

• Flowchart: Diagram representing algorithm using symbols.


• Even/Odd Flowchart:
o Start → Input N → N % 2 == 0? → Yes → Print "Even" → End
→ No → Print "Odd" → End
(Drawing not possible here, but you can follow this logic to sketch it.)

Q: Write an algorithm and draw flowchart to find factorial of a number.


A:

1. Start
2. Read number N
3. Set fact = 1
4. Loop i = 1 to N → fact = fact * i
5. Display fact
6. Stop

Q: Write an algorithm "To calculate the perimeter and area of rectangle."


A:

1. Start
2. Read length and width
3. Perimeter = 2 × (length + width)
4. Area = length × width
5. Display both
6. Stop

Q: What is a flowchart? List any four symbols used in a flowchart


A:

• Flowchart: Visual representation of logic steps


• Symbols:
o Terminator (Start/Stop)
o Input/Output
o Process
o Decision
Q: Write an algorithm “to calculate the simple interest using the formula SI =
PNR/100.”
A:

1. Start
2. Read P, N, R
3. SI = (P × N × R) / 100
4. Display SI
5. Stop

Q: Flowchart to find average of three numbers


A:

1. Start
2. Read A, B, C
3. Avg = (A + B + C) / 3
4. Display Avg
5. Stop

(Use process, input/output and terminator symbols)

Q: Describe algorithm “To calculate perimeter and area of rectangle.”


A:
(Same as above)

Q: What is pseudo code? Give pseudo code for given program statement.
A:

• Pseudo code: Plain-language steps representing a program.


• Example:

mathematica
CopyEdit
Start
Read A, B
Sum = A + B
Print Sum
End

Q: Write an algorithm and draw flowchart


a. Check whether the entered number is positive or negative number.

1. Start
2. Read N
3. If N > 0 → Print "Positive"
4. Else → Print "Negative"
5. Stop

b. To reverse a number

1. Start
2. Read N
3. Rev = 0
4. While N > 0
Digit = N % 10
Rev = Rev * 10 + Digit
N = N / 10
5. Print Rev
6. Stop

Module 2: FUNDAMENTALS OF C-PROGRAMMING


Q: Write a C program to find the largest of three numbers using the ternary operator

c
CopyEdit
#include <stdio.h>
void findLargest() {
int a, b, c, max;
printf("Enter 3 numbers: ");
scanf("%d %d %d", &a, &b, &c);
max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
printf("Largest = %d\n", max);
}

Q: Write a program to calculate the average of 3 numbers.

c
CopyEdit
#include <stdio.h>
void average() {
int a, b, c;
float avg;
printf("Enter 3 numbers: ");
scanf("%d %d %d", &a, &b, &c);
avg = (a + b + c) / 3.0;
printf("Average = %.2f\n", avg);
}

Q: Write a C program to check if a given number is even or odd using the modulus
operator.

c
CopyEdit
#include <stdio.h>
void evenOdd() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (n % 2 == 0)
printf("Even\n");
else
printf("Odd\n");
}

Q: Write a C program to take a string input using gets() and display it using puts()

c
CopyEdit
#include <stdio.h>
void stringInputOutput() {
char str[100];
printf("Enter a string: ");
gets(str);
puts(str);
}

Q: What are Bitwise Operators in C? List all Bitwise Operators.

A:
Bitwise operators perform operations on bits:

• & AND
• | OR
• ^ XOR
• ~ NOT
• << Left Shift
• >> Right Shift

Q: Write a program to find if a number is even or odd using ternary operator.

c
CopyEdit
#include <stdio.h>
void checkEvenOdd() {
int n;
printf("Enter number: ");
scanf("%d", &n);
(n % 2 == 0) ? printf("Even\n") : printf("Odd\n");
}
Q: Write a program to find minimum number among two numbers using ternary
operator

c
CopyEdit
#include <stdio.h>
void findMin() {
int a, b, min;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
min = (a < b) ? a : b;
printf("Minimum = %d\n", min);
}

Q: Discuss the fundamental and derived data types of the C language with examples.

A:

• Fundamental: int, char, float, double


• Derived: array, pointer, structure, union

Q: Give output of following program (with use of different operators)


Please upload the program to provide output.

Q: WAP to accept basic salary and calculate gross salary with 50% DA and 40% HRA

c
CopyEdit
#include <stdio.h>
void calcGrossSalary() {
float basic, gross;
printf("Enter basic salary: ");
scanf("%f", &basic);
gross = basic + (0.5 * basic) + (0.4 * basic);
printf("Gross Salary = %.2f\n", gross);
}

Let me know if you'd like me to continue with Module 3: Control Structures.

4o

You said:

yes

ChatGPT said:

Continuing with Module 3: CONTROL STRUCTURES — answers are in C and follow void
method style.

Q: What is the purpose of a switch statement? How does it differ from if-else?
A:
Switch is used for multi-way branching based on a variable.

• Switch: Better for fixed values.


• If-else: Works for ranges, conditions.

Q: WAP to check whether the number entered is divisible by 10 or not.

c
CopyEdit
#include <stdio.h>
void checkDivisibleBy10() {
int n;
printf("Enter number: ");
scanf("%d", &n);
if (n % 10 == 0)
printf("Divisible by 10\n");
else
printf("Not divisible by 10\n");
}

Q: WAP to find number of days in a month using switch case. Explain the need of break
keyword in switch case
A:
break exits the switch to prevent fall-through.

c
CopyEdit
#include <stdio.h>
void daysInMonth() {
int month;
printf("Enter month (1-12): ");
scanf("%d", &month);
switch(month) {
case 2:
printf("28 or 29 days\n");
break;
case 4: case 6: case 9: case 11:
printf("30 days\n");
break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
printf("31 days\n");
break;
default:
printf("Invalid month\n");
}
}

Q: Write a C program to print numbers from 1 to 10 using a for loop.

c
CopyEdit
#include <stdio.h>
void print1to10() {
for (int i = 1; i <= 10; i++)
printf("%d ", i);
}

Q: C program to calculate grade of student based on marks using if-else ladder

c
CopyEdit
#include <stdio.h>
void calcGrade() {
int marks;
printf("Enter marks: ");
scanf("%d", &marks);
if (marks >= 90)
printf("Grade A\n");
else if (marks >= 75)
printf("Grade B\n");
else if (marks >= 60)
printf("Grade C\n");
else if (marks >= 40)
printf("Grade D\n");
else
printf("Fail\n");
}

Q: Write a program to print Floyd’s Triangle

c
CopyEdit
#include <stdio.h>
void floydTriangle() {
int n, num = 1;
printf("Enter number of rows: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
printf("%d ", num++);
printf("\n");
}
}

Q: WAP using switch to compute i) sqrt ii) square iii) cube iv) factorial v) prime factors

c
CopyEdit
#include <stdio.h>
#include <math.h>
void computeChoice() {
int choice, n, i;
long fact = 1;
printf("Enter number: ");
scanf("%d", &n);
printf("1.SQRT 2.SQUARE 3.CUBE 4.FACTORIAL 5.PRIME FACTORS\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch(choice) {
case 1: printf("SQRT = %.2f\n", sqrt(n)); break;
case 2: printf("SQUARE = %d\n", n*n); break;
case 3: printf("CUBE = %d\n", n*n*n); break;
case 4:
for (i = 1; i <= n; i++) fact *= i;
printf("Factorial = %ld\n", fact);
break;
case 5:
printf("Prime factors: ");
for (i = 2; n > 1; i++) {
while (n % i == 0) {
printf("%d ", i);
n /= i;
}
}
break;
default: printf("Invalid\n");
}
}

Q: WAP to check whether the entered number is palindrome or not

c
CopyEdit
#include <stdio.h>
void checkPalindrome() {
int n, rev = 0, rem, orig;
printf("Enter number: ");
scanf("%d", &n);
orig = n;
while (n > 0) {
rem = n % 10;
rev = rev * 10 + rem;
n /= 10;
}
if (rev == orig)
printf("Palindrome\n");
else
printf("Not Palindrome\n");
}

Module 3: CONTROL STRUCTURES


Q: Compare while loop with do while loop.
A:

• while: condition is checked before loop body.


• do while: loop runs at least once, condition checked after.

Q: Program to check if number is Armstrong or not


(Armstrong: sum of cube of digits = number)

c
CopyEdit
#include <stdio.h>
void checkArmstrong() {
int n, temp, sum = 0, digit;
printf("Enter number: ");
scanf("%d", &n);
temp = n;
while (temp > 0) {
digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if (sum == n)
printf("Armstrong\n");
else
printf("Not Armstrong\n");
}

Q: Program to find sum of 1 to 10 numbers using Do while loop

c
CopyEdit
#include <stdio.h>
void sumDoWhile() {
int i = 1, sum = 0;
do {
sum += i;
i++;
} while (i <= 10);
printf("Sum = %d\n", sum);
}

Q: WAP to print the following pattern (stars)

markdown
CopyEdit
*
**
***
****
*****

c
CopyEdit
#include <stdio.h>
void printPattern() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++)
printf("*");
printf("\n");
}
}

Q: Menu-driven program for Add, Subtract, Multiply, Divide, Modulus using switch

c
CopyEdit
#include <stdio.h>
void arithmeticMenu() {
int a, b, choice;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
printf("1.Add 2.Sub 3.Mul 4.Div 5.Mod\n");
printf("Enter choice: ");
scanf("%d", &choice);
switch(choice) {
case 1: printf("Sum = %d\n", a + b); break;
case 2: printf("Diff = %d\n", a - b); break;
case 3: printf("Product = %d\n", a * b); break;
case 4:
if (b != 0) printf("Div = %d\n", a / b);
else printf("Divide by 0 Error\n");
break;
case 5:
if (b != 0) printf("Mod = %d\n", a % b);
else printf("Divide by 0 Error\n");
break;
default: printf("Invalid\n");
}
}

Q: Program to find sum and average of 1 to 10 numbers using for loop

c
CopyEdit
#include <stdio.h>
void sumAverageFor() {
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
printf("Sum = %d\nAverage = %.2f\n", sum, sum / 10.0);
}

Q: Program to print weekday name using switch case

c
CopyEdit
#include <stdio.h>
void weekDayName() {
int day;
printf("Enter day number (1-7): ");
scanf("%d", &day);
switch(day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
case 6: printf("Saturday\n"); break;
case 7: printf("Sunday\n"); break;
default: printf("Invalid\n");
}
}

Q: Program to input alphabet and check vowel or consonant using switch

c
CopyEdit
#include <stdio.h>
void checkVowel() {
char ch;
printf("Enter an alphabet: ");
scanf(" %c", &ch);
switch(ch) {
case 'a': case 'e': case 'i': case 'o': case 'u':
case 'A': case 'E': case 'I': case 'O': case 'U':
printf("Vowel\n"); break;
default:
printf("Consonant\n");
}
}

Q: Program to display table of any number using do while

c
CopyEdit
#include <stdio.h>
void displayTable() {
int n, i = 1;
printf("Enter number: ");
scanf("%d", &n);
do {
printf("%d x %d = %d\n", n, i, n * i);
i++;
} while (i <= 10);
}

Q: Explain continue, break and goto with examples

A:

• continue: skips rest of loop and starts next iteration


• break: exits loop or switch
• goto: jumps to a labeled part of program (use sparingly)

c
CopyEdit
void exampleBreakContinue() {
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
if (i == 5) break;
printf("%d ", i);
}
}

c
CopyEdit
void exampleGoto() {
int i = 1;
start:
if (i > 3) return;
printf("%d ", i++);
goto start;
}

Q: WAP to calculate sum of given series x + x² + x³ + ... + x^m

c
CopyEdit
#include <stdio.h>
#include <math.h>
void sumSeries() {
int x, m, sum = 0;
printf("Enter x and m: ");
scanf("%d %d", &x, &m);
for (int i = 1; i <= m; i++)
sum += pow(x, i);
printf("Sum = %d\n", sum);
}

Q: WAP to display pattern

yaml
CopyEdit
12345
1234
123
12
1

c
CopyEdit
#include <stdio.h>
void patternNumbers() {
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++)
printf("%d", j);
printf("\n");
}
}

Q: WAP to accept number and display: a) number of digits b) sum of digits c) product
of digits

c
CopyEdit
#include <stdio.h>
void digitInfo() {
int n, count = 0, sum = 0, product = 1, digit;
printf("Enter number: ");
scanf("%d", &n);
while (n > 0) {
digit = n % 10;
sum += digit;
product *= digit;
count++;
n /= 10;
}
printf("Digits: %d\nSum: %d\nProduct: %d\n", count, sum, product);
}

Module 4: ARRAYS, STRINGS, STRUCTURE AND


UNION
Q: Define structure and union. Write the differences.
A:

• Structure: All members occupy separate memory.


• Union: All members share same memory.
• Use struct and union keywords.

Q: Write a C program to input and display a 2D array of size 3x3.

c
CopyEdit
#include <stdio.h>
void inputDisplay2D() {
int a[3][3];
printf("Enter 3x3 matrix:\n");
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
scanf("%d", &a[i][j]);
printf("Matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
printf("%d ", a[i][j]);
printf("\n");
}
}

Q: What are built-in functions in string.h? Explain any 4 with example.

A:
Common string functions:

• strlen() – gets length


• strcpy() – copies string
• strcmp() – compares
• strcat() – concatenates

c
CopyEdit
void stringFunctions() {
char a[50] = "Hello", b[50] = "World";
printf("Length: %lu\n", strlen(a));
strcpy(b, a);
printf("Copy: %s\n", b);
strcat(a, " World");
printf("Concat: %s\n", a);
printf("Compare: %d\n", strcmp("abc", "abd"));
}

Q: Define a structure Student with name, roll number and marks. Accept and display 5
students.

c
CopyEdit
#include <stdio.h>
struct Student {
char name[20];
int roll;
float marks;
};

void studentDetails() {
struct Student s[5];
for (int i = 0; i < 5; i++) {
printf("Enter name, roll, marks: ");
scanf("%s %d %f", s[i].name, &s[i].roll, &s[i].marks);
}
for (int i = 0; i < 5; i++) {
printf("%s %d %.2f\n", s[i].name, s[i].roll, s[i].marks);
}
}

Q: Explain the following string functions:


a) strcpy() b) strlen() c) strcmp() d) strcat() e) puts() f) getch()

A:

• strcpy() – copy strings


• strlen() – length of string
• strcmp() – compare strings
• strcat() – append string
• puts() – prints string
• getch() – gets a char (no echo)

Q: Discuss the concept of an Array with examples.


A:
Array stores multiple values of same type in one variable.
Example: int a[5] = {1, 2, 3, 4, 5};
Q: WAP to count the number of even numbers in the array

c
CopyEdit
#include <stdio.h>
void countEven() {
int a[5], count = 0;
printf("Enter 5 numbers: ");
for (int i = 0; i < 5; i++) {
scanf("%d", &a[i]);
if (a[i] % 2 == 0) count++;
}
printf("Even numbers = %d\n", count);
}

Q: WAP to display five elements of an array

c
CopyEdit
#include <stdio.h>
void displayArray() {
int a[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++)
printf("%d ", a[i]);
}

Q: WAP to display addition of two matrices of size mxn

c
CopyEdit
#include <stdio.h>
void addMatrices() {
int m = 2, n = 2, a[2][2], b[2][2], sum[2][2];
printf("Enter elements of matrix A:\n");
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
scanf("%d", &a[i][j]);
printf("Enter elements of matrix B:\n");
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
scanf("%d", &b[i][j]);
printf("Sum:\n");
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
sum[i][j] = a[i][j] + b[i][j];
printf("%d ", sum[i][j]);
}
printf("\n");
}
}

Q: WAP to find transpose of a matrix and use function to do it

c
CopyEdit
#include <stdio.h>
void transpose(int a[2][2], int b[2][2]) {
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
b[j][i] = a[i][j];
}

void useTranspose() {
int a[2][2], b[2][2];
printf("Enter 2x2 matrix:\n");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
scanf("%d", &a[i][j]);
transpose(a, b);
printf("Transpose:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
printf("%d ", b[i][j]);
printf("\n");
}
}

Q: Program to search an element in array

c
CopyEdit
#include <stdio.h>
void searchArray() {
int a[5], key, found = 0;
printf("Enter 5 elements: ");
for (int i = 0; i < 5; i++) scanf("%d", &a[i]);
printf("Enter number to search: ");
scanf("%d", &key);
for (int i = 0; i < 5; i++) {
if (a[i] == key) {
found = 1;
break;
}
}
if (found)
printf("Found\n");
else
printf("Not Found\n");
}

Q: Write a C program to reverse a string with and without using built-


in functions.

c
CopyEdit
#include <stdio.h>
#include <string.h>

void reverseWithFunction() {
char str[100];
printf("Enter string: ");
gets(str);
strrev(str);
printf("Reversed: %s\n", str);
}

void reverseWithoutFunction() {
char str[100];
int i, len;
printf("Enter string: ");
gets(str);
len = strlen(str);
printf("Reversed: ");
for (i = len - 1; i >= 0; i--)
putchar(str[i]);
printf("\n");
}

Q: WAP to accept EMPLOYEE details (Name, Designation, Gender, DOJ,


Salary). Define functions to compute:
i) Total number of employees
ii) Employees with salary > 20,000

c
CopyEdit
#include <stdio.h>
struct Employee {
char name[20], designation[20], gender[10];
char doj[20];
float salary;
};

void processEmployees() {
struct Employee e[5];
int count = 0;
for (int i = 0; i < 5; i++) {
printf("Enter name, designation, gender, DOJ, salary:\n");
scanf("%s %s %s %s %f", e[i].name, e[i].designation,
e[i].gender, e[i].doj, &e[i].salary);
count++;
}
printf("Total employees = %d\n", count);
printf("Employees with salary > 20000:\n");
for (int i = 0; i < 5; i++) {
if (e[i].salary > 20000)
printf("%s\n", e[i].name);
}
}

Q: C program to take a string input and perform the following using


built-in functions:

1. Find the length


2. Convert to uppercase
3. Concatenate another string
4. Copy to another variable

c
CopyEdit
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void stringOperations() {
char str1[100], str2[100], str3[100];
printf("Enter string: ");
gets(str1);

printf("Length = %lu\n", strlen(str1));

for (int i = 0; str1[i]; i++)


str1[i] = toupper(str1[i]);
printf("Uppercase: %s\n", str1);

printf("Enter string to concatenate: ");


gets(str2);
strcat(str1, str2);
printf("Concatenated: %s\n", str1);

strcpy(str3, str1);
printf("Copied string: %s\n", str3);
}

Q: WAP to accept two strings, compare them, and display whether equal
or not. If not, display the greater one.

c
CopyEdit
#include <stdio.h>
#include <string.h>
void compareStrings() {
char str1[100], str2[100];
printf("Enter two strings: ");
gets(str1);
gets(str2);
int cmp = strcmp(str1, str2);
if (cmp == 0)
printf("Strings are equal\n");
else if (cmp > 0)
printf("'%s' is greater\n", str1);
else
printf("'%s' is greater\n", str2);
}

Q: Program to define a structure Hockey with player name, country,


matches played, goals scored. Accept and display 5 players.

c
CopyEdit
#include <stdio.h>
struct Hockey {
char name[20];
char country[20];
int matches;
int goals;
};

void hockeyPlayers() {
struct Hockey p[5];
for (int i = 0; i < 5; i++) {
printf("Enter player name, country, matches, goals:\n");
scanf("%s %s %d %d", p[i].name, p[i].country, &p[i].matches,
&p[i].goals);
}
printf("Player Details:\n");
for (int i = 0; i < 5; i++) {
printf("%s from %s played %d matches and scored %d goals\n",
p[i].name, p[i].country, p[i].matches, p[i].goals);
}
}

Module 5: FUNCTIONS AND PARAMETERS


Q: What are storage classes in C? Explain different types.
A:
Storage classes define variable scope, lifetime, and linkage.
Types:

• auto – default local variable


• register – stored in CPU register
• static – retains value between calls
• extern – global variable from another file

Q: Write a recursive function to print Fibonacci series up to N terms

c
CopyEdit
#include <stdio.h>
int fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
void printFibonacci() {
int n;
printf("Enter N: ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
printf("%d ", fib(i));
}

Q: Program to find the sum of two numbers using a function

c
CopyEdit
#include <stdio.h>
void sum(int a, int b) {
printf("Sum = %d\n", a + b);
}
void callSum() {
int x, y;
printf("Enter 2 numbers: ");
scanf("%d %d", &x, &y);
sum(x, y);
}

Q: Program to swap two numbers using call by value and call by


reference

c
CopyEdit
#include <stdio.h>
// Call by value
void swapValue(int a, int b) {
int temp = a;
a = b;
b = temp;
printf("Inside swapValue: a=%d b=%d\n", a, b);
}

// Call by reference
void swapRef(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

void testSwap() {
int x = 5, y = 10;
printf("Original: x=%d y=%d\n", x, y);
swapValue(x, y);
printf("After swapValue: x=%d y=%d\n", x, y);
swapRef(&x, &y);
printf("After swapRef: x=%d y=%d\n", x, y);
}

Q: WAP to calculate Factorial using recursion

c
CopyEdit
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
void calcFactorial() {
int n;
printf("Enter number: ");
scanf("%d", &n);
printf("Factorial = %d\n", factorial(n));
}

Q: WAP to check if a number is prime using function


c
CopyEdit
#include <stdio.h>
int isPrime(int n) {
if (n < 2) return 0;
for (int i = 2; i <= n / 2; i++)
if (n % i == 0) return 0;
return 1;
}
void checkPrime() {
int n;
printf("Enter number: ");
scanf("%d", &n);
if (isPrime(n))
printf("Prime\n");
else
printf("Not Prime\n");
}

Q: Difference between call by value and call by reference

A:

• Call by value: Copy is passed, original not changed.


• Call by reference: Address is passed, original can be modified.

Q: Benefits of using functions in C. Explain predefined and user-


defined functions with examples.
A:

• Benefits: Code reuse, modularity, easier debugging.


• Predefined: printf(), scanf()
• User-defined: Custom written like int sum(int a, int b) { return
a + b; }

Module 6: POINTER
Q: Write a C program to demonstrate pointer arithmetic

c
CopyEdit
#include <stdio.h>
void pointerArithmetic() {
int a[] = {10, 20, 30};
int *p = a;
printf("Value: %d\n", *p);
p++;
printf("Next Value: %d\n", *p);
printf("Address: %p\n", p);
}

Q: What is a pointer in C? How is it useful? Give declaration with


example.
A:
Pointer stores address of another variable.
Syntax: int *p;
Useful for dynamic memory, arrays, functions, structures.

Example:

c
CopyEdit
void pointerExample() {
int x = 5;
int *p = &x;
printf("Value: %d, Address: %p\n", *p, p);
}

Q: Explain dynamic memory allocation functions (malloc, calloc, free)


with examples.

A:

• malloc(size) – allocates uninitialized memory


• calloc(n, size) – allocates and initializes to 0
• free(ptr) – releases memory

c
CopyEdit
#include <stdio.h>
#include <stdlib.h>

void demoDynamicAllocation() {
int *p, *q;
p = (int *)malloc(3 * sizeof(int)); // malloc
q = (int *)calloc(3, sizeof(int)); // calloc

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


p[i] = i + 1;
q[i] = (i + 1) * 10;
}

printf("malloc: ");
for (int i = 0; i < 3; i++) printf("%d ", p[i]);
printf("\ncalloc: ");
for (int i = 0; i < 3; i++) printf("%d ", q[i]);

free(p);
free(q);
}

Q: Explain pointer / pointer variable in detail.


A:
Pointer variable stores memory address.
Declared using *.
Used for dynamic memory, parameter passing, arrays, etc.

c
CopyEdit
void pointerVar() {
int x = 100;
int *p = &x;
printf("x = %d, *p = %d\n", x, *p);
}

Q: Output of the given program with pointer

c
CopyEdit
#include <stdio.h>

void pointerOutput() {
int a = 250, *p, **p1;
p = &a;
p1 = &p;

printf("%d\n", a); // 250


printf("%p\n", p); // Address of a
printf("%p\n", p1); // Address of p
printf("%d\n", *p); // 250
printf("%p\n", *p1); // Address of a (same as p)
}

Q: What is an array of pointers? Give an example where it's useful.

A:
Array of pointers stores multiple addresses (e.g., strings).
Useful in handling arrays of strings.

c
CopyEdit
void arrayOfPointers() {
char *names[] = {"Alice", "Bob", "Charlie"};
for (int i = 0; i < 3; i++)
printf("%s\n", names[i]);
}

You might also like