0% found this document useful (0 votes)
55 views

answers_c

The document outlines a programming course in C for KTU 2024, covering various topics such as identifiers, arrays, strings, structures, functions, file handling, and algorithms. It includes questions and answers related to C programming concepts, code snippets, and explanations for tasks like checking Armstrong numbers, counting binary 1s, and finding GCD using recursion. The document serves as a comprehensive guide for students to understand and practice C programming.

Uploaded by

disalfinksunny
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)
55 views

answers_c

The document outlines a programming course in C for KTU 2024, covering various topics such as identifiers, arrays, strings, structures, functions, file handling, and algorithms. It includes questions and answers related to C programming concepts, code snippets, and explanations for tasks like checking Armstrong numbers, counting binary 1s, and finding GCD using recursion. The document serves as a comprehensive guide for students to understand and practice C programming.

Uploaded by

disalfinksunny
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/ 16

Programming in C (GXEST204) – KTU 2024 Scheme

PART A (Each question carries 3 marks)

1. Identify the valid and invalid identifiers in C, given below. Justify your answer.

• i) mark1 – Valid (Starts with a letter and contains letters/numbers)


• ii) _123 – Valid (Starts with underscore, allowed in C)
• iii) $price – Invalid ($ is not allowed in C identifiers)
• iv) rank list – Invalid (Contains space)
• v) Xyz – Valid
• vi) name_3 – Valid

2. What will be the output of the following C program? Justify your answer.

void main() {
int i = 1234, j = 0;
while (i > 0) {
j = j * 10 + i % 10;
i = i / 10;
}
printf("%d %d", i, j);
}

Output: 0 4321

Justification:

• This code reverses the digits of the integer i.


• j accumulates the reversed digits.
• When i becomes 0, the loop exits.

3. What are the different ways to declare and initialize a single-dimensional array?

Answer:

• int arr[5]; // Declaration only


• int arr[5] = {1, 2, 3, 4, 5}; // Declaration + Initialization
• int arr[] = {10, 20, 30}; // Size inferred from values
• int arr[5] = {0}; // All elements initialized to 0
4. Write a C program to find the length of a given string without using any string
functions.

#include <stdio.h>
int main() {
char str[100];
int i = 0;
printf("Enter a string: ");
scanf("%s", str);
while (str[i] != '\0') {
i++;
}
printf("Length of the string = %d\n", i);
return 0;
}

5. Compare the difference between structure and union data types in C.

Feature Structure Union


Allocates memory for largest member
Memory Allocates memory for all members
only
All members can be accessed
Access One member at a time
simultaneously
Use Useful when storing different related
Useful when sharing memory
case values

6. What will be the output of the following C function, if the function was called 5 times
in the main program? Justify your answer.

void fun() {
static int count = 0;
count++;
printf("Count: %d\n", count);
}

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

Justification:

• The static variable retains its value between function calls.


7. Write function prototypes of array of pointers, pointer to function, and pointer to
structure.

Answer:

• Array of pointers: int *arr[10];


• Pointer to function: int (*fptr)(int, int);
• Pointer to structure:
• struct Student {
• int id;
• char name[20];
• };
• struct Student *ptr;

Q8: What happens in the following scenarios when using the statement:

fp = fopen("data.txt", "w");

• If data.txt does not exist on the disk:


It creates a new file named data.txt for writing.
• If data.txt already exists on the disk:
It truncates (empties) the file to zero length and opens it for writing.

Explanation:
The "w" mode in fopen() is used for writing. If the file exists, it is cleared. If not, a new file
is created.

• If data.txt does not exist:


→ fopen() with "w" mode creates a new file for writing.
→ Cursor is placed at the beginning of the file.
• If data.txt exists:
→ The existing file is opened and cleared (truncated).
→ All old contents are deleted, and cursor is at the beginning.

Concept:

• "w"stands for write-only.


• You can only write (not read) to the file.
• Used when you want a fresh file each time.
PART B

Module 1

Q9a)What will be the output of the following program? Justify your answer.

#include<stdio.h>
void main() {
int a=5, b=8, c=9, d;
d = a++ + --b + c++;
printf("%d %d %d %d\n", a, b, c, d);
}

Answer:

• a = 6 (post-increment)
• b = 7 (pre-decrement)
• c = 10 (post-increment)
• d = 5 + 7 + 9 = 21

Output: 6 7 10 21

