0% found this document useful (0 votes)
55 views39 pages

C Programming Module 1 Answers

The document is a question bank for a C programming course, detailing fundamental concepts such as the structure of a C program, variables, data types, and operators. It includes explanations of key topics, rules for naming variables and identifiers, and examples of code. Additionally, it outlines the steps for compiling and executing a C program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views39 pages

C Programming Module 1 Answers

The document is a question bank for a C programming course, detailing fundamental concepts such as the structure of a C program, variables, data types, and operators. It includes explanations of key topics, rules for naming variables and identifiers, and examples of code. Additionally, it outlines the steps for compiling and executing a C program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Problem Solving Using C

(25BECPHY104)
Module-1: Question Bank -
Complete Answers
Academic Year: 2025-26, Semester I
Department: Computer Science & Engineering, SNPSU

Question 1: Explain the basic


structure of a C program
A C program has a well-defined structure consisting of several key sections:

1. Documentation Section: Comments explaining the program's purpose


and author details
2. Preprocessor Directives: Lines like #include<stdio.h>,
#include<conio.h> that link library functions
3. Global Declaration Section: Variables and constants accessible
throughout the program
4. Function Definitions: User-defined functions
5. Main Function: The entry point where program execution starts
o Variable declarations
o Executable statements
o Return statement (return 0;)
Example Structure:
#include<stdio.h> // Preprocessor directive
int x = 10; // Global variable
int main() // Main function
{
int y = 20; // Local variable
printf("Hello World"); // Output statement
return 0; // Return statement
}
Question 2: What is a variable?
Explain rules for defining variable
names
Definition: A variable is a named memory location used to store data values
that can change during program execution.

Rules for Naming Variables:

1. Must start with a letter (A-Z, a-z) or underscore (_)


2. Cannot start with a digit (0-9)
3. Can contain letters, digits, and underscores only (no spaces or special
characters)
4. Cannot be a C keyword (int, while, for, if, etc.)
5. Names are case-sensitive (age and Age are different)
6. Should be meaningful and reflect the data being stored
Valid Examples:

 int total_marks;
 float student_age;
 char _name[30];
 int marks1, marks2;
Invalid Examples:

 int 1marks; (starts with digit)


 int student age; (contains space)
 int for; (C keyword)

Question 3: List different


characteristics of C programming
1. Procedural Language: Follows a step-by-step approach
2. Structured Programming: Supports functions, blocks, and modularity
3. Mid-level Language: Combines high-level features with low-level
operations (pointers, bit operations)
4. Efficient and Fast: Close to hardware, produces compact and fast code
5. Portable: Code written on one platform can run on another with minimal
changes
6. Simple Syntax: Easy to learn and understand
7. Rich Set of Operators: Over 45 operators for various operations
8. Extensible: New functions and features can be easily added
9. Dynamic Memory Allocation: Can allocate and deallocate memory at
runtime
10. Simple I/O: Easy input/output operations

Question 4: What are identifiers?


State the rules for naming them
Definition: Identifiers are user-defined names given to identify program
elements such as variables, functions, arrays, structures, and labels.

Rules for Naming Identifiers:

1. First character must be a letter (A-Z, a-z) or underscore (_)


