[go: up one dir, main page]

0% found this document useful (0 votes)
40 views12 pages

Acpp Cat 2 Set 1 Answers

The document covers various programming concepts including command-line arguments in C, error handling functions for files, string manipulation in Python, and conditional statements. It includes code examples for managing student records in C, calculating multiplication in Python, and billing based on customer type. Additionally, it discusses the differences between compilers and interpreters, along with providing sample programs for practical understanding.

Uploaded by

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

Acpp Cat 2 Set 1 Answers

The document covers various programming concepts including command-line arguments in C, error handling functions for files, string manipulation in Python, and conditional statements. It includes code examples for managing student records in C, calculating multiplication in Python, and billing based on customer type. Additionally, it discusses the differences between compilers and interpreters, along with providing sample programs for practical understanding.

Uploaded by

ranganeerajr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

What will be the values for argc and argv[] when the input “ run with my
values” is passed as command line arguments?
When "run with my values" is passed as command-line arguments, argc will
be 2 and argv[] will contain the strings "run", and "with my values".
2. Write about different error handling functions on files.

Function Purpose
fopen() Opens a file, returns NULL on error
perror() Prints error message based on errno
strerror() Returns string describing errno
feof() Checks for end-of-file
ferror() Checks for file operation errors
clearerr() Clears file error and EOF flags

3. Describe the prototype of the function fopen().

FILE *fopen(const char *filename, const char *mode);

4. Write a C program to get name and marks of n number of students from


user and store them in a file.

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

int main() {
FILE *fp;
char name[50];
int marks, n;

// Open file in write mode


fp = fopen("students.txt", "w");
if (fp == NULL) {
perror("Error opening file");
return 1;
}

// Ask for number of students


printf("Enter the number of students: ");
scanf("%d", &n);

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


printf("\nStudent %d\n", i + 1);
printf("Enter name: ");
scanf(" %[^\n]", name); // to allow spaces in name

printf("Enter marks: ");


scanf("%d", &marks);

// Write to file
fprintf(fp, "Name: %s\tMarks: %d\n", name, marks);
}

fclose(fp);
printf("\nStudent data written to students.txt successfully.\n");

return 0;
}

Output:

Enter the number of students: 2

Student 1
Enter name: Alice Johnson
Enter marks: 85

Student 2
Enter name: Bob Smith
Enter marks: 90

Student data written to students.txt successfully.

5. Outline the logic to swap the contents of two identifiers without using third
variable.

To swap the contents of two identifiers without using a third variable, we can
employ various methods like addition and subtraction, multiplication and
division, or the XOR operation.

// Let a = 5 and b = 10

// Step 1: a = a + b; (a becomes 15)


a = a + b;

// Step 2: b = a - b; (b becomes 5)
b = a - b;
// Step 3: a = a - b; (a becomes 10)
a = a - b;

// a now holds 10, and b now holds 5

6. Analyze different ways to manipulate strings in python.

Concatenation
Repetition
Indexing
Slicing
Splitting
Joining

7. Point Out the rules to be followed for naming any identifier.

 Can contain letters, digits, and underscores


 Cannot start with a digit
 No special characters allowed
 Cannot use keywords
 Case-sensitive

8. State about logical operators available in python language with example.

In Python, Logical operators are used on conditional statements (either True or


False). They perform Logical AND, Logical OR, and Logical NOT operations.

Operator Description Syntax Example

Returns True if both


and x and y x>7 and x>10
the operands are true

Returns True if either


or x or y x<7 or x>15
of the operands is true

Returns True if the not(x>7 and


not not x
operand is false x> 10)

9. Give the various data types in Python.


Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Boolean Type: bool

PART-B

Create a C Program to manage student records stored in a binary file.


Each student record contains roll no, name and mark. The program
should add a new student record, display all student records and search
for a student by roll number using random file access.

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

#define FILENAME "students.dat"

struct Student {
int roll_no;
char name[50];
float marks;
};

// Function to add a new student


void addStudent() {
FILE *fp = fopen(FILENAME, "ab"); // append in binary mode
if (fp == NULL) {
perror("Error opening file");
return;
}

struct Student s;
printf("Enter Roll Number: ");
scanf("%d", &s.roll_no);
printf("Enter Name: ");
scanf(" %[^\n]", s.name); // read with spaces
printf("Enter Marks: ");
scanf("%f", &s.marks);

fwrite(&s, sizeof(struct Student), 1, fp);


fclose(fp);
printf("Student added successfully!\n");
}
// Function to display all students
void displayStudents() {
FILE *fp = fopen(FILENAME, "rb");
if (fp == NULL) {
perror("Error opening file");
return;
}

struct Student s;
printf("\n--- All Student Records ---\n");
while (fread(&s, sizeof(struct Student), 1, fp)) {
printf("Roll No: %d | Name: %s | Marks: %.2f\n", s.roll_no, s.name,
s.marks);
}

fclose(fp);
}

// Function to search a student by roll number


