Unit 2 Question Bank Answers
Unit 2 Question Bank Answers
1. What is a C Token?
A C token is the smallest unit of a C program. It includes:
c
Copy code
condition ? expression1 : expression2;
Example:
c
Copy code
int x = (a > b) ? a : b; // Assigns the greater value to x
Example:
c
Copy code
float x = 10.75;
int y = (int)x; // Explicit conversion, y = 10
Without explicit conversion, unwanted behavior may occur.
Here are brief answers and C program examples for each question:
---
Structure of a C Program:
// Function Definition
int main() {
// Code Statements
printf("Hello, World!");
return 0;
}
Explanation:
#include <stdio.h> – Header file for standard input and output functions.
---
Example Program:
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three numbers: ");
scanf("%d%d%d", &a, &b, &c);
return 0;
}
---
1. Arithmetic Operators:
+, -, *, /, % Example:
int a = 5, b = 2;
printf("%d", a + b); // Outputs 7
2. Relational Operators:
3. Conditional Operators:
Example Program:
#include <stdio.h>
int main() {
int n, reverse = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
while(n != 0) {
reverse = reverse * 10 + n % 10;
n /= 10;
}
---
Definition:
Rules:
Cannot be a keyword.
Case-sensitive.
Example:
int x = 10;
---
#include <stdio.h>
int main() {
int n, fact = 1;
printf("Enter a number: ");
scanf("%d", &n);
---
4A. Explain the various input and output statements in C with examples.
Input:
int x;
scanf("%d", &x);
Output:
printf("%d", x);
---
Example Program:
#include <stdio.h>
int main() {
int n, i = 1;
printf("Enter a number: ");
scanf("%d", &n);
while(i <= 10) {
printf("%d x %d = %d\n", n, i, n * i);
i++;
}
return 0;
}
---
Example:
// while loop
while(condition) {
// code
}
// do-while loop
do {
// code
} while(condition);
---
Example Program:
#include <stdio.h>
int main() {
int n, i, isPrime = 1;
printf("Enter a number: ");
scanf("%d", &n);
return 0;
}
---
Syntax:
Example:
---
6B. Write a C program to print all even numbers between 1 and 100.
Example Program:
#include <stdio.h>
int main() {
for(int i = 2; i <= 100; i += 2) {
printf("%d ", i);
}
return 0;
}
---
int x = 10;
float y = 3.5;
char c = 'A';
---
Example Program:
#include <stdio.h>
int main() {
int n, count = 0;
printf("Enter a number: ");
scanf("%d", &n);
while(n != 0) {
n /= 10;
count++;
}
---
---
Example:
switch(operator) {
case '+': result = a + b; break;
case '-': result = a - b; break;
}
---
---
---