2. Subsequent characters can be letters, digits (0-9), or underscores
3. No spaces allowed within identifier names
4. Special characters (!, @, #, $, %, etc.) are not permitted
5. Case-sensitive (Name and name are different identifiers)
6. Cannot use C reserved keywords
7. Maximum length depends on compiler (typically 31-32 characters)
Valid Identifiers:

 student_name, _flag, MAX_VALUE, a1b2c3


Invalid Identifiers:

 123name (starts with digit)


 student-age (contains hyphen)
 int (reserved keyword)

Question 5: Differentiate between


variables and identifiers
Aspect Variable Identifier
Definition Named memory Any name used to
location storing identify program
changeable data elements
Scope Limited to a block or Can refer to any named
function element
Types Only data storage Includes variables,
entities functions, arrays,
structures
Purpose Store and manipulate Distinguish and identify
data program elements
Example int age; Function name:
calculate()

Key Point: Every variable name is an identifier, but not every identifier is a
variable. Function names, array names, and structure names are identifiers but
not variables.

Question 6: Explain the use of


scanf() with an example
Definition: scanf() is a formatted input function used to read data from the
keyboard and store it in memory locations specified by the user.

Syntax:
scanf("format_specifier", &variable1, &variable2, ...);

Important Points:

 The & operator (address-of operator) provides the memory address where
data is stored
 Format specifier must match the data type being read
 Multiple inputs are separated by spaces or newlines
Example Program:
#include<stdio.h>
int main()
{
int age;
float salary;

printf("Enter your age: ");


scanf("%d", &age); // Read integer

printf("Enter your salary: ");


scanf("%f", &salary); // Read float

printf("Age: %d, Salary: %.2f\n", age, salary);


return 0;

Sample Output:
Enter your age: 25
Enter your salary: 50000.50
Age: 25, Salary: 50000.50

Question 7: Write a short note on


data types in C
Definition: Data types define the type, size, and range of values that a variable
can store.

Classification of Data Types:

1. Primitive (Basic) Data Types


 int: Integer values (e.g., 10, -5, 0)
o Size: 2 or 4 bytes, Range: -32,768 to 32,767 or -2,147,483,648 to
2,147,483,647
 float: Single precision floating-point (e.g., 3.14, -0.5)
o Size: 4 bytes, Range: ±3.4e-38 to ±3.4e+38
 double: Double precision floating-point (e.g., 3.141592653)
o Size: 8 bytes, Range: ±1.7e-308 to ±1.7e+308
 char: Single character (e.g., 'A', '5', '*')
o Size: 1 byte, Range: -128 to 127

2. Derived Data Types


 Arrays, Pointers, Functions

3. User-Defined Data Types


 Structures (struct), Unions (union), Enumerations (enum)

4. Void Type
 Represents no value or no return type
Storage Sizes (Typical 32-bit System):

Data Type Size Range


char 1 byte -128 to 127
int 4 bytes -2,147,483,648 to
2,147,483,647
float 4 bytes ±3.4e-38 to ±3.4e+38
double 8 bytes ±1.7e-308 to
±1.7e+308

Question 8: What are format


specifiers? List any four with their
meanings
Definition: Format specifiers are special symbols used with printf() and
scanf() functions to specify the type and format of data to be displayed or read.

Format specifier starts with % symbol followed by a character.

Common Format Specifiers:

Format Specifier Data Type Example


%d Integer (signed printf("%d", 25);
decimal)
%f Float printf("%f", 3.14);
%c Single character printf("%c", 'A');
%s String printf("%s",
"Hello");
%lf Double printf("%lf",
3.14159);
%u Unsigned integer printf("%u", 100);
%x Hexadecimal printf("%x", 255);
outputs ff
%o Octal printf("%o", 8);
outputs 10

Example Program:
#include<stdio.h>
int main()
{
int marks = 95;
float percentage = 95.5;
char grade = 'A';

printf("%d\n", marks); // Output: 95


printf("%.2f\n", percentage); // Output: 95.50
printf("%c\n", grade); // Output: A
return 0;

Question 9: What are operators?


Classify the types of operators in C
Definition: Operators are special symbols that perform operations on operands
(variables or constants) and return a result.

Classification of Operators in C:

1. Arithmetic Operators
 + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus)
 Example: a + b, x * y, 10 % 3 gives 1

2. Relational Operators
 == (Equal), != (Not equal), > (Greater than), < (Less than), >= (Greater
than or equal), <= (Less than or equal)
 Example: a > b, x == 10

3. Logical Operators
 && (AND), || (OR), ! (NOT)
 Example: (a > 5) && (b < 10)

4. Assignment Operators
 =, +=, -=, *=, /=, %=
 Example: a = 10;, a += 5; (same as a = a + 5)

5. Increment/Decrement Operators
 ++ (Increment), -- (Decrement)
 Example: a++ (post-increment), ++a (pre-increment)
6. Bitwise Operators
 & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left shift), >> (Right shift)
 Example: a & b, a << 2

7. Conditional (Ternary) Operator


 Syntax: condition ? value_if_true : value_if_false
 Example: age > 18 ? "Adult" : "Minor"

8. Special Operators
 sizeof(): Returns size of data type
 &: Address-of operator
 *: Pointer operator
 .: Member access (structure)
 ->: Pointer to member

Question 10: Explain the concept of


type casting with an example
Definition: Type casting (or type conversion) is the process of converting a
value from one data type to another explicitly by the programmer.

Two Types of Casting:

1. Implicit Casting (Automatic)


Compiler automatically converts compatible data types:
int a = 5;
float b = a; // 5 is automatically converted to 5.0

2. Explicit Casting (Manual)


Programmer explicitly converts using cast operator:
Syntax: (new_type) expression

Example Program:
#include<stdio.h>
int main()
{
int a = 5, b = 2;
float result;
// Without explicit casting - result will be integer division
result = a / b; // result = 2.0
printf("Without casting: %f\n", result);

// With explicit casting


result = (float)a / b; // result = 2.5
printf("With casting: %f\n", result);

// Casting double to int


double d = 3.14159;
int i = (int)d; // i = 3 (decimal part is lost)
printf("Double to int: %d\n", i);

return 0;

Output:
Without casting: 2.000000
With casting: 2.500000
Double to int: 3

Question 11: Describe the steps


involved in compiling and executing
a C program
Steps:

Step 1: Editing (Source Code Creation)


 Write the C program using a text editor (Notepad, VS Code, etc.)
 Save the file with .c extension (e.g., program.c)

Step 2: Preprocessing
 Preprocessor handles directives like #include, #define, #ifdef
 Includes header files and replaces macros
 Produces an intermediate file (not visible to user)

Step 3: Compilation
 Compiler converts preprocessed code into assembly language
 Checks for syntax errors and converts to object code
 Produces .obj or .o file (object file)
 If errors occur, compiler stops and reports errors

Step 4: Linking
 Linker combines object file with library functions
 Resolves external references
 Creates an executable file (.exe on Windows, .out on Linux)

Step 5: Loading
 Operating system loads the executable file into memory
 Allocates memory for code, data, and stack

Step 6: Execution
 CPU executes the program from the main() function
 Program produces output and terminates
Diagram Flow:
Source Code (.c) → Preprocessor → Compiler → Object Code (.obj)

Linker + Libraries

Executable (.exe/.out)

Execution/Output

Question 12: Explain in detail the


different types of data types in C
with examples
Data types in C are broadly classified into:

1. Primitive (Basic) Data Types


a) Integer Type (int)

 Stores whole numbers


 Variants: int, short int, long int, signed int, unsigned int
int age = 25;
long int population = 1000000;
unsigned int count = 500;
b) Floating-Point Type

 Stores decimal numbers


 Variants: float, double, long double