void searchByRollNo() {
int target_roll;
int found = 0;
printf("Enter roll number to search: ");
scanf("%d", &target_roll);

FILE *fp = fopen(FILENAME, "rb");


if (fp == NULL) {
perror("Error opening file");
return;
}

struct Students;

// Read each record and compare


while (fread(&s, sizeof(struct Student), 1, fp)) {
if (s.roll_no == target_roll) {
printf("Record Found!\nRoll No: %d\nName: %s\nMarks: %.2f\n",
s.roll_no, s.name, s.marks);
found = 1;
break;
}
}

if (!found) {
printf("Student with Roll No %d not found.\n", target_roll);
}
fclose(fp);
}
// Menu-driven main function
int main() {
int choice;

do {
printf("\n--- Student Record ---\n");
printf("1. Add Student\n");
printf("2. Display All Students\n");
printf("3. Search by Roll Number\n");
printf("0. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);

switch(choice) {
case 1: addStudent(); break;
case 2: displayStudents(); break;
case 3: searchByRollNo(); break;
case 0: printf("Exiting...\n"); break;
default: printf("Invalid choice! Try again.\n");
}
} while (choice != 0);

return 0;
}
Student Record
1. Add Student
2. Display All Students
3. Search by Roll Number
0. Exit
Enter choice: 1
Enter Roll Number: 101
Enter Name: Alice Brown
Enter Marks: 89.5
Student added successfully!

Write a Python program to accepts a string and calculates the number of


digits and letters.

# Accept input from user


text = input("Enter a string: ")
# Initialize counters
letters = 0
digits = 0

# Loop through each character


for char in text:
if char.isalpha():
letters += 1
elif char.isdigit():
digits += 1

# Display result
print(f"Letters: {letters}")
print(f"Digits: {digits}")

Output:

Enter a string: Hello123


Letters: 5
Digits: 3

Write a program to check if the word ‘open’ is present in the “This is open
source software”.

text = "This is open source software"

# Check if the word 'open' is in the string


if 'open' in text:
print("The word 'open' is present in the string.")
else:
print("The word 'open' is not present in the string.")

Sketch the structures of interpreter and complier. Detail the differences


between them. Write a python program to accept two numbers multiply
them and print the result.
Feature Compiler Interpreter
Translation Method Translates entire program Translates line by line
Slower (interpreted at
Execution Speed Faster (after compilation)
runtime)
Error Handling Shows all errors after compiling Stops at the first error
Generates a separate machine Does not produce separate
Output
code file
Language Examples C, C++, Java (compiled) Python, JavaScript, PHP
Memory Usage More (stores compiled code) Less
Modification Less convenient (recompile Easy to test changes
Convenience needed) immediately
Python program to accept two numbers multiply them and print the result.

# Accept two numbers from the user


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Multiply the numbers


result = num1 * num2

# Display the result


print(f"The result of multiplication is: {result}")

Output:

Enter first number: 5


Enter second number: 3
The result of multiplication is: 15.0

List the three of conditional statements and explain them. Write a python program to
accept two numbers find the greatest and print the result.

List the three of conditional statements

Types of Conditional statements in Python:


 Python If Statement
 Python If Else Statement
 Python Nested If Statement
 Python Elif

(Note: have to explain individually with syntax and sample program)

Write a python program to accept two numbers find the greatest and print the
result.
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Output:
b is not greater than a

Write a c Program that uses conditional compilation directives. The


program should take customer type as input(R, C or I), take number of
units consumed and calculate and display the bill.
Billing Rules:

Residential (R)
 First 100 units:Rs 1.5/unit
 Next 200 units:Rs2.5/unit
 Above 300 units:Rs3.5/unit
Commercial(c)
 Flat Rs5/unit for all consumption
Industrial(I)
 First 500 units:Rs 4/unit
 Above 500 units:Rs 6/unit

PROGRAM:

#include <stdio.h>

// Define customer types


#define RESIDENTIAL
// #define COMMERCIAL
// #define INDUSTRIAL

int main() {
char type;
int units;
float bill = 0;

// Take customer type and units as input


printf("Enter Customer Type (R = Residential, C = Commercial, I =
Industrial): ");
scanf(" %c", &type);
printf("Enter number of units consumed: ");
scanf("%d", &units);

// Convert to uppercase for simplicity


if (type >= 'a' && type <= 'z') {
type = type - 32;
}

// Calculate bill based on customer type


#ifdef RESIDENTIAL
if (type == 'R') {
if (units <= 100)
bill = units * 1.5;
else if (units <= 300)
bill = 100 * 1.5 + (units - 100) * 2.5;
else
bill = 100 * 1.5 + 200 * 2.5 + (units - 300) * 3.5;
}
#endif

#ifdef COMMERCIAL
if (type == 'C') {
bill = units * 5.0;
}
#endif

#ifdef INDUSTRIAL
if (type == 'I') {
if (units <= 500)
bill = units * 4.0;
else
bill = 500 * 4.0 + (units - 500) * 6.0;
}
#endif
// Display the bill
if (bill > 0)
printf("Total bill for %c customer: Rs %.2f\n", type, bill);
else
printf("Invalid customer type or data.\n");

return 0;
}

Output:

Enter Customer Type (R = Residential, C = Commercial, I = Industrial): R


Enter number of units consumed: 350
Total bill for R customer: Rs 775.00

You might also like