2nd and 3rd Flashcards
Q8.3: How is the greater number determined in the code?
By comparing num1 and num2; if num1 is greater, it is selected, otherwise num2 is selected.
Q8.3: Provide a code snippet for the swap function.
\nvoid swap(int *a, int *b) {\n int temp = *a; // Store value of *a\n *a = *b; // Assign value of *b to *a\n *b = temp; // Assign stored value to *b\n}\n
Q2: What is the main functionality of the Electricity Bill Calculator program?
Explanation
This program calculates the total electricity bill based on the number of units consumed with a tiered pricing model:
For the first 200 units: Rs 1 per unit.
For the next 100 units: Rs 1.5 per unit.
Beyond 300 units: Rs 2 per unit.
Input Validation:
The program checks if the input is a non-negative integer.
Code Example
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
int units;
float total = 0.0;
// Prompt user for input and validate printf("Enter number of units consumed: "); if (scanf("%d", &units) != 1 || units < 0) { printf("Invalid input. Please enter a non-negative integer.\n"); return 1; } // Calculate bill based on the units consumed if (units <= 200) { total = units * 1.0; // Rs 1 per unit for first 200 units } else if (units <= 300) { total = 200 * 1.0 + (units - 200) * 1.5; // Next 100 units at Rs 1.5 each } else { total = 200 * 1.0 + 100 * 1.5 + (units - 300) * 2.0; // Beyond 300 units at Rs 2 each } printf("Total electricity bill: Rs %.2f\n", total); return 0; }
Q2.6: What calculation is done for units above 300?
The program computes the cost for the first 200 units, then the next 100 units, and finally multiplies the remaining units by 2.0.
Q10.9: Summarize the differences between all four storage classes.
External variables are globally scoped and persistent, static variables are local but persistent, automatic variables are local and temporary, and register variables are optimized for speed.
Q7.1: What loop structure is used in the sum of natural numbers program?
A for loop is used to iterate from 1 to N.
Q9.1: What does the continue statement do inside a loop?
It immediately skips the remaining code in the current iteration and moves to the next iteration of the loop.
Q10.1: What defines an external variable in C?
An external variable is declared outside any function, has global scope, and persists for the entire program run.
Q3.1: Define actual parameters in the context of a function call.
They are the arguments provided to a function when it is called, representing the actual data used by the function.
Q5.2: Provide an example of a function with parameters and no return value.
\nvoid displaySum(int a, int b) {\n printf(\"Sum: %d\", a + b);\n}\n
Q9.2: Recap the role of formal parameters.
They are placeholders in the function definition that receive the actual parameters.
Q10.6: Provide a code snippet that demonstrates a static variable inside a function.
\nvoid func() {\n static int count = 0; // Retains its value between calls\n count++;\n printf(\"Count: %d\\n\", count);\n}\n
Q1.3: How do you handle multiple data types in one program?
By declaring variables of different types (int, float, char) and using proper format specifiers in printf and scanf to read and display their values.
Q4.5: Provide an example code snippet demonstrating call by reference.
\nvoid swap(int *a, int *b) {\n int temp = *a;\n *a = *b;\n *b = temp;\n}\n
Q9.3: Provide a simple code snippet demonstrating this concept.
\nvoid displayNumber(int num) { // 'num' is a formal parameter\n printf(\"Number: %d\\n\", num);\n}\n\nint main() {\n int value = 25; // 'value' is the actual parameter\n displayNumber(value);\n return 0;\n}\n
Q3.4: Continuing with 153, what is the result of 153 / 10?
153 / 10 equals 15, effectively removing the last digit (3) from 153.
Q10: How do external, static, automatic, and register variables differ in C?
Explanation
C provides several storage classes that determine the scope, lifetime, and memory allocation of variables:
External Variables:
Scope: Global (accessible from any file if declared with extern).
Lifetime: Exists for the duration of the program.
Memory: Allocated in the global data area.
Example:
c
Copy
Edit
int globalVar = 10; // Global variable accessible throughout the program
Static Variables:
Scope: Local to the block where declared (if declared inside a function), but retain their value between function calls.
Lifetime: Entire program run.
Memory: Allocated in the static data area.
Example:
c
Copy
Edit
void func() {
static int count = 0; // Retains its value between calls
count++;
printf(“Count: %d\n”, count);
}
Automatic Variables:
Scope: Local to the block or function where declared.
Lifetime: Exists only during the execution of the block/function.
Memory: Allocated on the stack.
Example:
c
Copy
Edit
void func() {
int localVar = 5; // Automatic variable, created and destroyed with the function call
printf(“Local Variable: %d\n”, localVar);
}
Register Variables:
Scope: Local to the block or function where declared.
Lifetime: Similar to automatic variables.
Memory: Hinted to be stored in CPU registers for faster access, though modern compilers optimize this automatically.
Example:
c
Copy
Edit
void func() {
register int counter = 0; // Suggests storing in a CPU register
counter++;
printf(“Counter: %d\n”, counter);
}
Summary
External: Global scope, exists for the program’s duration.
Static: Local scope with extended lifetime.
Automatic: Local scope, created and destroyed with the function call.
Register: Similar to automatic but optimized for speed.
Q1.2: Why does isPrime loop up to the square root of the number?
Because if a number has a divisor greater than its square root, the corresponding divisor would be less than the square root, so checking up to sqrt(n) is sufficient.
Q3.4: Provide a code example that illustrates the difference between actual and formal parameters.
\nvoid display(int num) { // 'num' is a formal parameter\n printf(\"Value is: %d\\n\", num);\n}\n\nint main() {\n int actualValue = 10; // 'actualValue' is an actual parameter\n display(actualValue);\n return 0;\n}\n
Q1.1: What does the isPrime function do in the Prime Number Generator?
It checks whether a given number is prime by returning false for numbers ≤1 and looping from 2 to sqrt(n) to see if any number divides it evenly.
Q8.1: What is the primary method used to compare two numbers in the program?
An if-else statement is used to compare the two numbers.
Q7.3: Provide a code snippet that demonstrates call by value.
\nvoid modifyValue(int x) {\n x = 100;\n}\n
Q2.5: Show the code used when the units are between 201 and 300.
\nelse if (units <= 300) {\n total = 200 * 1.0 + (units - 200) * 1.5;\n}\n
Q5.4: Provide an example of a function without parameters and without a return value.
\nvoid greet() {\n printf(\"Hello there!\\n\");\n}\n
Q4.2: What does call by reference mean in function parameter passing?
It means the function receives the address of the argument, allowing the function to modify the original variable.
Q3.3: Using 153 as an example, what is 153 % 10 and why?
153 % 10 equals 3, because the remainder of dividing 153 by 10 is 3, the last digit.
Q9.1: Recap the role of actual parameters.
They supply the real data that a function uses when it is called.
Q10.3: Why is using goto generally discouraged?
Because it can make code harder to read and maintain, leading to “spaghetti code”. However, it may be useful for simple error handling.
Q7.1: How does call by value protect the original variable?
Since the function works on a copy, any modifications do not affect the original variable.
Q2.8: How is floating-point arithmetic used in this program?
It uses a float variable to store the total bill, ensuring that fractional amounts are correctly calculated and displayed.
Q1.4: Provide a code snippet showing the for loop used in the Prime Number Generator.
\nfor (int i = 1; i <= n; i++) {\n if (isPrime(i)) {\n printf(\"%d \", i);\n }\n}\n
Original Q1: Addition and I/O - Write a C program that adds two numbers and demonstrate the use of printf and scanf for different data types.
Explanation:
I/O Functions:
printf is used to display output.
scanf is used to read input from the user.
Data Types:
We demonstrate how to work with multiple data types such as int, float, and char.
Process:
The program reads two numbers, performs addition, and then prints the results.
Code Example:
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
int intNum1, intNum2; // Variables for integer values
float floatNum1, floatNum2; // Variables for floating-point values
char character; // Variable for a character
// Prompt and read two integer numbers from the user printf("Enter two integers: "); scanf("%d %d", &intNum1, &intNum2); // Calculate and display the sum of the integers int intSum = intNum1 + intNum2; printf("Sum of integers: %d\n", intSum); // Prompt and read two float numbers from the user printf("Enter two floating point numbers: "); scanf("%f %f", &floatNum1, &floatNum2); // Calculate and display the sum of the floats float floatSum = floatNum1 + floatNum2; printf("Sum of floats: %.2f\n", floatSum); // Prompt and read a character from the user printf("Enter a character: "); scanf(" %c", &character); // Notice the space before %c to consume any leftover whitespace // Display the character input printf("You entered: %c\n", character); return 0; }
Q8.5: Why is a temporary variable needed in the swap function?
It temporarily holds one of the values so that it is not overwritten when assigning the second value to the first variable.
Q4: How are user-defined functions classified based on parameter passing and return type?
A. Based on Parameter Passing
1. Call by Value
The function receives a copy of the actual parameter. Changes made inside the function do not affect the original variable.
c
Copy
Edit
#include <stdio.h></stdio.h>
// Function demonstrating call by value
int add(int a, int b) { // ‘a’ and ‘b’ are formal parameters
return a + b;
}
int main() {
int x = 5, y = 7;
printf(“Sum: %d\n”, add(x, y)); // x and y are actual parameters
return 0;
}
2. Call by Reference
The function receives the address of the actual parameter. Changes made inside the function affect the original variable.
c
Copy
Edit
#include <stdio.h></stdio.h>
// Function demonstrating call by reference
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1 = 5, num2 = 10;
swap(&num1, &num2); // Pass addresses of num1 and num2
printf(“num1 = %d, num2 = %d\n”, num1, num2);
return 0;
}
B. Based on Return Type
1. Functions that Return a Value
These functions perform calculations and return a value to the caller.
c
Copy
Edit
#include <stdio.h></stdio.h>
// Function that returns a value
int square(int num) {
return num * num;
}
int main() {
int value = 4;
printf(“Square: %d\n”, square(value));
return 0;
}
2. Functions that Do Not Return a Value
These functions perform actions (like printing) but do not return a value.
c
Copy
Edit
#include <stdio.h></stdio.h>
// Function with no return value (void)
void printMessage() {
printf(“Hello, World!\n”);
}
int main() {
printMessage();
return 0;
}
Q6.5: What does a function call do?
It invokes the function, passing actual parameters to the formal parameters, and executes the function’s code.
Q1.4: In the addition program, how are integer values read?
They are read using scanf with the format specifier %d, for example: scanf("%d %d", &intNum1, &intNum2).
Q6.1: What information does the function header provide?
It specifies the return type, function name, and list of parameters.
Q2.1: What is implicit type conversion?
Implicit type conversion is the automatic promotion of a smaller data type to a larger data type when an operation requires it.
Q4.3: How are functions classified based on their return type?
They are either functions that return a value (with a specific return type) or void functions that do not return any value.
Q9.3: What is the outcome of using continue in the example loop?
Only odd numbers (1, 3, 5, 7, 9) are printed, as even numbers are skipped.
Q8.2: Why is a for loop included even though it’s not required for comparing two numbers?
The for loop is included to meet the specific requirement of using one, even though it only iterates once.
Q8.4: What would happen if you tried swapping numbers using call by value instead?
Using call by value would only swap copies of the numbers, leaving the original values unchanged.
Q7: What is the difference between call by value and call by reference?
Explanation
Call by Value:
The function receives a copy of the argument. Changes inside the function do not affect the original variable.
Call by Reference:
The function receives the address of the argument. Changes inside the function modify the original variable.
Code Example
c
Copy
Edit
#include <stdio.h></stdio.h>
// Call by Value: The value is copied; changes do not affect the original variable.
void modifyValue(int x) {
x = 100;
}
// Call by Reference: The address is passed; changes affect the original variable.
void modifyReference(int *x) {
*x = 100;
}
int main() {
int a = 10, b = 10;
modifyValue(a); // a remains unchanged
modifyReference(&b); // b becomes 100
printf(“After modifyValue: a = %d\n”, a);
printf(“After modifyReference: b = %d\n”, b);
return 0;
}
Q8: How does the swap function using call by reference work in C?
Explanation
Swapping numbers by call by reference involves passing the addresses of the variables to a function, which then uses pointers to modify their values directly.
Code Example
c
Copy
Edit
#include <stdio.h></stdio.h>
// Function to swap two numbers using pointers (call by reference)
void swap(int *a, int *b) {
int temp = *a; // Save the value of *a in temp
*a = *b; // Assign the value of *b to *a
*b = temp; // Assign the saved value to *b
}
int main() {
int num1 = 5, num2 = 10;
printf(“Before swap: num1 = %d, num2 = %d\n”, num1, num2);
swap(&num1, &num2); // Pass addresses of num1 and num2
printf(“After swap: num1 = %d, num2 = %d\n”, num1, num2);
return 0;
}
Q10.2: How do static variables behave differently from automatic variables?
Static variables, although local in scope, retain their value between function calls, whereas automatic variables are reinitialized each time a function is called.
Q1.7: What is an efficiency consideration in the isPrime function?
Looping only up to the square root of the number avoids unnecessary checks and improves performance for larger numbers.
Q4.6: Summarize the main differences between call by value and call by reference.
Call by value creates a copy of the data, while call by reference passes the memory address, allowing the function to modify the original variable.
Q10.5: Provide a code snippet that demonstrates an external variable.
\nint globalVar = 10; // Global variable\n\nint main() {\n printf(\"Global variable: %d\\n\", globalVar);\n return 0;\n}\n
Q2.4: Provide an example of explicit conversion in C.
Example: float c = 5.8; int result = (int)c; This converts the float to an int, truncating the decimal part.
Q2.4: How does the program calculate the bill when units are ≤200?
It multiplies the number of units by 1.0, as each unit costs Rs 1.
Q5.2: What condition checks for a negative number?
else if(number < 0) is used to determine if the number is negative.
Q9.2: How is continue used in the provided example?
In the loop, if the current number is even (i % 2 == 0), the continue statement is executed, skipping the print statement for that iteration.
Q10.2: In the given example, when is goto used?
goto is used when a negative number is detected, jumping to the error handling section.
Q3.2: Define formal parameters in a function definition.
They are placeholders declared in the function signature that receive the values of the actual parameters.
Original Q7: Sum of Natural Numbers - Write a C program to calculate the sum of natural numbers from 1 to N using a for loop.
Explanation:
Objective:
Calculate the sum of natural numbers from 1 to N.
Process:
Use a for loop to iterate from 1 to N.
Accumulate the sum and then display the result.
Code Example:
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
int N, sum = 0;
// Prompt user to enter the value of N printf("Enter a positive integer N: "); scanf("%d", &N); // Calculate the sum of natural numbers from 1 to N using a for loop for (int i = 1; i <= N; i++) { sum += i; // Add the current number i to sum } // Display the result printf("Sum of natural numbers from 1 to %d is: %d\n", N, sum); return 0; } Bullet Points:
Loop:
Iterates from 1 to N.
Accumulation:
Adds each number to the sum.
Q10.7: Provide a code snippet that demonstrates an automatic variable.
\nvoid func() {\n int localVar = 5; // Automatic variable\n printf(\"Local Variable: %d\\n\", localVar);\n}\n
Q3.5: How does the Armstrong check determine if 153 is valid?
It cubes each extracted digit (3^3 = 27, 5^3 = 125, 1^3 = 1), sums them (27+125+1 = 153) and compares this sum with the original number.
Q6.1: What is a palindrome number?
A palindrome number is one that reads the same forwards and backwards.
Q2.2: What is explicit type conversion?
Explicit type conversion (casting) is when a programmer manually converts one data type to another using a cast operator, e.g., (int)variable.
Q5.3: What does the else branch in the sign check code do?
It handles the case when the number is zero.
Q4.1: What causes the dangling else problem in C?
It is caused by nested if statements without proper braces, making it unclear which if the else belongs to.
Q10.3: What is the typical lifetime and scope of an automatic variable?
They are local to the function/block in which they are declared and only exist during the execution of that function.
Q9.5: What are some tips for avoiding common mistakes with parameter passing?
Always match the type and number of parameters in function calls and be clear whether data should be modified (use reference) or preserved (use value).
Q4.1: What does call by value mean in function parameter passing?
It means the function receives a copy of the argument, so modifications inside the function do not affect the original variable.
Original Q4: Dangling Else Problem - Describe the dangling else problem and provide a solution.
Explanation:
Problem:
Occurs when an else statement can be paired with more than one if, causing ambiguity.
Solution:
Use braces {} to clearly define the blocks and ensure the correct association of if-else.
Code Example (Problem Demonstration):
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
int a = 5, b = 10, c = 15;
// Without braces, the else pairs with the nearest if, which may not be the intended logic. if (a < b) if (a < c) printf("a is smallest\n"); else // This else pairs with the second if, not the first if. printf("c is smallest\n"); return 0; } Code Example (Solution with Braces):
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
int a = 5, b = 10, c = 15;
// Using braces to clearly define which if statement the else belongs to if (a < b) { if (a < c) { printf("a is smallest\n"); } else { printf("c is smallest\n"); } } else { printf("b is smallest\n"); } return 0; } Bullet Points:
Issue:
Ambiguous else statement.
Resolution:
Always use braces to clearly associate if and else blocks.
Q1: What is the overall purpose of the Prime Number Generator program?
Explanation
The program below asks the user for a number n and then prints all prime numbers between 1 and n. A helper function (isPrime) is used to check whether a number is prime.
Prime Check:
Any number less than or equal to 1 is not prime.
For numbers greater than 1, we loop from 2 to the square root of the number. If any divisor evenly divides the number, it is not prime.
Loop Structure:
The for loop in main() iterates from 1 to n. For each iteration, it calls isPrime to decide whether to print the number.
Code Example
c
Copy
Edit
#include <stdio.h>
#include <stdbool.h>
#include <math.h></math.h></stdbool.h></stdio.h>
// Function to check if a number is prime
bool isPrime(int num) {
if (num <= 1)
return false; // Numbers <= 1 are not prime
// Check divisibility from 2 to sqrt(num) for (int i = 2; i <= sqrt(num); i++) { if (num % i == 0) { return false; // Not prime if divisible by i } } return true; // Prime if no divisor found }
int main() {
int n;
printf(“Enter the upper limit (n): “);
scanf(“%d”, &n);
printf("Prime numbers between 1 and %d are:\n", n); // Loop from 1 to n for (int i = 1; i <= n; i++) { if (isPrime(i)) { printf("%d ", i); // Print if i is prime } } printf("\n"); return 0; }.
Q6.4: What is the significance of the return type in a function declaration?
It indicates the type of data that the function will return; if the function doesn’t return a value, the return type is void.
Q2.3: Provide a code snippet that demonstrates the input validation used.
\nprintf(\"Enter number of units consumed: \");\nif (scanf(\"%d\", &units) != 1 || units < 0) {\n printf(\"Invalid input. Please enter a non-negative integer.\\n\");\n return 1;\n}\n
Q7.2: How is the sum of natural numbers computed in the loop?
Each number from 1 to N is added to a running total using the statement sum += i.
Q6.3: How is the reversed number compared to the original?
After the loop, the reversed number is compared with the original number; if they are equal, it is a palindrome.
Q9.4: Why is it important to understand the difference between actual and formal parameters?
It helps avoid confusion about data flow into functions and ensures that functions are used correctly and efficiently.
Q3.3: How do actual and formal parameters interact during a function call?
During the call, the actual parameters’ values are copied or referenced into the formal parameters, allowing the function to work with that data.
Original Q6: Palindrome Number Check - Write a C program to check whether a given number is a palindrome.
Explanation:
Definition:
A palindrome number reads the same forward and backward.
Process:
Reverse the number using modulus and division.
Compare the reversed number with the original number.
Code Example:
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
int number, original, remainder, reversed = 0;
// Prompt user for a number printf("Enter a number: "); scanf("%d", &number); // Save the original number for comparison later original = number; // Reverse the number while (number != 0) { remainder = number % 10; // Extract last digit reversed = reversed * 10 + remainder; // Append digit to reversed number number /= 10; // Remove the last digit } // Check if the original number and reversed number are equal if (original == reversed) printf("%d is a palindrome.\n", original); else printf("%d is not a palindrome.\n", original); return 0; } Bullet Points:
Reverse Process:
Use loop to extract and accumulate digits.
Comparison:
Compare original and reversed numbers.
Q2.3: Provide an example of implicit conversion in C.
For instance, when an int (10) is added to a float (3.5), the int is automatically converted to float to perform the addition.
Q2.2: How does the program validate user input in the Electricity Bill Calculator?
It checks if the input from scanf is a valid non-negative integer. If not, it outputs an error message and exits.
Q10.4: What is the purpose of a register variable in C?
It suggests to the compiler that the variable should be stored in a CPU register for faster access, though actual placement is compiler-dependent.
Q3.2: How do you remove the last digit from a number?
By performing integer division by 10 (number = number / 10), which discards the last digit.
Original Q10: Unconditional goto Statement - Write a C program demonstrating the use of goto and explain its effect on control flow.
Explanation:
Usage:
goto provides an unconditional jump to another part of the program.
Flow of Control:
Although generally discouraged due to potential for creating “spaghetti code,” it can be useful in specific scenarios like error handling.
Process:
Use goto to jump to a labeled section in the code.
Code Example:
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
int number;
// Prompt user for a number printf("Enter a positive number (or a negative to jump to error handling): "); scanf("%d", &number); // If the number is negative, jump to error handling section using goto if (number < 0) { goto error; // Unconditional jump to label 'error' } // Normal processing if number is positive printf("You entered a positive number: %d\n", number); return 0;
error:
// Label for error handling
printf(“Error: You entered a negative number.\n”);
return 1;
}
Bullet Points:
Label:
error: marks the destination for the goto.
Usage:
Direct jump from the if statement to the error handling block.
Q7.4: Provide a code snippet that demonstrates call by reference.
\nvoid modifyReference(int *x) {\n *x = 100;\n}\n
Q6.2: What is contained in the function body?
The function body is the code block enclosed in braces that implements the function’s logic.
Q6: What are the main elements of a user-defined function in C?
Explanation of Elements
Function Header:
Contains the return type, function name, and parameter list.
Function Body:
The block of code within braces {} that defines what the function does.
Parameters:
Variables passed to the function (if any). These are known as formal parameters.
Return Type:
Specifies the type of data the function returns. If the function does not return any data, the return type is void.
Function Call:
How the function is invoked in a program.
Code Example
c
Copy
Edit
#include <stdio.h></stdio.h>
// Function header: return type ‘int’, name ‘add’, and parameters (int a, int b)
int add(int a, int b) {
// Function body: perform addition and return result
return a + b;
}
int main() {
// Function call: passing actual parameters 3 and 4
int result = add(3, 4);
printf(“Result of addition: %d\n”, result);
return 0;
}
Q1.2: What is the purpose of scanf in C?
scanf is used to read user input from the console and store it in variables.
Q3: What is the difference between actual parameters and formal parameters in C?
Explanation
Actual Parameters: The real values or variables passed to a function when it is called.
Formal Parameters: The variables defined in the function definition that receive the actual parameters.
Code Example
c
Copy
Edit
#include <stdio.h></stdio.h>
// Function with a formal parameter ‘num’
void display(int num) {
printf(“Value is: %d\n”, num); // Using the formal parameter
}
int main() {
int actualValue = 10; // This is the actual parameter
display(actualValue); // Passing the actual parameter to the function
return 0;
}
Q9: What is the difference between actual and formal parameters? (Revisited)
Explanation
As before, actual parameters are the arguments provided during a function call, while formal parameters are the variables defined in the function declaration that receive these arguments.
Code Example
c
Copy
Edit
#include <stdio.h></stdio.h>
// ‘num’ is the formal parameter in the function definition
void displayNumber(int num) {
printf(“Number: %d\n”, num);
}
int main() {
int value = 25; // ‘value’ is the actual parameter
displayNumber(value); // Actual parameter is passed to the function
return 0;
}
Q5.3: Provide an example of a function without parameters but with a return value.
\nint getMagicNumber() {\n return 42;\n}\n
Q1.1: What is the purpose of printf in C?
printf is used to display text and variable values to the console.
Original Q3: Armstrong Number Check - Write a C program to check if a 3-digit number is an Armstrong number.
Explanation:
Definition:
An Armstrong number (for 3-digit numbers) is one where the sum of the cubes of its digits equals the number itself.
Steps:
Extract digits using modulus and division.
Cube each digit, sum them, and compare to the original number.
Code Example:
c
Copy
Edit
#include <stdio.h>
#include <math.h> // Required for pow() function</math.h></stdio.h>
int main() {
int number, originalNumber, remainder, result = 0;
// Prompt user for a 3-digit number printf("Enter a 3-digit number: "); scanf("%d", &number); // Save the original number for later comparison originalNumber = number; // Loop to extract each digit while (number != 0) { remainder = number % 10; // Get the last digit result += pow(remainder, 3); // Cube the digit and add to the result number /= 10; // Remove the last digit } // Check if the number is an Armstrong number if (result == originalNumber) printf("%d is an Armstrong number.\n", originalNumber); else printf("%d is not an Armstrong number.\n", originalNumber); return 0; }
Original Q8: Finding the Greater Number - Write a C program to find the greater of two numbers using a for loop and an if statement.
Explanation:
Objective:
Find the greater of two numbers.
Additional Requirement:
Although a loop is not typically required, we include one to satisfy the specification.
Logic:
Use a for loop (even if trivial) and an if statement to compare the two numbers.
Code Example:
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
int num1, num2, greater;
// Prompt user for two numbers printf("Enter two numbers: "); scanf("%d %d", &num1, &num2); // Using a for loop as required (this loop runs only once) for (int i = 0; i < 1; i++) { // Compare the two numbers using if-else if (num1 > num2) greater = num1; else greater = num2; } // Print the greater number printf("The greater number is: %d\n", greater); return 0; } Bullet Points:
Comparison:
if (num1 > num2) to decide the greater number.
For Loop:
Included to meet the problem’s requirement.
Q6.7: Why are inline comments important in function definitions?
They clarify the purpose and logic of each part of the function, making the code easier to understand and maintain.
Q4.4: How does adding braces resolve this ambiguity?
Using braces, as in: if(a < b) { if(a < c) { printf("a is smallest"); } else { printf("c is smallest"); } } else { printf("b is smallest"); } makes the association explicit.
Q1.6: How are inline comments used in the Prime Number Generator code?
They explain each part of the code, such as the purpose of the for loop and the logic inside the isPrime function, making the code easier to understand.
Q5.1: Provide an example of a function with parameters and a return value.
\nint multiply(int a, int b) {\n return a * b;\n}\n
Q2.1: Describe the tiered pricing model used in the Electricity Bill Calculator.
The first 200 units cost Rs 1 per unit, the next 100 units cost Rs 1.5 per unit, and any units beyond 300 cost Rs 2 per unit.
Q1.5: What constitutes a prime number according to this program?
A prime number is a number greater than 1 that has no divisors other than 1 and itself.
Q8.2: What role do pointers play in swapping numbers by call by reference?
Pointers allow the function to access the actual memory addresses of the variables, so the swap affects the original variables.
Q4.4: Provide an example code snippet demonstrating call by value.
\nint add(int a, int b) {\n return a + b;\n}\n
Q6.2: How do you reverse a number in C?
By using a loop to extract each digit with modulus, then accumulating them into a reversed number using multiplication and addition.
Original Q9: Usage of the Continue Statement - Explain and demonstrate the use of continue in loops with an example in C.
Explanation:
Purpose of continue:
Skips the current iteration in a loop and moves directly to the next iteration.
Example Scenario:
Print numbers from 1 to 10 but skip printing even numbers.
Process:
Use an if statement inside a loop to check for even numbers and use continue to skip the rest of the loop body.
Code Example:
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
// Loop from 1 to 10
for (int i = 1; i <= 10; i++) {
// If the number is even, skip printing it
if (i % 2 == 0) {
continue; // Skip the rest of the loop for even numbers
}
// This line is executed only for odd numbers
printf(“%d “, i);
}
printf(“\n”);
return 0;
}
Bullet Points:
Condition Check:
if (i % 2 == 0) checks for even numbers.
continue Statement:
Causes the loop to skip to the next iteration for even values.
Q7.2: How does call by reference allow a function to modify a variable?
By passing the variable’s address, the function can access and modify the original variable directly through its pointer.
Q6.6: Provide a code snippet that demonstrates a complete function definition and call.
\nint add(int a, int b) { // Function header and body\n return a + b;\n}\n\nint main() {\n int result = add(3, 4); // Function call\n printf(\"Result: %d\\n\", result);\n return 0;\n}\n
Q3.1: How do you extract the last digit of a number using modulus?
Using the expression number % 10 returns the last digit of the number.
Q7.5: What are the typical use cases for call by value versus call by reference?
Call by value is used when you want to preserve the original data, while call by reference is used when you need to modify the original data or return multiple values.
Q7.3: Why is user input required in this program?
User input defines the upper bound N, determining how many natural numbers to sum.
Q5.5: How do these function definitions differ in their usage?
Functions with parameters allow external data to be passed in, while those without parameters do not. Similarly, functions with return values provide data back to the caller, unlike void functions.
Q1.3: How does the main function use isPrime in the Prime Number Generator?
The main function uses a for loop to iterate from 1 to n and calls isPrime for each number; if true, the number is printed.
Q2.7: Provide the code snippet for the >300 units calculation.
\nelse {\n total = 200 * 1.0 + 100 * 1.5 + (units - 300) * 2.0;\n}\n
Q6.3: How are parameters used in a function?
Parameters act as local variables that receive values from the function call and are used within the function to perform operations.
Q5: What are the four possible ways to define a user-defined function in C?
- With Parameters and with Return Value
c
Copy
Edit
// Function with parameters and a return value
int multiply(int a, int b) {
return a * b;
} - With Parameters and without Return Value
c
Copy
Edit
#include <stdio.h></stdio.h>
// Function with parameters and no return value (void)
void displaySum(int a, int b) {
printf(“Sum: %d\n”, a + b);
}
3. Without Parameters and with Return Value
c
Copy
Edit
// Function without parameters but returns a value
int getMagicNumber() {
return 42;
}
4. Without Parameters and without Return Value
c
Copy
Edit
#include <stdio.h></stdio.h>
// Function without parameters and no return value (void)
void greet() {
printf(“Hello there!\n”);
}
Q5.1: What condition is used to check if a number is positive?
if(number > 0) is used to check if the number is positive.
Q8.1: Describe the step-by-step process of the swap function.
First, the value of *a is stored in a temporary variable. Then *a is assigned the value of *b, and finally, *b is assigned the temporary value, completing the swap.
Q4.3: Provide an example of ambiguous if-else code.
if(a < b) if(a < c) printf("a is smallest"); else printf("c is smallest"); // Here, the else pairs with the inner if by default.
Q10.8: Provide a code snippet that demonstrates a register variable.
\nvoid func() {\n register int counter = 0; // Suggests fast access storage\n counter++;\n printf(\"Counter: %d\\n\", counter);\n}\n
Q4.2: How can you resolve the dangling else problem?
By using braces to clearly delimit the intended if and else blocks.
Q10.4: How is a label defined for goto in C?
A label is defined by a name followed by a colon (e.g., error:), which marks the destination for a goto jump.
Original Q5: Number Sign Check - Write a snippet of C code to check if a number is positive, negative, or zero.
Explanation:
Objective:
Determine if a number is positive, negative, or zero.
Logic:
Use an if-else if-else structure to evaluate the number and print the corresponding message.
Code Example:
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
int number;
// Prompt user for a number printf("Enter a number: "); scanf("%d", &number); // Check the sign of the number if (number > 0) { printf("The number is positive.\n"); } else if (number < 0) { printf("The number is negative.\n"); } else { printf("The number is zero.\n"); } return 0; } Bullet Points:
Positive Check:
if (number > 0)
Negative Check:
else if (number < 0)
Zero Check:
else
Original Q2: Type Conversion Methods - Define type conversion methods in C with examples of implicit and explicit conversion.
IExplanation:
Implicit Conversion (Automatic):
Occurs automatically when operands of different data types are used together.
Explicit Conversion (Casting):
The programmer forces a conversion by specifying the target type in parentheses.
Examples:
Implicit: Assigning an int to a float automatically converts the value.
Explicit: Converting a float to an int to remove the decimal part.
Code Example:
c
Copy
Edit
#include <stdio.h></stdio.h>
int main() {
// Implicit conversion example:
int a = 10;
float b = 3.5;
float resultImplicit = a + b; // ‘a’ is implicitly converted to float
printf(“Implicit conversion (int to float): %.2f\n”, resultImplicit);
// Explicit conversion (casting) example: float c = 5.8; int resultExplicit = (int)c; // Casting float to int truncates the decimal part printf("Explicit conversion (float to int): %d\n", resultExplicit); return 0; } Bullet Points:
Implicit Conversion:
Automatic type promotion.
No additional syntax required.
Explicit Conversion:
Requires a cast operator.
Allows controlled conversion.
Q10.1: What does the goto statement do in C?
It causes an unconditional jump to a labeled statement within the same function, altering the normal control flow.