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

Module 2 Important Questions

The document covers various programming concepts in C, including the use of goto statements, the importance of operator precedence, and the differences between control flow statements like break and continue. It also provides examples of C programs for reversing a number, reading input, and calculating factorials, along with explanations of data types, operators, and escape sequences. Additionally, it discusses type casting, variable naming rules, and the basic structure of a C program.

Uploaded by

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

Module 2 Important Questions

The document covers various programming concepts in C, including the use of goto statements, the importance of operator precedence, and the differences between control flow statements like break and continue. It also provides examples of C programs for reversing a number, reading input, and calculating factorials, along with explanations of data types, operators, and escape sequences. Additionally, it discusses type casting, variable naming rules, and the basic structure of a C program.

Uploaded by

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

MODULE -2

PROGRAM BASICS

⭐1. Is it advisable to use goto statements in a C program? Justify your answer. (3 marks)

Ans: Goto statements in a C program is generally discouraged due to:


Readability and Maintenance: goto statements can make code harder to understand and maintain, as they
allow for arbitrary jumps in program flow, leading to confusion.
Structured Programming: Modern programming principles emphasize structured control flow using loops
and conditionals, which promote clear code organization. goto undermines this structure.
Debugging and Error Handling: Debugging becomes difficult with goto, as it can lead to unpredictable
program flow. Error handling and resource management can also be problematic when using goto.
In most cases, it's better to use structured control constructs for improved code clarity and maintainability.

⭐⭐2. Write a C program to read a Natural Number through keyboard and to display the reverse of the
given number. For example, if “3214567” is given as input, the output to be shown is “7654123”.(3 marks to
7 marks)
#include <stdio.h>
int main() {
int num, digit, reverse = 0;
printf("Enter a natural number: ");
scanf("%u", &num);
// Reverse the number
while (num > 0)
{
digit = num % 10;
reverse = reverse * 10 + digit;
num =num / 10;
}
printf("Reverse of the given number: %u\n", reverse);
return 0;
}

3. What is the importance of precedence and associativity? Write the table for operator precedence .(7
marks)

Ans: Precedence and associativity in C determine the order in which operators are evaluated, ensuring
correct expression evaluation and avoiding ambiguity.
⭐4. Differentiate between 'break' and 'continue' statements.(3 marks)

⭐5. Differentiate between while and do-while loops using an example.(3 marks)
⭐6. What is the difference between equality and assignment operator? (3 marks)
Ans: The equality operator (==) and the assignment operator (=) serve distinct purposes in C:
Equality Operator (==):
The equality operator is used to compare two values for equality.
It returns 1 (true) if the values are equal, and 0 (false) if they are not.
It is commonly used in conditional statements and expressions to make decisions based on whether two
values are equal.
Assignment Operator (=):
The assignment operator is used to assign a value to a variable.
It assigns the value on its right-hand side to the variable on its left-hand side.
It does not compare values; instead, it performs an action of assigning a value.

7. What are the rules when naming variables(identifiers) in C? (3 marks)


Ans:

⭐8. Explain how one can use the builtin function in C, scanf to read values of different data types. Also
explain using examples how one can use the builtin function in C, printf for text formatting. (7 marks)

Ans: *scanf() for Reading Different Data Types:*


In C, the `scanf()` function is used to read input from the user. To read values of different data types, we
need to provide appropriate format specifiers. Use of `scanf()` for different data types:
1. Reading integers:
int num;
scanf("%d", &num);
2. Reading floating-point numbers:
float floatNum;
scanf("%f", &floatNum);
3. Reading characters:
char character;
scanf(" %c", &character); // Note the space before %c to consume any newline character left in the input
buffer.
4. Reading strings:
char str[50];
scanf("%s", str);

*printf() for Text Formatting:*


In C, the `printf()` function is used to display output. It allows text formatting using format specifiers. Use
`printf()` for text formatting:
1. Printing integers:
int num = 42;
printf("The number is: %d\n", num);
2. Printing floating-point numbers:
float floatNum = 3.14159;
printf("The value of pi is: %f\n", floatNum);
3. Printing characters:
char character = 'A';
printf("The character is: %c\n", character);
4. Printing strings:
char name[] = "John";
printf("Hello, %s!\n", name);
5. Formatting width and precision:
float price = 24.99;
printf("The price is: %.2f\n", price); // Displays the float with 2 decimal places.

⭐⭐9. With suitable examples, explain various operators in C. (7 marks onwards)


Ans: Various operators in C are:
1. **Arithmetic Operators:**
- Addition (`+`): Adds two values.
- Subtraction (`-`): Subtracts the second value from the first.
- Multiplication (`*`): Multiplies two values.
- Division (`/`): Divides the first value by the second.
- Modulus (`%`): Returns the remainder of division.
Example: `int result = 10 + 5;`

2. **Relational Operators:**
- Equal to (`==`): Checks if two values are equal.
- Not equal to (`!=`): Checks if two values are not equal.
- Greater than (`>`): Checks if the first value is greater than the second.
- Less than (`<`): Checks if the first value is less than the second.
- Greater than or equal to (`>=`): Checks if the first value is greater than or equal to the second.
- Less than or equal to (`<=`): Checks if the first value is less than or equal to the second.
Example: `if (x > y) { /* do something */ }`