Explaination:

int a = 5, b = 8, c = 9, d;

d = a++ + --b + c++;

Step-by-step:

a++ is post-increment: use 5, then a = 6

--b is pre-decrement: b = 7, then use 7

c++ is post-increment: use 9, then c = 10

So,d = 5 + 7 + 9 = 21

a = 6, b = 7, c = 10

Output: 6 7 10 21

Concepts:

Post-increment: use first, then increment.

Pre-decrement: decrement first, then use


Q9b)
Write a C program to check whether a number is an Armstrong number.

Definition: A number is Armstrong if:


sum of (each digit)^number of digits = number itself
Example: 153 = 1³ + 5³ + 3³

Logic:

1. Count digits (n)


2. Take each digit, raise it to power n, and add to sum
3. Compare sum with original

Code explanation: Uses pow() to calculate each digit raised to power n.

Code:

#include <stdio.h>
#include <math.h>

int main() {
int num, original, rem, sum = 0, n = 0;
printf("Enter a number: ");
scanf("%d", &num);
original = num;

int temp = num;


while (temp != 0) {
temp /= 10;
n++;
}

temp = num;
while (temp != 0) {
rem = temp % 10;
sum += pow(rem, n);
temp /= 10;
}

if (sum == original)
printf("Armstrong number\n");
else
printf("Not an Armstrong number\n");
return 0;
}

Q10a)
C program to count number of 1s in the binary representation using bitwise operators:

Logic:

• Binary form of number has 0s and 1s.


• Use num & 1 to check last bit
• Right shift num (i.e., num = num >> 1) to move to next bit
Concept:
Bitwise AND with 1 gives 1 if LSB is 1. Repeat until number is 0.

Example:
5 in binary = 101 → 2 ones

Code:
#include <stdio.h>

int main() {
int num, count = 0;
printf("Enter a number: ");
scanf("%d", &num);

while (num != 0) {
if (num & 1)
count++;
num = num >> 1;
}

printf("Number of 1s: %d\n", count);


return 0;
}

Q10b)
Check if a number is prime:

Logic:

• A prime number has only two divisors: 1 and itself


• Check divisibility from 2 to n/2
• If any divisor exists, it’s not prime

Concept:
Efficient check up to sqrt(n) is enough for large numbers.

Code:

#include <stdio.h>

int main() {
int num, i, flag = 1;
printf("Enter a number: ");
scanf("%d", &num);

if (num <= 1)
flag = 0;
else {
for (i = 2; i <= num/2; i++) {
if (num % i == 0) {
flag = 0;
break;
}
}
}

if (flag)
printf("Prime\n");
else
printf("Not Prime\n");
return 0;
}

Module 2

Q11a)
Sum of odd numbers in an array:

Logic:

• Input array
• Traverse each element: if (element % 2 != 0)
• Add it to sum

Concept:
Odd numbers leave remainder 1 when divided by 2.

Code:

#include <stdio.h>

int main() {
int arr[100], n, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);

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


scanf("%d", &arr[i]);
if (arr[i] % 2 != 0)
sum += arr[i];
}

printf("Sum of odd numbers: %d\n", sum);


return 0;
}

Q11b)
Arrange array in descending order using bubble sort:

Logic:

• Compare adjacent elements


• Swap if left < right
• Repeat until array is sorted

Concept:
Bubble sort has n-1 passes. In each pass, largest/smallest bubbles up to correct position.

Example:
Array: [5, 2, 9]
Pass 1: [5, 9, 2] → [9, 5, 2]

Code:

#include <stdio.h>

int main() {
int arr[100], n, temp;
printf("Enter number of elements: ");
scanf("%d", &n);

for (int i = 0; i < n; i++)


scanf("%d", &arr[i]);

for (int i = 0; i < n-1; i++) {


for (int 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;
}
}
}

printf("Sorted array in descending order: ");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

Q12a)
Count number of words and lines in a string:

Logic:

• Count \n → line count


• Count ' ' and \n → word count

Concepts:

• Words are separated by spaces


• Lines are separated by newline (\n)

Note: Uses getchar() to read multi-line input until a stop character like #
Code:
#include <stdio.h>