float price = 99.99;
double pi = 3.14159;
long double precision = 3.14159265358979;
c) Character Type (char)

 Stores single characters


 Size: 1 byte
char grade = 'A';
char symbol = '@';

2. Derived Data Types


a) Array

 Collection of elements of same data type


int marks[5] = {90, 85, 88, 92, 87};
char name[20] = "John";
b) Pointer

 Stores memory address of another variable


int x = 10;
int *ptr = &x; // ptr stores address of x
c) Function

 Block of code with specific purpose


int add(int a, int b) {
return a + b;
}

3. User-Defined Data Types


a) Structure (struct)

 Combines different data types under one name


struct Student {
char name[30];
int rollNo;
float cgpa;
};
struct Student s1 = {"Raj", 101, 8.5};
b) Union (union)

 Similar to struct but shares same memory location


union Data {
int i;
float f;
char c;
};
c) Enumeration (enum)

 Set of named integer constants


enum Days {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday};
enum Days today = Monday;

4. Void Type
 Represents "nothing"
 Used for function return type or generic pointers
void display() {
printf("This function returns nothing\n");
}
Size of Data Types (32-bit system):

Data Type Size (bytes) Range


char 1 -128 to 127
short int 2 -32,768 to 32,767
int 4 -2,147,483,648 to
2,147,483,647
long int 4 or 8 Larger range
float 4 ±3.4e-38 to ±3.4e+38
double 8 ±1.7e-308 to
±1.7e+308

Question 13: Write a C program to


read two numbers and display sum,
difference, product, and quotient
Algorithm:

1. Declare variables for two numbers and results


2. Read two numbers from user using scanf()
3. Calculate sum, difference, product, and quotient
4. Display all results using printf()
Program:
#include<stdio.h>

