1st Flashcards
Write an algorithm to check whether a given number is prime or not.
Start.
Input a number n.
If n <= 1, then:
Print “Not Prime”
Stop.
If n = 2, then:
Print “Prime”
Stop.
If n is even (n % 2 = 0) and n > 2, then:
Print “Not Prime”
Stop.
Set i = 3.
While i is less than or equal to the integer part of the square root of n, do:
If n % i = 0, then:
Print “Not Prime”
Stop.
Increase i by 2.
If no divisor is found in the loop, then:
Print “Prime”.
End.
What is a prime number?
A prime number is a number greater than 1 that has no divisors other than 1 and itself.
What is the main idea of the prime-checking algorithm?
The algorithm checks if a number n is prime by testing divisibility from 2 (or 3 for odd numbers) up to the square root of n.
What are the critical edge cases in this algorithm?
Edge cases include: n <= 1 (not prime), n = 2 (prime), and even numbers greater than 2 (not prime).
Why do we only check divisibility up to the square root of n?
Because if n has a factor larger than its square root, it must have a corresponding factor smaller than the square root.
Why is the number 2 handled separately in the algorithm?
2 is the only even prime number, so it can be immediately classified as prime without further checks.
How does the algorithm optimize the loop for checking factors?
After handling even numbers, the algorithm checks only odd numbers (incrementing by 2) from 3 to the square root of n.
What is the basic structure of the pseudocode for this algorithm?
If n <= 1, print ‘Not Prime’. If n == 2, print ‘Prime’. If n is even, print ‘Not Prime’. Otherwise, loop i from 3 to floor(sqrt(n)) (step 2) and if n mod i == 0, print ‘Not Prime’; if no divisor is found, print ‘Prime’.
Can you provide a concrete example using the number 49?
For n = 49, the square root is 7. The algorithm checks odd numbers: 3 and 5 do not divide 49, but 7 does, so 49 is not prime.
What is a disadvantage of this simple prime-checking algorithm?
It may not be efficient for very large numbers, where more advanced techniques (like probabilistic tests) would be preferable.
How does this algorithm improve computational efficiency compared to checking all numbers up to n?
By limiting the range to the square root of n and skipping even numbers (after 2), the algorithm significantly reduces the number of checks needed.
Draw a flowchart to print the ASCII value of a character.
+———–+
| Start |
+———–+
|
v
+———————–+
| Input a character (ch)|
+———————–+
|
v
+———————–+
| Get ASCII value of ch |
| (e.g., ord(ch)) |
+———————–+
|
v
+———————–+
| Print the ASCII value |
+———————–+
|
v
+———–+
| End |
+———–+
Which header files are included in the program and why?
The program includes <stdio.h> for input/output functions and <math.h> for mathematical functions like sqrt().</math.h></stdio.h>
What are the variables used to store the quadratic equation coefficients?
The coefficients are stored in double a, b, c.
How is the discriminant calculated in the code?
The discriminant is calculated as discriminant = b * b - 4 * a * c.
What does the discriminant tell you about the quadratic equation?
It indicates: Positive means two distinct real roots; Zero means one real repeated root; Negative means two complex roots.
What condition is checked to determine if there are two distinct real roots?
The program checks if discriminant > 0.
How are the two distinct real roots calculated?
They are calculated as root1 = (-b + sqrt(discriminant)) / (2 * a) and root2 = (-b - sqrt(discriminant)) / (2 * a).
What condition is checked to determine if there is one repeated real root?
The program checks if discriminant == 0.
How is the repeated real root computed?
It is computed as root1 = -b / (2 * a).
What condition leads to calculating complex roots?
Complex roots are calculated when discriminant < 0.
How are the real and imaginary parts of complex roots calculated?
The real part is computed as -b / (2 * a) and the imaginary part as sqrt(-discriminant) / (2 * a).
What function is used to compute the square root in the program?
The sqrt() function from <math.h> is used to compute square roots.</math.h>
What message is printed when two distinct real roots are found?
It prints ‘Two distinct real roots: [root1] and [root2]’.
What output does the program produce for a repeated real root?
It prints ‘One real repeated root: [root1]’.
What output is given when the equation has complex roots?
It prints ‘Complex roots: [realPart] + [imaginaryPart]i and [realPart] - [imaginaryPart]i’.
Why do we use (2 * a) in the formulas for the roots?
(2 * a) is used as the denominator in the quadratic formula to divide the computed numerators for both real and complex roots.
What is the purpose of inline comments in the code?
Inline comments explain each step of the code, making it easier to understand the logic and flow of the program.
How does the program prompt the user for input?
The program uses printf to ask the user for coefficients a, b, and c, then reads the input using scanf.
What does the return 0; statement at the end of main() signify?
It indicates that the program executed successfully without errors.
How should you compile this program, and why is the -lm flag necessary?
Compile with ‘gcc quadratic.c -o quadratic -lm’. The -lm flag links the math library required for functions like sqrt().
In which scenario is the sqrt() function used with a negated discriminant?
When the discriminant is negative, sqrt(-discriminant) is used to compute the imaginary part of the complex roots.
Write a c program that calculates the roots of a quadratic equation given coefficients a, b, and c.
include <stdio.h></stdio.h>
#include <math.h></math.h>
int main() {
double a, b, c; // Coefficients of the quadratic equation
double discriminant; // Variable to store the discriminant (b² - 4ac)
double root1, root2; // Variables to store the roots of the equation
double realPart, imaginaryPart; // Variables to store the real and imaginary parts for complex roots
// Prompt the user to enter coefficients for the quadratic equation ax^2 + bx + c = 0 printf("Enter coefficients a, b, and c: "); scanf("%lf %lf %lf", &a, &b, &c); // Calculate the discriminant: b² - 4ac discriminant = b * b - 4 * a * c; // Check if the discriminant is positive if (discriminant > 0) { // Two distinct real roots exist root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); printf("Two distinct real roots: %.2lf and %.2lf\n", root1, root2); } // Check if the discriminant is zero else if (discriminant == 0) { // One real repeated root exists root1 = -b / (2 * a); printf("One real repeated root: %.2lf\n", root1); } // The discriminant is negative, so the roots are complex else { // Calculate the real and imaginary parts of the complex roots realPart = -b / (2 * a); imaginaryPart = sqrt(-discriminant) / (2 * a); printf("Complex roots: %.2lf + %.2lfi and %.2lf - %.2lfi\n", realPart, imaginaryPart, realPart, imaginaryPart); } return 0; }
What header file is needed for input and output operations in C?
include <stdio.h></stdio.h>
How do you declare a floating-point variable in C to store Fahrenheit temperature?
float fahrenheit;
How do you declare a floating-point variable in C to store Celsius temperature?
float celsius;
How do you prompt the user to enter a temperature in Fahrenheit?
printf("Enter temperature in Fahrenheit: ");
How do you read a floating-point number from the user in C?
scanf("%f", &fahrenheit);
What is the formula to convert Fahrenheit to Celsius?
Celsius = (Fahrenheit - 32) * 5 / 9;
How do you implement the Fahrenheit to Celsius conversion in C?
celsius = (fahrenheit - 32) * 5.0 / 9.0;
Why do we use 5.0 / 9.0 instead of 5 / 9 in the conversion formula?
To ensure floating-point division and avoid integer division, which would result in 0.
How do you display the converted Celsius temperature with two decimal places?
printf("%.2f Fahrenheit is equal to %.2f Celsius\n", fahrenheit, celsius);
What does return 0; indicate at the end of the main() function?
It signifies that the program ended successfully.
What is the purpose of inline comments in a C program?
They explain the functionality of each line or block of code for better understanding.
What is the purpose of scanf("%f", &fahrenheit); in the program?
It takes user input and stores the entered Fahrenheit value in the variable fahrenheit.
What happens if the user enters a non-numeric value instead of a number in scanf?
The behavior is undefined; it may cause unexpected results or program failure.
Why do we use #include <stdio.h> at the beginning of the program?</stdio.h>
It allows the use of standard input-output functions like printf and scanf.
How can you modify the program to convert multiple temperatures in a loop?
Use a while or for loop to repeatedly ask for input and perform conversion.
Write a C program to convert Fahrenheit to Celsius.
include <stdio.h></stdio.h>
int main()
{
float Fahrenheit, Celsius;
printf("Enter temperature in Fahrenheit: ");
scanf("%f", &fahrenheit); celsius = (fahrenheit - 32) * 5.0 / 9.0;
printf("%.2f Fahrenheit is equal to %.2f Celsius\n", fahrenheit, celsius);
return 0;
}
Write a C program that calculates the area and perimeter for a circle, an equilateral triangle, and a rectangle.
include <stdio.h></stdio.h>
#include <math.h>
#define PI 3.14159265358979323846
int main() {
double radius, triangleSide, rectLength, rectWidth;
double circleArea, circleCircumference;
double triangleArea, trianglePerimeter;
double rectangleArea, rectanglePerimeter;</math.h>
printf(\"Enter the radius of the circle: \");\n scanf(\"%lf\", &radius);\n circleArea = PI * radius * radius;\n circleCircumference = 2 * PI * radius;\n\n printf(\"Enter the side length of the equilateral triangle: \");\n scanf(\"%lf\", &triangleSide);\n triangleArea = (sqrt(3) / 4) * triangleSide * triangleSide;\n trianglePerimeter = 3 * triangleSide;\n\n printf(\"Enter the length of the rectangle: \");\n scanf(\"%lf\", &rectLength);\n printf(\"Enter the width of the rectangle: \");\n scanf(\"%lf\", &rectWidth);\n rectangleArea = rectLength * rectWidth;\n rectanglePerimeter = 2 * (rectLength + rectWidth);\n\n printf(\"\nCircle:\\n\");\n printf(\"Area: %.2lf\\n\", circleArea);\n printf(\"Circumference: %.2lf\\n\", circleCircumference);\n\n printf(\"\nEquilateral Triangle:\\n\");\n printf(\"Area: %.2lf\\n\", triangleArea);\n printf(\"Perimeter: %.2lf\\n\", trianglePerimeter);\n\n printf(\"\nRectangle:\\n\");\n printf(\"Area: %.2lf\\n\", rectangleArea);\n printf(\"Perimeter: %.2lf\\n\", rectanglePerimeter);\n\n return 0;\n}
What formula is used to calculate the area of a circle?
area = π * radius²
What formula is used to calculate the circumference of a circle?
circumference = 2 * π * radius
What formula is used to calculate the area of an equilateral triangle?
area = (√3 / 4) * side²
What formula is used to calculate the perimeter of an equilateral triangle?
perimeter = 3 * side
What formula is used to calculate the area of a rectangle?
area = length * width
What formula is used to calculate the perimeter of a rectangle?
perimeter = 2 * (length + width)
What input does the program ask for when calculating the circle’s properties?
The user is prompted to enter the radius of the circle.
What input does the program ask for when calculating the equilateral triangle’s properties?
The user is prompted to enter the side length of the equilateral triangle.
What input does the program ask for when calculating the rectangle’s properties?
The user is prompted to enter the length and width of the rectangle.
Which library is included to use mathematical functions like sqrt()?
include <math.h></math.h>
What constant is defined for better precision in calculations?
define PI 3.14159265358979323846
Which function is used to read user input?
scanf()
Which function is used to print the output?
printf()
What does the program do after computing all the values?
The program displays the calculated areas and perimeters of all shapes.
Explain how input and output functions operate in a C program.
The <stdio.h> header file provides the necessary declarations for standard input/output functions in C. The scanf function is used to receive formatted input from the user by reading values according to specified conversion specifiers and storing them in provided variables. Conversely, the printf function displays output by formatting values into a string using conversion specifiers and printing it to the console.</stdio.h>
What is the role of the <stdio.h> header file in C?</stdio.h>
It provides declarations for standard I/O functions such as printf and scanf, enabling the program to perform input and output operations.
How does the scanf function work in a C program?
The scanf function reads formatted input from the user based on specified conversion specifiers and stores the input into corresponding variables.
What is the purpose of conversion specifiers in scanf?
Conversion specifiers (e.g., %d for integers) tell scanf what type of data to expect and how to interpret the input correctly.
How does the printf function operate in a C program?
The printf function displays formatted output by converting values into a string based on provided conversion specifiers and printing that string to the console.
What role do conversion specifiers play in printf?
They determine the format in which values are displayed, such as %s for strings and %d for integers, ensuring the output appears as intended.
tokens, identifiers,implicit vs explicit and data types.
Tokens in C: Define what a token is and explain its role in the C compilation process. List the six types of tokens in C: keywords, identifiers, constants, strings, operators, and special symbols. For each type, provide a brief explanation along with one example (e.g., int for keywords, x for identifiers). Identifiers and Naming Rules: Explain the role of identifiers in a C program and why they are important for naming variables, functions, etc. List the rules for forming valid identifiers (e.g., starting with a letter or underscore, no spaces, avoiding reserved keywords). Provide examples of valid identifiers (such as count, _temp, num1) and examples of invalid identifiers (such as 2ndVar, int, var-name). Implicit vs. Explicit Conversion: Describe the concept of type conversion in C and explain the difference between implicit (automatic) and explicit (manual, using casts) conversion. List at least two key differences between these conversion types. Provide suitable code examples that illustrate both implicit and explicit type conversions (e.g., converting an int to a float implicitly versus using (float)intVar for explicit conversion). Data Types in C: Define what data types are in C and explain their significance in data representation and memory management. Briefly describe the basic data types in C: int, float, double, and char. For each data type, include a simple code example and mention any typical memory size details if relevant (e.g., int age = 30;, float price = 19.99;, double distance = 12345.678;, char grade = ‘A’;).
What is lexical analysis in the context of C compilation?
Lexical analysis is the first phase of the C compilation process where the source code is broken down into tokens. This helps the compiler identify the smallest meaningful elements of the code.
How do tokens contribute to syntax analysis and error detection in C?
Tokens, once identified during lexical analysis, are used in syntax analysis to build the structure of the program. This process also helps in early detection of syntax errors by ensuring all parts of the code conform to C language rules.
What is a token in C?
A token is the smallest individual element in a C program recognized by the compiler, serving as the building blocks for further compilation processes.
List the six types of tokens in C.
The six types of tokens in C are: Keywords, Identifiers, Constants, Strings, Operators, and Special Symbols.
Define keywords in C and provide an example.
Keywords are reserved words with predefined meanings in C. For example, ‘int’ is a keyword used to declare an integer variable.
Define identifiers in C and provide an example.
Identifiers are names given to variables, functions, arrays, etc. For instance, ‘x’ is an identifier used as a variable name.
Define constants in C and provide an example.
Constants are fixed values that do not change during program execution. An example is ‘3.14’ used for a floating-point value.
Define strings in C and provide an example.
“Strings are sequences of characters enclosed in double quotes. For example, "Hello
Define operators in C and provide an example.
Operators are symbols used to perform operations on variables and values. For example, the ‘+’ operator adds two numbers.
Define special symbols in C and provide an example.
Special symbols are punctuation characters with special roles in the syntax, such as ‘;’ which denotes the end of a statement.
Why are identifiers crucial in a C program?
Identifiers are essential because they provide meaningful names for variables, functions, and other elements, enhancing code readability, maintainability, and proper linking during compilation.
What are the naming rules for identifiers in C?
Valid identifiers must start with a letter (a–z, A–Z) or an underscore (_), can include letters, digits, and underscores after the first character, must not contain spaces or special characters (except underscore), and cannot be reserved keywords.
Provide an example of a valid identifier and explain why it’s valid.
Example: ‘count’ is valid because it starts with a letter and contains only letters with no spaces or special characters.
Provide an example of an invalid identifier and explain why it’s invalid.
Example: ‘2ndVar’ is invalid because it begins with a digit, violating the naming rules for identifiers.
How does using a reserved keyword as an identifier cause issues?
Using a reserved keyword as an identifier causes compilation errors because reserved keywords have predefined meanings in C, leading to conflicts in the code.
What is type conversion in C?
Type conversion in C is the process of converting a value from one data type to another to ensure that operations and expressions between different types work correctly.
What is implicit type conversion in C?
Implicit type conversion is an automatic conversion performed by the compiler when mixing different data types, such as converting an int to a float in an arithmetic expression.
Provide a code example of implicit type conversion.
Example:\n\nint a = 10;\nfloat b = 5.5;\nfloat result = a + b; // ‘a’ is automatically converted to float, resulting in 15.5
What is explicit type conversion in C?
Explicit type conversion (casting) is a manual conversion performed by the programmer using a cast operator to convert a value from one data type to another.
Provide a code example of explicit type conversion.
Example:\n\nfloat a = 10.75;\nint b = (int)a; // explicitly converts ‘a’ to an int, resulting in 10 (decimal part is truncated)
List two key differences between implicit and explicit type conversion.
- Implicit conversion is performed automatically by the compiler, whereas explicit conversion requires a manual cast by the programmer.\n2. Implicit conversion can lead to unintended data loss, while explicit conversion allows the programmer to control and be aware of potential data loss.
Why are data types important in C programming?
Data types in C are important because they determine the kind of data a variable can hold, how data is represented, and how much memory is allocated. This affects both program behavior and resource management.
List the basic data types in C.
The basic data types in C are int, float, double, and char.
Describe the ‘int’ data type in C with an example and typical memory size.
The ‘int’ data type stores integer values. Example: ‘int age = 30;’ typically occupies 4 bytes of memory.
Describe the ‘float’ data type in C with an example and typical memory size.
The ‘float’ data type stores single-precision floating-point numbers. Example: ‘float price = 19.99;’ typically occupies 4 bytes of memory.
Describe the ‘double’ data type in C with an example and typical memory size.
The ‘double’ data type stores double-precision floating-point numbers. Example: ‘double distance = 12345.678;’ typically occupies 8 bytes of memory.
Describe the ‘char’ data type in C with an example and typical memory size.
The ‘char’ data type stores a single character. Example: ‘char grade = ‘A’;’ typically occupies 1 byte of memory.
How does memory size influence the choice of data types in C?
Memory size is important because it determines how much data can be stored and processed efficiently. Choosing the appropriate data type ensures optimal memory usage and program performance.