int main() {
char str[1000];
int lines = 0, words = 0, i = 0;

printf("Enter text (end with #):\n");


while ((str[i] = getchar()) != '#') i++;
str[i] = '\0';

for (i = 0; str[i] != '\0'; i++) {


if (str[i] == '\n')
lines++;
if (str[i] == ' ' || str[i] == '\n')
words++;
}
printf("Lines = %d\nWords = %d\n", lines + 1, words + 1);
return 0;
}

Q12b)
Check if string is palindrome (without string functions):

Logic:

• Find length of string manually


• Compare first and last characters
• Continue inward until middle

Concept:
A palindrome reads the same forward and backward.

Code:

#include <stdio.h>

int main() {
char str[100];
int i, j, flag = 1;

printf("Enter a string: ");


scanf("%s", str);

for (j = 0; str[j] != '\0'; j++);


j--;

for (i = 0; i < j; i++, j--) {


if (str[i] != str[j]) {
flag = 0;
break;
}
}

if (flag)
printf("Palindrome\n");
else
printf("Not a Palindrome\n");
return 0;
}

Module 3

Q13 a)Evaluate the series: 1 + x + x² + ... + xⁿ

Logic:

• Initialize sum = 1
• Loop from 1 to n
• Add x^i using pow(x, i)

Concept:
This is a geometric series.
Manual calculation also possible if needed.

Example:
x = 2, n = 3 → 1 + 2 + 4 + 8 = 15

Code:

#include <stdio.h>
#include <math.h>

int series(int x, int n) {


int sum = 1;
for (int i = 1; i <= n; i++) {
sum += pow(x, i);
}
return sum;
}

int main() {
int x, n;
printf("Enter x and n: ");
scanf("%d%d", &x, &n);
printf("Sum = %d\n", series(x, n));
return 0;
}

Q13 (b): Recursive Function for GCD

Concept Explanation:

• A recursive function calls itself until a base condition is met.


• The GCD (Greatest Common Divisor) can be calculated using Euclid’s algorithm:
o If b == 0, return a.
o Otherwise, GCD(a, b) = GCD(b, a % b).

Code with Explanation:

#include <stdio.h>

// Recursive function to find GCD


int gcd(int a, int b) {
if (b == 0) // Base case: if b becomes 0, a is the GCD
return a;
else
return gcd(b, a % b); // Recursive call with new values
}

int main() {
int a = 36, b = 60;
printf("GCD of %d and %d is %d", a, b, gcd(a, b));
return 0;
}

Q14 (a): Structure for Student Records

Concept Explanation:

• struct allows grouping of related data types (roll number, name, marks, etc.).
• We use an array of structures to store 10 student records.
• We calculate percentage = (total_mark / 500.0) * 100
• Then we assign a grade using if-else conditions.

Code with Explanation:

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

// Structure definition
struct Student {
int roll_no;
char name[50];
int total_mark;
float percentage;
char grade;
};

// Function to return grade based on percentage


char calculateGrade(float percentage) {
if (percentage >= 90) return 'O';
else if (percentage >= 80) return 'A';
else if (percentage >= 70) return 'B';
else if (percentage >= 60) return 'C';
else if (percentage >= 50) return 'D';
else if (percentage >= 40) return 'E';
else return 'F';
}