int main()
{
float num1, num2;
float sum, difference, product, quotient;

printf("Enter first number: ");


scanf("%f", &num1);

printf("Enter second number: ");


scanf("%f", &num2);

// Calculate operations
sum = num1 + num2;
difference = num1 - num2;
product = num1 * num2;
quotient = num1 / num2;

// Display results
printf("\nResults:\n");
printf("Sum: %.2f\n", sum);
printf("Difference: %.2f\n", difference);
printf("Product: %.2f\n", product);
printf("Quotient: %.2f\n", quotient);

return 0;

Sample Output:
Enter first number: 20
Enter second number: 4

Results:
Sum: 24.00
Difference: 16.00
Product: 80.00
Quotient: 5.00

Question 14: Discuss the


importance of header files in C
programming
Definition: Header files contain declarations of functions, macros, constants,
and data types that are included in C programs using #include directive.
Importance of Header Files:

1. Code Reusability

o Pre-written functions and declarations can be reused without


rewriting
o Example: printf() defined in <stdio.h>
2. Organization

o Separates interface (declarations) from implementation


o Makes code more modular and maintainable
3. Standard Library Access

o Provides access to standard library functions


o Essential for input/output, string handling, math operations
4. Time-Saving

o Eliminates need to redefine functions and constants


o Reduces development time
5. Consistency

o Ensures consistent function prototypes across programs


o Prevents errors from incorrect function declarations
Common Header Files:

Header File Purpose


<stdio.h> Standard I/O functions (printf, scanf)

<string.h> String manipulation functions

<math.h> Mathematical functions

<stdlib.h> Memory allocation, random numbers

<ctype.h> Character classification

<time.h> Time and date functions

Question 15: Explain the difference


between global and local variables
with examples
Aspect Global Variables Local Variables
Declaration Outside all functions, at Inside a function or
file beginning block
Scope Entire program (all Limited to
functions) function/block
Lifetime Entire program Until function/block
execution ends
Memory Static memory segment Stack memory
Initialization Automatically No automatic
initialized to 0 initialization
Access Accessible by all Only accessible in that
functions function

Example Program:
#include<stdio.h>

int global_var = 100; // Global variable

void function1()
{
printf("Global var in func1: %d\n", global_var);
global_var = 200; // Modify global variable
}

void function2()
{
printf("Global var in func2: %d\n", global_var);
}

int main()
{
int local_var = 50; // Local variable to main

printf("Local var in main: %d\n", local_var);


printf("Global var in main: %d\n", global_var);

function1();
function2();

printf("Local var after functions: %d\n", local_var);


printf("Global var after functions: %d\n", global_var);

return 0;

}
Output:
Local var in main: 50
Global var in main: 100
Global var in func1: 100
Global var in func2: 200
Local var after functions: 50
Global var in main: 200

Question 16: Describe different


types of constants in C with suitable
examples
Definition: Constants are fixed values that cannot be changed during program
execution.

Types of Constants:

1. Integer Constants
 Whole number values without decimal point
 Can be decimal, octal, or hexadecimal
100 // Decimal
0150 // Octal (prefix 0)
0x1F // Hexadecimal (prefix 0x)
-25 // Negative integer

2. Floating-Point Constants
 Real numbers with decimal point or exponent
3.14 // Decimal form
-0.5 // Negative float
1.5e2 // Exponential form (150.0)
2.5E-3 // Scientific notation (0.0025)

3. Character Constants
 Single character enclosed in single quotes
 Can include escape sequences
'A' // Letter
'5' // Digit
'*' // Special character
'\n' // Newline (escape sequence)
'\t' // Tab
'\' // Backslash
4. String Constants
 Sequence of characters enclosed in double quotes
"Hello"
"C Programming"
"Line 1\nLine 2" // With escape sequences

5. Defined Constants (using #define)


#define PI 3.14159
#define MAX_SIZE 100
#define STR "Hello"

6. Declared Constants (using const keyword)


const int AGE = 25;
const float SALARY = 50000.50;
const char GRADE = 'A';

Example Program:
#include<stdio.h>

#define PI 3.14159

int main()
{
// Different types of constants
int count = 10; // Integer constant
float area_factor = 2.5; // Float constant
char initial = 'S'; // Character constant

const float radius = 5.0;

printf("Count: %d\n", count);


printf("Area: %.2f\n", PI * radius * radius);
printf("Grade: %c\n", initial);

return 0;

Question 17: Write and explain a C


program to calculate the area of a
circle
Formula: Area = π × r²
Program:
#include<stdio.h>

int main()
{
float radius, area;
float pi = 3.14159;

printf("Enter the radius of circle: ");


scanf("%f", &radius);

// Calculate area using formula: Area = pi * r * r


area = pi * radius * radius;

printf("Area of circle with radius %.2f = %.2f\n", radius, area);

return 0;

Explanation:

1. Include <stdio.h> for input/output operations


2. Declare variables: radius for user input, area for result, pi for constant
3. Prompt user to enter radius
4. Read radius using scanf()
5. Calculate area using the formula
6. Display result with formatted output
7. Return 0 to indicate successful execution
Sample Output:
Enter the radius of circle: 7
Area of circle with radius 7.00 = 153.94

Enhanced Version (with multiple calculations):


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

#define PI 3.14159

int main()
{
float radius, area, circumference;

printf("Enter the radius of circle: ");


scanf("%f", &radius);

// Calculate area
area = PI * radius * radius;
// Calculate circumference: C = 2 * pi * r
circumference = 2 * PI * radius;

printf("\n--- Circle Calculations ---\n");


printf("Radius: %.2f\n", radius);
printf("Area: %.2f sq. units\n", area);
printf("Circumference: %.2f units\n", circumference);

return 0;

Question 18: Explain the structure


of a C program using an example
and label each part
C Program Structure:

// Documentation Section
/*
Program Name: Basic Structure Demonstration
Author: Student
Purpose: To explain C program structure
*/

// Link/Preprocessor Section
#include<stdio.h>
#include<conio.h>

// Definition Section
#define PI 3.14159
int global_var = 100; // Global variable

// Function Declaration (Function Prototype)


void display();
int calculate(int a, int b);

// Main Function
int main()
{
// Local variable declaration
int a = 10, b = 20;
int sum;

// Executable statements
sum = a + b;
printf("Sum: %d\n", sum);
display(); // Function call

calculate(a, b); // Another function call

// Return statement
return 0;

// Function Definition
void display()
{
printf("This is a user-defined function\n");
}

int calculate(int x, int y)


{
int result = x * y;
printf("Product: %d\n", result);
return result;
}

Explanation of Each Part:

Part Purpose Example


Documentation Comments explaining /* Program description
program */
Link Section Include header files #include<stdio.h>
Definition Define constants and #define PI 3.14, int x =
global variables 10;
Function Declaration Prototype of user int add(int, int);
functions
Main Function Program entry point int main() { ... }
Variable Declaration Local variables int sum;
Statements Executable code printf(), scanf()
Function Definition User function void show() { ... }
implementation
Question 20: Describe the steps
involved in compiling and executing
a C program
Detailed Steps:

Step 1: Source Code Creation


 Write C program using text editor
 File extension: .c (e.g., program.c)
 Contains human-readable C code

Step 2: Preprocessing
Preprocessor processes:

 #include directives (include header files)


 #define macros (replace constants)
 #ifdef directives (conditional compilation)
 Comment removal

Step 3: Compilation
 Compiler reads preprocessed code
 Performs syntax checking
 Converts to assembly language
 Generates object code (.obj or .o file)
 If errors: Compilation fails

Step 4: Linking
 Linker combines object files
 Links with library functions
 Resolves external references
 Creates executable file (.exe or .out)

Step 5: Loading
 Operating system loads executable into RAM
 Allocates memory sections:
o Code segment (program instructions)
o Data segment (global/static variables)
o Stack (local variables)
o Heap (dynamic memory)

Step 6: Execution
 CPU starts executing from main()
 Program runs and produces output
 On completion, returns control to OS
Compilation Commands:

System Command Output


GCC (Linux) gcc program.c -o program (executable)
program
GCC (Windows) gcc program.c -o program.exe
program.exe
TurboC F9 (IDE) or tcc .exe file
program.c

Question 22: Algorithm, flowchart,


and program to find sum of two
numbers
Algorithm:

1. START
2. Declare variables num1, num2, sum
3. INPUT: Read num1 from user
4. INPUT: Read num2 from user
5. PROCESS: Calculate sum = num1 + num2
6. OUTPUT: Display sum
7. STOP
Flowchart Symbols Description:

 Oval (Terminator): START/STOP


 Parallelogram (Input/Output): Input/Output operations
 Rectangle (Process): Calculations
 Arrows: Flow direction
Flowchart:
START
|

INPUT num1
|

INPUT num2
|

PROCESS: sum = num1 + num2
|

OUTPUT: sum
|

STOP

C Program:
#include<stdio.h>

int main()
{
int num1, num2, sum;

printf("Enter first number: ");


scanf("%d", &num1);

printf("Enter second number: ");


scanf("%d", &num2);

sum = num1 + num2;

printf("Sum of %d and %d = %d\n", num1, num2, sum);

return 0;

Question 23: Algorithm, flowchart,


program to find average of three
numbers
Algorithm:

1. START
2. Declare variables: num1, num2, num3, sum, average
3. INPUT: Read three numbers
4. PROCESS: sum = num1 + num2 + num3
5. PROCESS: average = sum / 3
6. OUTPUT: Display average
7. STOP
Flowchart:
START
|

INPUT three numbers
num1, num2, num3
|

PROCESS: sum = num1 + num2 + num3
|

PROCESS: average = sum / 3
|

OUTPUT: Display average
|

STOP

C Program:
#include<stdio.h>

int main()
{
float num1, num2, num3, sum, average;

printf("Enter first number: ");


scanf("%f", &num1);

printf("Enter second number: ");


scanf("%f", &num2);

printf("Enter third number: ");


scanf("%f", &num3);

sum = num1 + num2 + num3;


average = sum / 3;

printf("Average of %.2f, %.2f, %.2f = %.2f\n", num1, num2, num3,


average);

return 0;
}

Question 24: Algorithm, flowchart,


program to check voting eligibility
Eligibility Condition: Age ≥ 18

Algorithm:

1. START
2. Declare variable: age
3. INPUT: Read age from user
4. DECISION: If age >= 18
o YES: OUTPUT "Eligible to vote"
o NO: OUTPUT "Not eligible to vote"
5. STOP
Flowchart:
START
|

INPUT age
|

Is age >= 18?
/
YES NO
||
↓↓
Eligible Not Eligible
||
\/
\/
STOP

C Program:
#include<stdio.h>

int main()
{
int age;

printf("Enter your age: ");


scanf("%d", &age);

if(age >= 18)


{
printf("You are eligible to vote.\n");
}
else
{
printf("You are not eligible to vote.\n");
}

return 0;

Sample Output:
Enter your age: 20
You are eligible to vote.

Question 25: Algorithm, flowchart,


program for area and perimeter of
rectangle
Formulas:

 Area = length × breadth


 Perimeter = 2 × (length + breadth)
Algorithm:

1. START
2. Declare variables: length, breadth, area, perimeter
3. INPUT: Read length
4. INPUT: Read breadth
5. PROCESS: area = length * breadth
6. PROCESS: perimeter = 2 * (length + breadth)
7. OUTPUT: Display area and perimeter
8. STOP
C Program:
#include<stdio.h>

int main()
{
float length, breadth, area, perimeter;

printf("Enter length of rectangle: ");


scanf("%f", &length);
printf("Enter breadth of rectangle: ");
scanf("%f", &breadth);

area = length * breadth;


perimeter = 2 * (length + breadth);

printf("\n--- Rectangle Measurements ---\n");


printf("Area: %.2f sq. units\n", area);
printf("Perimeter: %.2f units\n", perimeter);

return 0;

Question 26: Algorithm, flowchart,


program to swap two numbers using
temp variable
Algorithm:

1. START
2. Declare variables: a, b, temp
3. INPUT: Read a and b
4. PROCESS: temp = a
5. PROCESS: a = b
6. PROCESS: b = temp
7. OUTPUT: Display a and b
8. STOP
Flowchart:
START
|

INPUT a, b
|

temp = a
|

a=b
|

b = temp
|

OUTPUT a, b
|

STOP

C Program:
#include<stdio.h>

int main()
{
int a, b, temp;

printf("Enter value of a: ");


scanf("%d", &a);

printf("Enter value of b: ");


scanf("%d", &b);

printf("\nBefore swap:\n");
printf("a = %d, b = %d\n", a, b);

// Swap using temporary variable


temp = a;
a = b;
b = temp;

printf("\nAfter swap:\n");
printf("a = %d, b = %d\n", a, b);

return 0;

Sample Output:
Enter value of a: 10
Enter value of b: 20

Before swap:
a = 10, b = 20

After swap:
a = 20, b = 10

Question 27: Algorithm, flowchart,


program to calculate simple interest
Formula: SI = (P × R × T) / 100

Where:

 P = Principal amount
 R = Rate of interest per annum
 T = Time period in years
Algorithm:

1. START
2. Declare variables: principal, rate, time, interest
3. INPUT: Read principal
4. INPUT: Read rate
5. INPUT: Read time
6. PROCESS: interest = (principal * rate * time) / 100
7. OUTPUT: Display interest
8. STOP
C Program:
#include<stdio.h>

int main()
{
float principal, rate, time, interest;

printf("Enter principal amount: ");


scanf("%f", &principal);

printf("Enter rate of interest per annum: ");


scanf("%f", &rate);

printf("Enter time period in years: ");


scanf("%f", &time);

// Calculate simple interest


interest = (principal * rate * time) / 100;

printf("\n--- Simple Interest Calculation ---\n");


printf("Principal: %.2f\n", principal);
printf("Rate: %.2f %%\n", rate);
printf("Time: %.2f years\n", time);
printf("Simple Interest: %.2f\n", interest);
printf("Total Amount: %.2f\n", principal + interest);

return 0;

}
Sample Output:
Enter principal amount: 10000
Enter rate of interest per annum: 5
Enter time period in years: 2

--- Simple Interest Calculation ---


Principal: 10000.00
Rate: 5.00 %
Time: 2.00 years
Simple Interest: 1000.00
Total Amount: 11000.00

Question 28: Algorithm, flowchart,


program to print name, roll number,
and college name
Algorithm:

1. START
2. Declare variables for name, roll number, and college name
3. INPUT: Read name, roll number, and college name
4. OUTPUT: Display all three values
5. STOP
C Program (Fixed Values):
#include<stdio.h>

int main()
{
printf("--- Student Information ---\n");
printf("Name: Raj Kumar\n");
printf("Roll Number: 101\n");
printf("College Name: SNPSU\n");

return 0;

C Program (User Input):


#include<stdio.h>

int main()
{
char name[50];
int rollNumber;
char collegeName[50];
printf("Enter your name: ");
fgets(name, sizeof(name), stdin); // Read string with spaces

printf("Enter your roll number: ");


scanf("%d", &rollNumber);
getchar(); // Consume newline character

printf("Enter your college name: ");


fgets(collegeName, sizeof(collegeName), stdin);

printf("\n--- Student Information ---\n");


printf("Name: %s", name);
printf("Roll Number: %d\n", rollNumber);
printf("College Name: %s", collegeName);

return 0;

Sample Output:
Enter your name: Raj Kumar
Enter your roll number: 101
Enter your college name: SNPSU

--- Student Information ---


Name: Raj Kumar
Roll Number: 101
College Name: SNPSU

Question 29: Algorithm, flowchart,


program to find remainder and
quotient
Operators Used:

 Quotient: / (integer division)


 Remainder: % (modulus operator)
Algorithm:

1. START
2. Declare variables: dividend, divisor, quotient, remainder
3. INPUT: Read dividend and divisor
4. PROCESS: quotient = dividend / divisor
5. PROCESS: remainder = dividend % divisor
6. OUTPUT: Display quotient and remainder
7. STOP
Flowchart:
START
|

INPUT dividend, divisor
|

quotient = dividend / divisor
|

remainder = dividend % divisor
|

OUTPUT quotient, remainder
|

STOP

C Program:
#include<stdio.h>

int main()
{
int dividend, divisor, quotient, remainder;

printf("Enter dividend: ");


scanf("%d", &dividend);

printf("Enter divisor: ");


scanf("%d", &divisor);

if(divisor == 0)
{
printf("Error: Division by zero not allowed!\n");
}
else
{
quotient = dividend / divisor;
remainder = dividend % divisor;

printf("\n--- Division Result ---\n");


printf("%d ÷ %d = %d with remainder %d\n", dividend, divisor,
quotient, remainder);
}

return 0;

}
Sample Output:
Enter dividend: 17
Enter divisor: 5

--- Division Result ---


17 ÷ 5 = 3 with remainder 2

Question 30: Define an Algorithm.


List advantages and features
Definition of Algorithm:
An algorithm is a finite sequence of well-defined, unambiguous steps designed to
solve a specific problem or achieve a particular objective.

Characteristics of a Good Algorithm:

1. Finiteness: Must terminate after executing finite number of steps


2. Definiteness: Each step must be clear and unambiguous
3. Input: Must accept zero or more inputs
4. Output: Must produce at least one output
5. Effectiveness: Steps must be feasible and simple
6. Independent: Must be independent of programming language
Advantages of Algorithm:

1. Easy Problem Understanding

o Clear step-by-step breakdown of problem


o Easier for programmers to understand solution approach
2. Efficient Programming

o Provides structured approach to coding


o Reduces development time and effort
3. Error Detection

o Helps identify logical errors before coding


o Reduces debugging time during implementation
4. Optimal Solution

o Allows analysis of different approaches


o Enables selection of most efficient solution
5. Easy Communication

o Pseudo-code or algorithm language universal


o Easier to explain to team members
6. Language Independent

o Not tied to any specific programming language


o Can implement in any language
7. Quality Assurance

o Easier to review and validate


o Can be tested at logical level
8. Reusability

o Once developed, algorithm can be reused


o Saves time in future projects

Question 31: What is the procedure


to design an algorithm in C
Steps to Design an Algorithm:

Step 1: Problem Analysis


 Clearly understand the problem requirements
 Identify inputs, outputs, and constraints
 Determine scope and limitations

Step 2: Problem Definition


 Clearly state what problem needs to be solved
 List all requirements and conditions
 Identify special cases and edge cases

Step 3: Breaking into Smaller Parts


 Divide large problem into smaller subproblems
 Use top-down approach (divide and conquer)
 Focus on solving one part at a time

Step 4: Logical Sequencing


 Arrange steps in correct logical order
 Use control structures: sequence, selection, iteration
 Ensure proper flow of operations

Step 5: Algorithm Development


 Write algorithm in simple English or pseudocode
 Use clear variable names
 Include comments for clarity

Step 6: Algorithm Validation


 Test algorithm with sample test cases
 Verify correctness of logic
 Check for boundary conditions

Step 7: Optimization
 Analyze algorithm efficiency
 Reduce unnecessary steps
 Improve time and space complexity

Step 8: Implementation
 Convert algorithm to C code
 Follow coding standards
 Add necessary comments

Step 9: Testing
 Test with various test cases
 Check for errors and exceptions
 Verify output correctness
Example: Algorithm to Find Maximum of Three Numbers
Algorithm: Find Maximum

1. START
2. Read three numbers: a, b, c
3. Assume a is maximum, max = a
4. If b > max, then max = b
5. If c > max, then max = c
6. Display max
7. STOP
Question 32: Define Flowchart.
Explain different symbols used in
flowchart
Definition:
A flowchart is a graphical representation of an algorithm or process using
standard symbols connected by arrows to show the flow of control and sequence
of operations.

Purpose of Flowchart:

 Visual representation of program logic


 Easy to understand for non-programmers
 Helps identify logical errors before coding
 Serves as documentation
Standard Flowchart Symbols:

1. Terminator (Oval/Ellipse)
Purpose: Indicates start or end of algorithm
Symbol: Oval shape
┌─────────┐
│ START │
└─────────┘

2. Process (Rectangle)
Purpose: Represents computation or operation
Symbol: Rectangle
Examples: sum = a + b, x = x + 1
┌───────────┐
│ PROCESS │
└───────────┘

3. Input/Output (Parallelogram)
Purpose: Represents input from user or output to user
Symbol: Parallelogram
Examples: INPUT: age, OUTPUT: sum
┌─────────────┐
│ INPUT/OUT │
└─────────────┘

4. Decision (Diamond)
Purpose: Represents conditional branching
Symbol: Diamond shape
Contents: Condition or question with True/False or Yes/No branches

/
/
Yes No

5. Flow Lines (Arrows)


Purpose: Shows direction of flow
Symbol: Arrows pointing from one symbol to another
↓ or → or ↑ or ←

6. Connector (Small Circle)


Purpose: Connects different parts of flowchart
Symbol: Small circle with letter/number
Use: When flowchart spans multiple pages
⊙ (A) ... (A) ⊙

7. Subroutine (Rectangle with double lines)


Purpose: Calls to separate procedure or function
Symbol: Rectangle with vertical double lines on sides
║─────────║
║ CALL ║
║─────────║

8. Document (Rectangle with curved bottom)


Purpose: Represents document or report
Symbol: Rectangle with curved bottom edge
┌─────────┐
│ DOCUMENT│
╰─────────╯

Example Flowchart: Find Greater of Two Numbers

START


INPUT a, b


a > b?
/ \
YES NO
│ │
↓ ↓
a is b is
greater greater
│ │
\ /
\ /
STOP

Flowchart Design Rules:

1. Flow: Always shows from top to bottom (preferred) or left to right


2. Clarity: Use standard symbols and make lines clear
3. Simplicity: Keep flowchart simple and avoid complexity
4. Consistency: Use consistent size and style for symbols
5. Labeling: Clear and meaningful labels on symbols
6. Connections: Clear flow lines connecting symbols
7. Termination: Always have START and STOP symbols
Advantages of Flowchart:

 Easy visual representation


 Helps non-technical people understand process
 Identifies logical errors before coding
 Useful for documentation
 Easy to modify
Limitations:

 Difficult for large and complex algorithms


 Time-consuming to create
 Updates require complete redrawing
 Less suitable for modern programming languages

Summary Tips for Exam


1. Program Structure: Always include #include, main(), and return 0;
2. Variables: Use meaningful names and declare before use
3. Input/Output: Use scanf() for input and printf() for output
4. Format Specifiers: Match format specifier with data type (%d, %f, %c,
%s)
5. Operators: Use correct operators for intended operations
6. Algorithm: Write clear, step-by-step algorithm before coding
7. Flowchart: Use standard symbols and clear flow direction
8. Testing: Test program with multiple test cases
9. Comments: Add meaningful comments in code
10. Compilation: Know the compilation and execution process

Document prepared for SNPSU CSE Department


Problem Solving Using C (25BECPHY104)
Module 1 Comprehensive Answer Bank - Exam Ready

You might also like