3. **Logical Operators:**
- Logical AND (`&&`): Returns true if both operands are true.
- Logical OR (`||`): Returns true if at least one operand is true.
- Logical NOT (`!`): Inverts the value of an operand.
Example: `if (a && b) { /* do something */ }`

4. **Assignment Operators:**
- Assignment (`=`): Assigns the value on the right to the variable on the left.
- Addition assignment (`+=`): Adds the right value to the left and assigns the result to the left.
- Subtraction assignment (`-=`): Subtracts the right value from the left and assigns the result to the left.
- Multiplication assignment (`*=`): Multiplies the left by the right and assigns the result to the left.
- Division assignment (`/=`): Divides the left by the right and assigns the result to the left.
Example: `x += 10;`

5. **Increment and Decrement Operators:**


- Increment (`++`): Increases the value of a variable by 1.
- Decrement (`--`): Decreases the value of a variable by 1.
Example: `count++;`

6. **Conditional (Ternary) Operator:**


- Ternary (`condition ? true_expression : false_expression`): Evaluates a condition and returns one of two
expressions based on the result.
Example: `max = (a > b) ? a : b;`

7. **Bitwise Operators:**
- Bitwise AND (`&`): Performs bitwise AND operation.

- Bitwise OR (`|`): Performs bitwise OR operation.


- Bitwise XOR (`^`): Performs bitwise exclusive OR operation.
- Bitwise NOT (`~`): Flips the bits of the operand.
- Left shift (`<<`): Shifts the bits of the left operand to the left by the number of positions specified by the
right operand.
- Right shift (`>>`): Shifts the bits of the left operand to the right by the number of positions specified by the
right operand.
Example: `result = a & b;`

10. Explain different escape sequences in C with example. (7 marks )


Ans: Escape sequences in C are special combinations of characters that represent non-printable or special
characters within strings or character literals. They are used to provide functionality like newlines, tabs, and
other control characters. Here are some common escape sequences along with examples:
1. `\n` - Newline:** Moves the cursor to the beginning of the next line.
Example:
printf("Hello\nWorld");
// Output:
Hello
World

2. `\t` - Tab:** Inserts a horizontal tab.


Example:
printf("Name:\tJohn");
// Output:
Name: John

3. `\\` - Backslash:** Inserts a literal backslash.


Example:
printf("This is a backslash: \\");
// Output:
This is a backslash: \

4. `\"` - Double Quote:** Inserts a double quote character within a string.


Example:
printf("She said, \"Hello!\"");
// Output:
She said, "Hello!"

5. `\'` - Single Quote:** Inserts a single quote character within a character literal.
Example:
char myChar = '\'';

6. `\r` - Carriage Return:** Moves the cursor to the beginning of the current line.
Example:
printf("Hello\rWorld");
// Output:
World

7. `\b` - Backspace:** Moves the cursor back one space.


Example:
printf("Hello\bWorld");
// Output:
HellWorld
8. `\a` - Alert (Bell):** Produces an audible or visible alert, such as a beep.
Example:
printf("Beep: \a");
// Produces an audible or visible alert

9. `\0` - Null Character:** Represents the null terminator character.


Example:
char str[] = "Hello\0World";
// "Hello" will be considered the content of the string

10. `\v` - Vertical Tab:** Inserts a vertical tab.


Example:
printf("Line1\vLine2");
// Output:
Line1
Line2
These escape sequences are useful for representing characters that are not easily typable or printable
directly in strings or character literals. They enhance the flexibility and formatting capabilities of C strings and
characters.

⭐⭐11. Explain different data types supported by C language with their memory requirements.(7 marks)
Ans: Primary Data Types:
int: Represents integer values, typically 4 bytes.

char: Represents a single character, 1 byte.


float: Represents single-precision floating-point numbers, 4 bytes.
double: Represents double-precision floating-point numbers, 8 bytes.
User-Defined Data Types:
struct: Represents a composite data type combining multiple variables with different data types.
Size depends on the members' sizes and alignment.
Derived Data Types:
pointer: Represents a memory address. Size depends on data type pointed to.
array: Represents a collection of elements of the same data type.
Size depends on the element size and the number of elements.
enum: Represents a set of named integer constants. Typically 4 bytes, but it depends on the range of values.
Additional Types:
long int: Represents larger integer values than int, typically 4 bytes.
long double: Represents higher precision floating-point numbers than double, often 8 bytes.
short int: Represents smaller integer values than int, 2 bytes.
unsigned int: Represents non-negative integer values, typically 4 bytes.
unsigned char: Represents non-negative character values, 1 byte.
unsigned long int: Represents larger non-negative integer values, typically 4 bytes.
These sizes are based on a typical 32-bit system. On a 64-bit system, the sizes may be different. Sizes can
also vary depending on the compiler and system architecture.

12. Explain with example the basic structure of a C program. (7 marks)