int main() {
struct Student s[10]; // Array to store 10 student records
for (int i = 0; i < 10; i++) {
printf("Enter Roll No, Name, and Total Marks (out of 500) for
Student %d: ", i + 1);
scanf("%d %s %d", &s[i].roll_no, s[i].name, &s[i].total_mark);
s[i].percentage = (s[i].total_mark / 500.0) * 100; // Convert to
percentage
s[i].grade = calculateGrade(s[i].percentage); // Assign grade
}

// Display all student records


printf("\nStudent Records:\n");
for (int i = 0; i < 10; i++) {
printf("%d %s %.2f %c\n", s[i].roll_no, s[i].name, s[i].percentage,
s[i].grade);
}

return 0;
}

Q14 (b): Display Students with Grade 'O'


// Add to the end of main() in the above program
printf("\nStudents with grade 'O':\n");
for (int i = 0; i < 10; i++) {
if (s[i].grade == 'O') {
printf("%d %s %.2f %c\n", s[i].roll_no, s[i].name, s[i].percentage,
s[i].grade);
}
}

Explanation:

• The loop checks each student.


• If their grade is 'O', their details are printed.

Q15 (a): malloc vs calloc

Feature malloc() calloc()


Initialization No Initializes to 0
Syntax malloc(size) calloc(n, size)
Use case Fast allocation Safe zero-initialized memory

Example:

int *a = (int *) malloc(5 * sizeof(int)); // Not initialized


int *b = (int *) calloc(5, sizeof(int)); // All elements = 0
Q15 (b): Concatenate Strings Using Pointers
#include <stdio.h>

// Function to concatenate strings using pointers


void concatenate(char *s1, char *s2) {
while (*s1) s1++; // Move to end of s1
while (*s2) {
*s1 = *s2; // Copy characters one by one
s1++;
s2++;
}
*s1 = '\0'; // End the concatenated string
}

int main() {
char str1[100] = "Hello ";
char str2[] = "World!";
concatenate(str1, str2);
printf("Concatenated String: %s\n", str1);
return 0;
}

Explanation:

• The function finds the end of s1, then copies characters from s2.
• *s1 = '\0' marks the end of the new string.

Q16 (a): Create and Display Text File


#include <stdio.h>

int main() {
FILE *fp;
char filename[] = "output.txt";
char ch;
int size = 0;

fp = fopen(filename, "w");
if (fp == NULL) {
printf("File creation failed.\n");
return 1;
}

printf("Enter text (end with #):\n");


while ((ch = getchar()) != '#') {
fputc(ch, fp); // Write character to file
size++;
}
fclose(fp); // Close after writing

printf("File size = %d bytes\n", size);

fp = fopen(filename, "r");
printf("Contents of file:\n");
while ((ch = fgetc(fp)) != EOF) {
putchar(ch); // Display file content
}
fclose(fp);

return 0;
}

Explanation:

• fputc writes char by char.


• Size is tracked manually.
• File content is read using fgetc.

Q16 (b): Stock File with Reorder Check


#include <stdio.h>

struct Item {
int item_code;
char item_name[30];
int quantity;
int reorder_level;
};

int main() {
struct Item items[100];
int n;

printf("Enter number of items: ");


scanf("%d", &n);

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


printf("Enter item_code, item_name, quantity, reorder_level:\n");
scanf("%d %s %d %d", &items[i].item_code, items[i].item_name,
&items[i].quantity, &items[i].reorder_level);
}

printf("\nItems needing reorder:\n");


for (int i = 0; i < n; i++) {
if (items[i].quantity < items[i].reorder_level) {
printf("%d %s %d %d\n", items[i].item_code, items[i].item_name,
items[i].quantity, items[i].reorder_level);
}
}

return 0;
}

Explanation:

• Structure Item stores item data.


• Loop reads all values.
• If quantity < reorder_level, print it (reorder needed).
Question Recap:

A stock file contains:

• item_code
• item_name
• quantity
• reorder_level

Task:

1. Create a file of N items.


2. List items where quantity < reorder_level (i.e., needs restocking).

Explanation of Each Part:

1. Structure Definition:

struct Item {
int item_code;
char item_name[30];
int quantity;
int reorder_level;
};

• Used to group related information for each item.


• item_code is a unique ID.
• item_name stores the item name as a string.
• quantity stores how much of the item is available.
• reorder_level is the minimum quantity that must be maintained.

2. Reading the Number of Items:

int n;
printf("Enter number of items: ");
scanf("%d", &n);

• The user is prompted to enter how many items they want to input.
• That number is stored in n.

3. Reading Details for N Items:

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


scanf("%d %s %d %d",
&items[i].item_code,
items[i].item_name,
&items[i].quantity,
&items[i].reorder_level);
}

• For each item, we use scanf to take inputs.


• %d for integers (item_code, quantity, reorder_level), %s for the string
item_name.

4. Checking for Reorder Condition:

if (items[i].quantity < items[i].reorder_level)

• This condition checks whether the quantity has fallen below the reorder level.
• If true, it means that the item should be reordered.

5. Printing Items That Need Reordering:

printf("Item Code: %d, Name: %s, Quantity: %d, Reorder Level: %d\n", ...)

• If the condition is true, all item details are printed in a clear format.

Sample Input & Output:

Input:

Enter number of items: 2


Enter item_code, item_name, quantity, reorder_level:
101 pen 5 10
102 book 15 10

Output:

Items needing reorder:


Item Code: 101, Name: pen, Quantity: 5, Reorder Level: 10

Explanation:

Only "pen" has quantity < reorder_level (5 < 10), so it needs to be reordered

You might also like