Ans:
#include <stdio.h> // Include the standard I/O library
int main() { // The main function, where the program execution begins

printf("Hello, World!\n"); // Print the message to the console


return 0; // Return 0 to indicate successful program execution
}

1. **Preprocessor Directives (`#include`)**: The `#include` directive is used to include header files that
provide declarations and definitions for functions and objects used in the program. In this example, we
include the `<stdio.h>` header, which contains functions for input and output operations.

2. **Function Declarations (`int main()`)**: Every C program must have a `main` function. This is the entry
point of the program, where execution begins. The `int` before `main` specifies the return type of the
function, which in this case is an integer. The parentheses `()` indicate that `main` doesn't take any
parameters.

3. **Function Body (`{ ... }`)**: The body of the `main` function is enclosed within curly braces. This is where
we write the actual code that the program will execute.

4. **Statements (e.g., `printf(...)`)**: Inside the function body, you write statements that perform actions. In
this example, the `printf` function is used to print the "Hello, World!" message to the console. The `\n`
represents a newline character to move to the next line after printing.
5. **Return Statement (`return 0;`)**: The `return` statement is used to indicate the end of the `main`
function. It also provides an exit status to the operating system. By convention, returning `0` typically
indicates successful execution, while other values indicate errors.
So, the basic structure of a C program includes preprocessor directives, function declarations, function
bodies, statements, and return statements.

13. What is type casting? Name the inbuilt typecasting functions available in C language. What is the
difference between type casting and type conversion? (7 marks)
Ans: Type Casting: In typing casting, a data type is converted into another data type by the programmer
using the casting operator during the program design. In typing casting, the destination data type may be
smaller than the source data type when converting the data type to another data type, that’s why it is also
called narrowing conversion.
Eg: double pi = 3.14159265;
int approximatePi = (int)pi; // Explicitly cast double to int
In C programming, there are 5 built-in type casting functions.
 atof(): This function is used for converting the string data type into a float data type.
 atbol(): This function is used for converting the string data type into a long data type.
 Itoa(): This function is used to convert the long data type into the string data type.
 itoba(): This function is used to convert an int data type into a string data type.
 atoi(): This data type is used to convert the string data type into an int data type.
14. Differentiate between prefix and postfix operators in C. (3 marks and above)
Ans: 1. **Prefix Operators**:
Prefix operators are applied before the variable, and they modify the variable's value and then return the
modified value.
Eg:
- **Increment (Prefix++)**: The `++` operator is used to increase the value of a variable by 1 before any
other operation is performed.
Example:
int x = 5;
int y = ++x; // y becomes 6, x becomes 6
2. **Postfix Operators**:
Postfix operators are applied after the variable, and they modify the variable's value but return the original
value before the modification.
Eg:
- **Decrement (Postfix--)**: The `--` operator is used to decrease the value of a variable by 1 after other
operations have been performed.
Example:
int m = 15;
int n = m--; // n becomes 15, m becomes 14
In summary:
- Prefix operators modify the variable's value before returning the modified value.
- Postfix operators modify the variable's value after returning the original value.

15. Differentiate between entry controlled and exit controlled loop. (3 marks).
16. Write a C program to read an English Alphabet through keyboard and display whether the given Alphabet
is in upper case or lower case. (7 marks)

Ans: #include <stdio.h>


int main() {
char alphabet;
printf("Enter an English alphabet: ");
scanf("%c", &alphabet);
if (alphabet >= 'a' && alphabet <= 'z')
{
printf("The given alphabet is in lower case.\n");
}
else if (alphabet >= 'A' && alphabet <= 'Z')
{
printf("The given alphabet is in upper case.\n");
}
else
{
printf("Invalid input. Please enter a valid English alphabet.\n");
}
return 0;
}

⭐17. Write a C program to find sum of first and last digits.(3 marks to 7 marks)
Ans: #include <stdio.h>
#include<math.h>
using namespace std;
int main()
{
int num,ld,count=0,fd,sum,power,temp;
printf("Enter the number\n");
scanf("%d",&num);
ld=num%10; //last digit
temp=num;
while(num!=0)
{
count++;
num=num/10;
}
power=pow(10,count-1);
fd=temp/power; //first digit
sum=fd+ld;
printf("sum is %d",sum);
}

18. Write a C program to find the factorial of a number.(3 marks to 7 marks)


Ans: #include <stdio.h>
int main() {
int n;
int factorial = 1;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n < 0) {
printf("Factorial is not defined for negative numbers.\n");
}
else {
for (int i = 1; i <= n; ++i) {
factorial *= i;
}
printf("Factorial of %d = %llu\n", n, factorial);
}
return 0;
}

19. Write a C program to find sum of digits of a given number.(3 marks to 7 marks)
Ans: #include <stdio.h>
int main() {
int number, originalNumber, digit, sum = 0;
printf("Enter a number: ");
scanf("%d", &number);
originalNumber = number;
while (number > 0) {
digit = number % 10;
sum += digit;
number /= 10;
}
printf("Sum of digits of %d = %d\n", originalNumber, sum);
return 0;
}

You might also like