0% found this document useful (0 votes)
72 views62 pages

U24cs101-Programming in C - QB - Answers

The document provides answers to 23 questions related to programming in C, covering topics such as variables, type conversion, operators, preprocessor directives, input/output functions, algorithms, and control structures. Each answer includes definitions, examples, and explanations of concepts like arithmetic, relational, and logical operators, as well as the significance of keywords and flowchart symbols. Additionally, it includes example programs demonstrating the use of various operators and algorithms.

Uploaded by

dharaneesh2007k
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)
72 views62 pages

U24cs101-Programming in C - QB - Answers

The document provides answers to 23 questions related to programming in C, covering topics such as variables, type conversion, operators, preprocessor directives, input/output functions, algorithms, and control structures. Each answer includes definitions, examples, and explanations of concepts like arithmetic, relational, and logical operators, as well as the significance of keywords and flowchart symbols. Additionally, it includes example programs demonstrating the use of various operators and algorithms.

Uploaded by

dharaneesh2007k
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/ 62

Programming in C — Part A (First 23 Questions) — Answers

(2-mark style)

Q1. What are variables? how to declare a variable.


Answer:
Variables are named memory locations used to store data. They have a type, name, and an optional initial value.
• Declaration syntax: ; e.g., int count;
• Initialization: int x = 10; (assigns initial value)
• Memory representation: each variable occupies bytes depending on its data type.
• Identifiers (names) must follow C naming rules and cannot be keywords.

Memory
Name: count
Type: int Val: 10

Q2. Define implicit type conversion


Answer:
Implicit type conversion (coercion) is when the compiler automatically converts one data type to another during
expression evaluation.
• Happens according to conversion hierarchy (e.g., int -> float -> double).
• May cause precision changes or truncation for narrowing conversions.
• Usual arithmetic conversions ensure operands share a common type.
• Use casts to override implicit conversions: (int)3.7 -> 3.

Type conversion examples

int float double

int -> float -> double

Q3. What are the various types of operators?


Answer:
Operators in C let you perform computations and manipulate data; they are grouped by their function.
• Arithmetic: +, -, *, /, % (for integer remainder).
• Relational: ==, !=, >, <, >=, <= — used in decision making.
• Logical: &&, ||, ! — combine boolean expressions.
• Bitwise, assignment, increment/decrement and conditional (?:) are other categories.

Operator categories

Arithmetic + Relational Logical Bitwise/Assign


Q4. What is the use of preprocessor directive?
Answer:
Preprocessor directives begin with # and are processed before compilation to handle inclusions, macros, and
conditional compilation.
• Common directives: #include, #define, #ifdef/#ifndef, #undef, #pragma.
• #include inserts headers; #define creates macros or symbolic constants.
• Conditional directives allow compiling code conditionally for portability.
• They are not C statements — handled by the preprocessor.

Compile stages
Preprocessor Compiler Linker

Q5. What are the input functions and output functions in C


Answer:
C provides I/O functions in stdio.h; printf and scanf are the primary formatted output and input functions.
• printf(format, ...) prints formatted output; use format specifiers like %d, %f, %c, %s.
• scanf(format, &vars;) reads formatted input; beware of whitespace and buffer overflows.
• Character I/O: getchar(), putchar(); String I/O: gets (unsafe) / fgets, puts.
• Always validate return values and prefer safer alternatives (e.g., fgets over gets).

I/O flow

Keyboard scanf() printf()

Q6. Write a C program to print Fibonacci series


Answer:
Fibonacci series starts with two numbers (commonly 0 and 1) and each subsequent number is the sum of the previous
two.
• Iterative approach: initialize a=0, b=1; loop n times printing a and updating a=b, b=a+b.
• Recursive approach is simple but has exponential time unless optimized (memoization).
• Time complexity (iterative) is O(n); space O(1) for iterative solution.
• Edge cases: handle n=0 or n=1 appropriately.

Fibonacci (iterative)

Init a=0,b=1 Print a; update

Q7. List some pre-processor directives


Answer:
Some commonly used preprocessor directives in C are used for header inclusion, macro definition, and conditional
compilation.
• #include — include header files.
• #define NAME value — define constants or macros.
• #ifdef / #ifndef / #endif — conditional compilation blocks.
• #undef, #pragma are other useful directives.

Examples:

#include
#define
#ifdef/#ifndef
#undef / #pragma

Q8. What are the importance of keyword in C


Answer:
Keywords are reserved words with special meaning in C's syntax; they cannot be used as identifiers.
• Examples: int, return, if, else, while, for, switch, break, continue.
• They define language constructs and control program flow.
• Using a keyword as an identifier causes compilation errors.
• C is case-sensitive: 'Int' is not the same as 'int'.

Keywords sample
int return if else
for while switch break

Q9. Give an Example of ternary operator.


Answer:
The ternary operator is a concise conditional expression: condition ? expr_if_true : expr_if_false.
• Syntax: result = (a > b) ? a : b; — returns either a or b based on the condition.
• It's an expression (returns a value), often used for short decisions.
• Equivalent to a short if-else; avoid overusing for complex logic.
• Works with any operands provided types are compatible.

Ternary example

(a>b)?a:b

Q10. Define an algorithm. What are its characteristics?


Answer:
An algorithm is a finite, well-defined sequence of instructions to solve a problem.
• Characteristics: finiteness, definiteness, input/output, effectiveness.
• Should terminate after a finite number of steps producing the correct output.
• Algorithms can be analyzed for time and space complexity.
• Expressed as steps, flowcharts, or pseudocode.
Algorithm traits
Finiteness Definiteness Input/Output Effectiveness

Q11. List different data types available in C


Answer:
C offers basic (primitive) data types and derived/user-defined types used to represent values.
• Primary types: int, char, float, double (varying sizes by implementation).
• Derived types: arrays, pointers, functions, structures, unions.
• Qualifiers: signed/unsigned, short/long alter size and sign behavior.
• Use sizeof() to determine storage size on a platform.

Type categories
int char float double

Q12. Write a C program to find factorial of the number using iteration.


Answer:
Factorial of n (n!) is the product of all positive integers up to n; commonly computed iteratively or recursively.
• Iterative: use a loop multiplying an accumulator from 1 to n.
• Recursive: fact(n) = n * fact(n-1) with base case fact(0)=1.
• Watch for integer overflow for large n; use long long or big integers if needed.
• Time complexity is O(n); recursion uses O(n) stack depth.

Factorial (iterative)

Init fact=1, i=1 fact *= i; i++

Q13. Differentiate between flowchart and pseudocode.


Answer:
Flowcharts are graphical representations with symbols and arrows; pseudocode is a textual, structured description of
algorithms.
• Flowcharts use shapes (oval start/end, rectangle process, diamond decision).
• Pseudocode reads like structured English and is easier to modify quickly.
• Flowcharts excel at visualizing flow; pseudocode is closer to implementation logic.
• Both are used to design and communicate algorithms before coding.
Flowchart vs Pseudocode

Flowchart Pseudocode

Q14. Define Algorithm. Write an algorithm to find the area of a circle


Answer:
To compute the area of a circle: area = π * r * r. An algorithm takes radius as input and outputs the area.
• Input radius r; use float/double for fractional radii.
• Compute area using M_PI or 3.14159: area = pi * r * r.
• Validate r >= 0; handle units consistently.
• Complexity: O(1) — constant time computation.

Area = πr²

Q15. Mention the difference between while and do while


Answer:
while and do-while are looping constructs; while tests the condition before executing the loop body, do-while tests
after.
• while: entry-controlled — body may not execute if condition false initially.
• do-while: exit-controlled — body executes at least once before checking condition.
• Syntax differs: do { ... } while(condition); vs while(condition) { ... }.
• Choose based on whether at least one execution is required.

while vs do-while
while(cond) { body } do { body } while(cond);

Q16. Describe the order of precedence of operators.


Answer:
Operator precedence determines the order in which parts of an expression are evaluated; higher precedence
operators are applied first.
• Example: *, / have higher precedence than +, -; parentheses () override precedence.
• Unary operators (like ++, --, unary +/-, !) have higher precedence.
• Associativity (left-to-right or right-to-left) resolves ties at the same precedence level.
• Use parentheses to make intent explicit and avoid unexpected behavior.
Sample precedence
Highest -> Lowest
(), ++, --
*, /, %
+, -

Q17. Evaluate the following C expression: A = 6+10**2/50-2+4


Answer:
The expression contains '**' which is not a C operator. We explain both likely interpretations: exponentiation or
multiplication.
• In standard C, '**' is invalid; to raise power use pow(10,2) from .
• If '**' meant exponent: 10**2 = 100 => A = 6 + 100/50 - 2 + 4 = 10.
• If it was intended as multiplication (10*2): A = 6 + (10*2)/50 -2 +4 = 8 (integer division yields 0).
• Clarify operator intent; prefer parentheses and correct operators in C.

Expression note
'**' is NOT a C operator
Use pow() for exponent or '*' for multiply

Q18. Differentiate between entry controlled and exit controlled loop


Answer:
Entry-controlled loops test the condition before the loop body (e.g., while, for); exit-controlled loops test after the body
(do-while).
• Entry-controlled: may execute zero times if condition false (while/for).
• Exit-controlled: executes body at least once (do-while).
• Use entry-controlled when pre-condition is required; use exit-controlled when post-check needed.

Loop control types


Entry-controlled: while/for Exit-controlled: do-while

Q19. Provide the significance of break statement in loops.


Answer:
The break statement immediately terminates the nearest enclosing loop or switch, transferring control to the statement
following it.
• Used to exit loops early when a condition is met.
• In switch statements, break prevents fall-through to the next case.
• Helps improve efficiency by avoiding unnecessary iterations.
• Use judiciously; excessive use can reduce readability.
break usage
Use 'break;' to exit loop/switch

Q20. Analyze Increment and Decrement Operators with an example.


Answer:
Increment (++) and decrement (--) operators increase or decrease a variable's value by one; they exist in prefix and
postfix forms.
• Prefix (++i) increments before the value is used; postfix (i++) increments after the value is used.
• Example: int i=5; int a = ++i; -> a=6, i=6; int b = i++; -> b=6, i=7.
• They can be used in expressions but watch side effects and sequence points.
• Available for integer types; for pointers they move the pointer by element size.

++ and -- examples
i = 5; a = ++i; -> a=6,i=6
i = 5; b = i++; -> b=5,i=6

Q21. Write pseudocode to find the largest of three numbers.


Answer:
Pseudocode gives a clear, language-agnostic sequence to find the largest of three numbers using comparisons.
• Compare first two numbers, keep the larger in a variable 'max'.
• Compare 'max' with the third number and update if needed.
• Finally output 'max' as the largest number.
• Edge cases: equal values — algorithm still yields a correct maximum.

Pseudocode outline
if a>b then max=a else max=b; if c>max then max=c; print max;

Q22. Construct a simple algorithm to check if a number is positive, negative, or zero.


Answer:
A simple algorithm checks sign by comparing the number with zero and branches accordingly.
• If n > 0 => positive; if n < 0 => negative; else zero.
• Implement using if-else-if ladder in C: if(n>0) ... else if(n<0) ... else ...
• Consider input validation if non-numeric input possible.
• This is O(1) time — constant-time decision.
Sign check
if (n>0) positive; else if (n<0) negative; else zero;

Q23. List the symbols used in a flowchart and their meanings.


Answer:
Flowchart symbols are standardized shapes representing operations, decisions, inputs/outputs, and flow.
• Oval: Start/End. Rectangle: Process/Instruction. Diamond: Decision (yes/no).
• Parallelogram: Input/Output. Arrow: Flow line indicating control direction.
• Connector/circle: Connects different parts of the flowchart or indicates jump.
• Use clear labels inside symbols to convey the operation precisely.

Common flowchart symbols


Process Decision
PART-B

1)Explain different types of operators in detail.with


example program.

In C language, operators are special symbols used to perform operations on variables and
values.

They are classified into the following types:

Arithmetic Operators

Used to perform basic mathematical operations.

 + (Addition)

 - (Subtraction)

 * (Multiplication)

 / (Division → quotient)

 % (Modulus → remainder)

Example:

#include <stdio.h>

int main() {

int a = 10, b = 3;

printf("a + b = %d\n", a + b);

printf("a - b = %d\n", a - b);

printf("a * b = %d\n", a * b);

printf("a / b = %d\n", a / b);

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

return 0;

2. Relational Operators

Used to compare two values. Result is true (1) or false (0).


 == (Equal to)

 != (Not equal to)

 > (Greater than)

 < (Less than)

 >= (Greater than or equal to)

 <= (Less than or equal to)

Example:

#include <stdio.h>

int main() {

int x = 5, y = 8;

printf("x == y: %d\n", x == y);

printf("x != y: %d\n", x != y);

printf("x > y : %d\n", x > y);

printf("x < y : %d\n", x < y);

printf("x >= y: %d\n", x >= y);

printf("x <= y: %d\n", x <= y);

return 0;

3. Logical Operators

Used to combine multiple conditions.

 && (Logical AND → true if both are true)

 || (Logical OR → true if at least one is true)

 ! (Logical NOT → inverts the result)

Example:

#include <stdio.h>

int main() {

int a = 5, b = 10;

printf("(a > 0 && b > 0) = %d\n", (a > 0 && b > 0));

printf("(a > 0 || b < 0) = %d\n", (a > 0 || b < 0));

printf("!(a > 0) = %d\n", !(a > 0));


return 0;

4. Assignment Operators

Used to assign values to variables.

 = (Simple assignment)

 += (Add and assign)

 -= (Subtract and assign)

 *= (Multiply and assign)

 /= (Divide and assign)

 %= (Modulus and assign)

Example:

#include <stdio.h>

int main() {

int x = 10;

x += 5; // x = x + 5

printf("x after += 5: %d\n", x);

x -= 3; // x = x - 3

printf("x after -= 3: %d\n", x);

x *= 2; // x = x * 2

printf("x after *= 2: %d\n", x);

x /= 4; // x = x / 4

printf("x after /= 4: %d\n", x);

x %= 3; // x = x % 3

printf("x after %%= 3: %d\n", x);

return 0;

5. Increment and Decrement Operators

 ++ (Increment by 1)
 -- (Decrement by 1)

They can be pre (before variable) or post (after variable).

Example:

#include <stdio.h>

int main() {

int a = 5;

printf("a++ = %d\n", a++); // Post-increment

printf("After a++: %d\n", a);

printf("++a = %d\n", ++a); // Pre-increment

return 0;

6. Bitwise Operators

Work at the binary (bit) level.

 & (Bitwise AND)

 | (Bitwise OR)

 ^ (Bitwise XOR)

 ~ (Bitwise NOT → 1’s complement)

 << (Left shift)

 >> (Right shift)

Example:

#include <stdio.h>

int main() {

int a = 5, b = 3;

printf("a & b = %d\n", a & b);

printf("a | b = %d\n", a | b);

printf("a ^ b = %d\n", a ^ b);

printf("~a = %d\n", ~a);

printf("a << 1 = %d\n", a << 1);

printf("a >> 1 = %d\n", a >> 1);

return 0;
}

7. Conditional (Ternary) Operator

Shorthand for if-else.


condition ? value_if_true : value_if_false;

Example:

#include <stdio.h>

int main() {

int a = 10, b = 20;

int max = (a > b) ? a : b;

printf("Maximum = %d\n", max);

return 0;

8. Special Operators

 sizeof → returns the size of a data type/variable in bytes

 Comma (,) → separates multiple expressions

 Pointer operators:

o & (Address of)

o * (Value at address / dereference)

Example:

#include <stdio.h>

int main() {

int x = 10, y = 20;

printf("Size of int: %lu\n", sizeof(int));

int z = (x++, y++); // comma operator

printf("z = %d, x = %d, y = %d\n", z, x, y);

int *ptr = &x; // pointer operator

printf("Address of x = %p, Value of x using ptr = %d\n", ptr, *ptr);

return 0;

}
2) Basic (Fundamental) Data Types in C
These are the primitive data types provided by C. They are the building blocks for all programs.

Characteristics:

 They occupy a fixed amount of memory (depends on system/architecture).

 Used for storing standard types of values like integers, floating point numbers,
characters, etc.

 Can be modified with type modifiers (short, long, signed, unsigned) to change their
range.

Types:

1. int (Integer)

o Stores whole numbers without decimals.

o Memory: usually 2 bytes (16-bit compilers) or 4 bytes (32/64-bit compilers).

o Variants: short int, long int, unsigned int.

2. int age = 21;

3. float (Floating-point number)

o Stores decimal values with single precision.

o Memory: 4 bytes.

o Precision: about 6 decimal places.

4. float price = 123.45;

5. double (Double precision floating point)

o Similar to float but with higher precision.

o Memory: 8 bytes.

o Precision: about 15–16 decimal places.

6. double pi = 3.141592653589;

7. char (Character)

o Stores a single character.

o Memory: 1 byte.

o Internally stored as ASCII code.


o Variants: unsigned char, signed char.

8. char grade = 'A';

9. void

o Represents no value.

o Mostly used for functions that do not return anything.

10. void greet() { printf("Hello!"); }

2. User-Defined Data Types in C

C allows programmers to create their own data types, which increases readability, reusability,
and flexibility.

Types:

1. typedef (Type Definition)

o Provides a new name (alias) for an existing data type.

o Increases readability in complex programs.

2. typedef unsigned int UINT;

3. UINT count = 100; // same as unsigned int

4. enum (Enumeration)

o Used to define a set of named integer constants.

o By default, values start from 0 and increase by 1.

o Makes code easier to understand compared to raw numbers.

5. enum Days { MON, TUE, WED, THU, FRI, SAT, SUN };

6. enum Days today = FRI; // value = 4

7. struct (Structure)

o Groups di erent types of variables under one unit.

o Each member has separate memory allocation.

o Useful for representing real-world entities (student, employee, etc.).

8. struct Student {

9. int roll;

10. char name[20];

11. float marks;

12. };
13. struct Student s1 = {101, "Arun", 89.5};

14. union

o Similar to structure but all members share the same memory location.

o Saves memory but only one member can hold a value at a time.

o Useful in memory-constrained applications like embedded systems.

15. union Data {

16. int i;

17. float f;

18. char ch;

19. };

20. union Data d1;

d1.i = 25; // same memory used for f and ch

3) Describe various input and output statements in


detail.

In C, input statements are used to take values from the user, and output statements are used
to display results on the screen.
These are part of the Standard Input/Output Library (stdio.h).

2. Output Statements

(a) printf()

 The most commonly used output function.

 Displays data on the standard output (usually the screen).

 Uses format specifiers to control the type of output.

Syntax:

printf("format string", variables);

Example:

int age = 20;

printf("Age = %d", age);

Common format specifiers:


 %d → integer

 %f → float

 %lf → double

 %c → character

 %s → string

(b) puts()

 Prints a string followed by a newline.

 Simpler than printf but less flexible.

Example:

puts("Hello, World!");

(c) putchar()

 Prints a single character to the output.

Example:

putchar('A');

3. Input Statements

(a) scanf()

 Used to take input from the user.

 Requires address-of operator (&) for variables (except strings).

Syntax:

scanf("format string", &variables);

Example:

int age;

scanf("%d", &age);

Common format specifiers:

 %d → integer

 %f → float

 %lf → double

 %c → character
 %s → string

(b) gets() (unsafe, but in older C)

 Reads a string with spaces until a newline is entered.

 Not recommended (unsafe, replaced by fgets()).

Example:

char name[50];

gets(name);

(c) fgets()

 Safer alternative to gets().

 Reads a string up to a specified size (including spaces).

Example:

char name[50];

fgets(name, 50, stdin);

(d) getchar()

 Reads a single character from input.

Example:

char ch;

ch = getchar();

4. Program Example (Combining Input & Output)

#include <stdio.h>

int main() {

int age;

char name[20];

printf("Enter your name: ");

fgets(name, 20, stdin);


printf("Enter your age: ");

scanf("%d", &age);

printf("Hello %s", name);

printf("You are %d years old.\n", age);

return 0;

4) Draw a flowchart and write an algorithm to check


whether a given number is prime or not.
Step 1: Start
Step 2: Input a number n
Step 3: If n <= 1, then print "Not Prime" and stop
Step 4: Set a flag = 0
Step 5: Repeat for i = 2 to √n
- If n % i == 0, then set flag = 1 and break
Step 6: If flag = 0 → Print "Prime"
Else → Print "Not Prime"
Step 7: Stop
5) Write a C program for the following series
1+2+3+4+…N

#include <stdio.h>

int main() {

int N, sum = 0;

printf("Enter a positive number N: ");

scanf("%d", &N);
for(int i = 1; i <= N; i++) {

sum += i; // Adding numbers from 1 to N

printf("Sum of first %d natural numbers is: %d\n", N, sum);

return 0;

6) Write a C program to check whether the given


number is palindrome or not
#include <stdio.h>

int main() {

int num, original, reversed = 0, digit;

printf("Enter a number: ");

scanf("%d", &num);

original = num;

while(num != 0) {

digit = num % 10;

reversed = reversed * 10 + digit;

num /= 10;

if(original == reversed)

printf("%d is a palindrome.\n", original);

else

printf("%d is not a palindrome.\n", original);


return 0;

7) Explain conditional statements in detail with


example.
In programming, execution of statements is usually sequential, i.e., one after another. But many
problems require decision-making. Conditional statements in C allow a program to choose
di erent paths of execution depending on whether a given condition evaluates to true or
false.

A condition is generally a relational or logical expression (e.g., a > b, x == y, age >= 18). The
result of this condition is either:

 True (non-zero) → executes the associated block

 False (zero) → skips or executes the alternate block

Thus, conditional statements help in branching the program flow.

Types of Conditional Statements

1. if Statement

 It is the simplest conditional statement.

 Used when a block of code should run only if the condition is true.

 If the condition is false, the statements inside the if block are skipped.

Syntax:

if (condition) {

// statements executed if condition is true

Example:

if (num > 0) {

printf("Positive number");

2. if-else Statement
 Provides two-way branching.

 If the condition is true, the if block executes.

 If the condition is false, the else block executes.

 Ensures that exactly one of the two blocks is executed.

Syntax:

if (condition) {

// executes if condition is true

} else {

// executes if condition is false

Example:

if (num % 2 == 0)

printf("Even number");

else

printf("Odd number");

3. else-if Ladder

 Used when multiple conditions are to be checked.

 The conditions are evaluated sequentially from top to bottom.

 The first condition that evaluates to true executes its block, and the rest are skipped.

 If none are true, the else block executes.

Syntax:

if (condition1) {

// block 1

} else if (condition2) {

// block 2

} else if (condition3) {

// block 3

} else {

// default block

}
Example:

if (marks >= 90)

printf("Grade A");

else if (marks >= 75)

printf("Grade B");

else if (marks >= 50)

printf("Grade C");

else

printf("Fail");

4. switch Statement

 Used when a variable/expression has to be compared with many fixed values (cases).

 Provides a cleaner alternative to multiple else-if statements.

 Works only with integral types (int, char, enum).

 Each case must end with a break to prevent fall-through.

Syntax:

switch(expression) {

case value1:

// statements

break;

case value2:

// statements

break;

...

default:

// executed if no case matches

Example:

switch(day) {

case 1: printf("Monday"); break;

case 2: printf("Tuesday"); break;


case 3: printf("Wednesday"); break;

default: printf("Invalid day");

8) Write in detail about various looping statements


with suitable example

In C programming, loops are used to execute a block of statements repeatedly until a certain
condition becomes false.

They are also called iteration statements because they allow repetition of code. Without loops,
we would have to write the same statements multiple times, which makes programs lengthy
and less e icient.

Types of Loops in C

1. for loop

 Best suited when the number of iterations is known in advance.

 It contains three expressions:

o Initialization → executed only once.

o Condition → checked before each iteration.

o Update → executed after each iteration.

Syntax:

for(initialization; condition; update) {

// loop body

Example:

for(int i = 1; i <= 5; i++) {

printf("%d ", i);

Prints: 1 2 3 4 5

2. while loop
 Used when the number of iterations is not known in advance.

 The condition is tested before the execution of the loop body.

 If the condition is false initially, the loop body will not run even once.

Syntax:

while(condition) {

// loop body

Example:

int i = 1;

while(i <= 5) {

printf("%d ", i);

i++;

Prints: 1 2 3 4 5

3. do-while loop

 Similar to while, but the condition is checked after executing the loop body.

 Hence, the loop executes at least once, even if the condition is false.

Syntax:

do {

// loop body

} while(condition);

Example:

int i = 1;

do {

printf("%d ", i);

i++;

} while(i <= 5);

Prints: 1 2 3 4 5

Loop Control Statements


C provides some special statements to control loops:

1. break → Exits the loop immediately.

2. continue → Skips the current iteration and goes to the next.

3. nested loops → Loops inside another loop (useful for patterns, matrices).

Example using break and continue:

for(int i = 1; i <= 5; i++) {

if(i == 3)

continue; // skips when i = 3

if(i == 5)

break; // stops the loop at i = 5

printf("%d ", i);

Prints: 1 2 4

9) Write a C program to find sum of digits of a number

#include <stdio.h>

int main() {

int num, sum = 0, digit;

printf("Enter a number: ");

scanf("%d", &num);

while(num != 0) {

digit = num % 10;

sum += digit;

num /= 10;

}
printf("Sum of digits is: %d\n", sum);

return 0;

10) Write a C program to swap two numbers with and


without using temporary variable

#include <stdio.h>

int main() {

int a, b, temp;

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

temp = a;

a = b;

b = temp;

printf("After swapping: a = %d, b = %d\n", a, b);

return 0;

#include <stdio.h>

int main() {

int a, b;

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);


a = a + b;

b = a - b;

a = a - b;

printf("After swapping: a = %d, b = %d\n", a, b);

return 0;

11) Write a C program to find the factorial of a given


number using while.

#include <stdio.h>

int main() {

int n, factorial = 1, i = 1;

printf("Enter a number: ");

scanf("%d", &n);

while(i <= n) {

factorial *= i;

i++;

printf("Factorial of %d is %d\n", n, factorial);

return 0;

}
12) Write a C program to check whether a given year
is leap or not

#include <stdio.h>

int main() {

int year;

printf("Enter a year: ");

scanf("%d", &year);

if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))

printf("%d is a leap year.\n", year);

else

printf("%d is not a leap year.\n", year);

return 0;

13) Write a C program to check whether a given year


is leap or not

In C programming, statements are executed sequentially by default.


However, sometimes we need to make decisions and execute certain statements only if a
condition is true or false.

This is achieved using conditional branching statements, which control the flow of
execution in a program.

Types of Conditional Branching Statements in C

1. if Statement

 Simplest form of decision-making.

 Executes a block of code only if the condition is true.

 If condition is false, the block is skipped.


Syntax:

if (condition) {

// statements

Flow:
Condition true → executes block → end
Condition false → skip block → end

Example:

if (num > 0) {

printf("Positive number");

2. if-else Statement

 Provides two-way branching.

 Executes one block if the condition is true, otherwise executes the else block.

Syntax:

if (condition) {

// true block

} else {

// false block

Flow:
Condition true → executes if block
Condition false → executes else block

Example:

if (num % 2 == 0)

printf("Even");

else

printf("Odd");

3. else-if ladder

 Used when multiple conditions need to be checked.


 Conditions are tested sequentially from top to bottom.

 First true condition executes its block, others are skipped.

 If none are true, the final else executes.

Syntax:

if (condition1) {

// block 1

} else if (condition2) {

// block 2

} else if (condition3) {

// block 3

} else {

// default block

Flow:
Checks condition1 → condition2 → condition3… until one is true.
If none true → executes else.

Example:

if (marks >= 90)

printf("Grade A");

else if (marks >= 75)

printf("Grade B");

else if (marks >= 50)

printf("Grade C");

else

printf("Fail");

4. switch Statement

 Used for multi-way branching.

 Expression is evaluated and compared against case values.

 When a match is found, that case executes.

 If no match, the default block executes.

 Each case usually ends with break to prevent fall-through.


Syntax:

switch(expression) {

case value1:

// statements

break;

case value2:

// statements

break;

...

default:

// statements

Flow:

 Expression evaluated once

 Control jumps to matching case

 Executes until break is encountered

 If no match, default is executed

Example:

switch(day) {

case 1: printf("Monday"); break;

case 2: printf("Tuesday"); break;

case 3: printf("Wednesday"); break;

default: printf("Invalid day");

Comparison of Conditional Statements

Statement Usage

if Simple one-way check

if-else Two-way decision

else-if ladder Multiple condition checks


Statement Usage

switch Multi-way branching for fixed values

Conclusion

Conditional branching statements in C are essential for decision-making.

 if is used for simple checks.

 if-else provides two outcomes.

 else-if ladder handles multiple conditions.

 switch is e icient for menu-driven or fixed-choice problems.

Thus, conditional statements make programs logical, flexible, and dynamic.

14) Write a C program to find the sum of all odd /


even numbers between 1 and100.

#include <stdio.h>

int main() {

int sumEven = 0, sumOdd = 0;

for(int i = 1; i <= 100; i++) {

if(i % 2 == 0)

sumEven += i;

else

sumOdd += i;

printf("Sum of even numbers: %d\n", sumEven);

printf("Sum of odd numbers: %d\n", sumOdd);


return 0;

}
Develop a C program for the following:

1.(i) To check whether a number is prime


or not.
🔹 Introduction
A prime number is a natural number greater than 1 which has no divisors other than 1 and
itself.​
Examples: 2, 3, 5, 7, 11, 13… are prime numbers.​
Prime number checking is one of the fundamental problems in C programming, often used in
number theory and cryptography.

🔹 Key Points to Remember


●​ Prime numbers have exactly two factors → 1 and the number itself.​

●​ If a number is divisible by any value between 2 and (n/2) or √n, it is not prime.​

●​ Steps to check prime:​

1.​ Input the number.​

2.​ Handle special cases (0, 1 are not prime).​

3.​ Divide the number by integers from 2 up to n/2 (or √n for efficiency).​

4.​ If divisible, it is not prime; otherwise, it is prime.

🔹 Example C Program
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
printf("%d is not a prime number.\n", n);
return 0;
}

for (i = 2; i <= n / 2; i++) {


if (n % i == 0) {
flag = 1; // divisor found
break;
}
}

if (flag == 0)
printf("%d is a prime number.\n", n);
else
printf("%d is not a prime number.\n", n);

return 0;
}

🔹 Sample Output
Enter a number: 7
7 is a prime number.

Enter a number: 12
12 is not a prime number.

🔹 Conclusion
Prime number checking is a simple yet important concept in programming. By using loops and
conditional statements in C, we can efficiently determine whether a number is prime or not.
(ii) To convert the temperature given in
Fahrenheit to Celsius and vice versa.

🔹 Introduction
Temperature conversion is a common problem in C programming. The two widely used scales
are Celsius (°C) and Fahrenheit (°F). Conversion between them is required in scientific and
real-life applications such as weather systems, physics, and engineering.

🔹 Conversion Formulas
●​ Celsius → Fahrenheit​
F=(C×95)+32F = (C \times \tfrac{9}{5}) + 32F=(C×59​)+32
●​ Fahrenheit → Celsius​
C=(F−32)×59C = (F - 32) \times \tfrac{5}{9}C=(F−32)×95​

🔹 Steps in Program
1.​ Ask the user to choose conversion type.​

2.​ Input the temperature value.​

3.​ Apply the correct formula.​

4.​ Display the converted result.​

🔹 Example C Program
#include <stdio.h>

int main() {

int choice;

float c, f;

printf("Temperature Conversion\n");
printf("1. Celsius to Fahrenheit\n");

printf("2. Fahrenheit to Celsius\n");

printf("Enter your choice (1 or 2): ");

scanf("%d", &choice);

if (choice == 1) {

printf("Enter temperature in Celsius: ");

scanf("%f", &c);

f = (c * 9 / 5) + 32;

printf("%.2f Celsius = %.2f Fahrenheit\n", c, f);

else if (choice == 2) {

printf("Enter temperature in Fahrenheit: ");

scanf("%f", &f);

c = (f - 32) * 5 / 9;

printf("%.2f Fahrenheit = %.2f Celsius\n", f, c);

else {

printf("Invalid choice!\n");

return 0;

}
🔹 Sample Output
Temperature Conversion

1. Celsius to Fahrenheit

2. Fahrenheit to Celsius

Enter your choice (1 or 2): 1

Enter temperature in Celsius: 37

37.00 Celsius = 98.60 Fahrenheit

Temperature Conversion

1. Celsius to Fahrenheit

2. Fahrenheit to Celsius

Enter your choice (1 or 2): 2

Enter temperature in Fahrenheit: 100

100.00 Fahrenheit = 37.78 Celsius

🔹 Conclusion
By using simple arithmetic formulas, the program efficiently converts temperatures between
Celsius and Fahrenheit. This demonstrates the use of mathematical expressions, conditional
statements, and user input handling in C programming.
2: Summarize the algorithm, flowchart and
pseudo code with an example.
🔹 Introduction
In programming, problem solving is done in a systematic way. Before writing a program in C, we
use Algorithm, Flowchart, and Pseudocode to represent the logic. These help in
understanding the problem better and avoiding errors in coding.

🔹 Key Points
●​ Algorithm → Step-by-step procedure to solve a problem.​

●​ Flowchart → Graphical representation of the steps using standard symbols.​

●​ Pseudocode → English-like representation of program logic, close to coding but not


syntax-bound.​

●​ C Program → Actual implementation in C language.​

🔹 Example Problem: Find Largest of Two Numbers


1. Algorithm

1.​ Start​

2.​ Read two numbers a and b​

3.​ If a > b then print "a is largest"​

4.​ Else print "b is largest"​

5.​ Stop​
2. Flowchart (Text Representation)

+------------------+

| Start |

+------------------+

+------------------+

| Input a, b |

+------------------+

+-------------------------+

| Is a > b ? |

+-------------------------+

| Yes | No

v v

+------------------+ +------------------+

| Print a largest | | Print b largest |

+------------------+ +------------------+

\ /

\ /

v v
+-------------+

| Stop |

+-------------+

3. Pseudocode

BEGIN

INPUT a, b

IF a > b THEN

PRINT "a is largest"

ELSE

PRINT "b is largest"

ENDIF

END

4. C Program

#include <stdio.h>

int main() {

int a, b;

printf("Enter two numbers: ");

scanf("%d %d", &a, &b);

if (a > b)

printf("%d is the largest number\n", a);

else

printf("%d is the largest number\n", b);


return 0;

5. Sample Output

Enter two numbers: 15 25

25 is the largest number

🔹 Conclusion
Thus, any programming problem can be represented using Algorithm, Flowchart, and
Pseudocode before converting it into actual code. This approach ensures clarity, reduces
errors, and makes the solution easy to understand.

3: Compare and contrast branching and


looping statements used in C.
🔹 Introduction
In C programming, control statements are used to change the flow of execution. They mainly
include:

●​ Branching statements → Used for decision-making (choosing one path).​

●​ Looping statements → Used for repetition (executing a block multiple times).​


Understanding their difference is essential for writing efficient programs.​

🔹 Branching Statements (Decision Making)


●​ Decide which block of code to execute based on conditions.​

●​ Execute once, depending on the condition.​

●​ Examples:​

○​ if, if-else, nested if, if-else if, switch.​


🔹 Looping Statements (Iteration)
●​ Execute a block of code repeatedly until a condition is false.​

●​ Useful for tasks that require repetition.​

●​ Examples:​

○​ for, while, do-while.​

🔹 Comparison (Branching vs Looping)


Aspect Branching Statements Looping Statements

Purpose Decision-making (choose a path) Repetition (execute multiple times)

Execution Executes a block once Executes a block multiple times

Keywords if, if-else, switch for, while, do-while

Example Check if a number is positive or not Print numbers from 1 to 10


Scenario

Branching Statements in C

Branching statements in C are used to make decisions in a program. They allow the program to
execute different blocks of code based on certain conditions. The primary branching statements
include if, if-else, nested if-else, and switch. For example, the if statement
executes a block of code only if a given condition is true, while if-else provides an alternative
block of code if the condition is false. The switch statement allows a variable to be tested
against multiple values, making it easier to manage multiple conditions instead of writing many
if-else statements. Branching is crucial in programming because it enables conditional
execution, allowing programs to respond dynamically to user input or data values.
Branching statements are generally used when the program needs to make choices or select
from several possible execution paths. They improve the readability and organization of the
code, as each condition is clearly separated. However, they do not repeat any code
automatically; they only decide which code executes at a particular moment. Excessive or
deeply nested branching can make a program complex and harder to debug, so careful design
is necessary. Overall, branching is essential for decision-making logic in C programs.

Looping Statements in C

Looping statements in C are used to execute a block of code repeatedly as long as a specific
condition is true. The main looping statements are for, while, and do-while. The for loop
is generally used when the number of iterations is known beforehand, while the while loop is
used when the number of iterations depends on a condition evaluated before each iteration. The
do-while loop guarantees that the code block executes at least once, as the condition is
checked after the execution. Looping is essential for tasks that require repetition, such as
processing arrays, performing calculations multiple times, or repeatedly taking input from a user.

Loops help in reducing code redundancy and make programs more efficient by automating
repetitive tasks. They also improve maintainability, as changes need to be made only once
inside the loop rather than in multiple repeated statements. However, improper use of loops,
such as missing exit conditions, can lead to infinite loops and program crashes. Combined with
branching statements, loops form the backbone of most C programs, allowing both repetition
and decision-making to achieve complex logic and functionality.

🔹 Example Program in C
#include <stdio.h>

int main() {

int num, i;

// Branching Example

printf("Enter a number: ");

scanf("%d", &num);
if (num % 2 == 0)

printf("%d is Even (Branching)\n", num);

else

printf("%d is Odd (Branching)\n", num);

// Looping Example

printf("Numbers from 1 to 5 (Looping):\n");

for (i = 1; i <= 5; i++) {

printf("%d ", i);

printf("\n");

return 0;

🔹 Sample Output
Enter a number: 7

7 is Odd (Branching)

Numbers from 1 to 5 (Looping):

1 2 3 4 5

🔹 Conclusion
●​ Branching controls the flow by selecting one path among alternatives.​

●​ Looping controls the flow by repeating a set of statements until a condition is false.​
Both are essential for building decision-based and repetitive tasks in C programs.
4: Write a C program to develop a simple
calculator using switch.
🔹 Introduction
A calculator program in C demonstrates the use of switch-case branching. The switch
statement allows us to execute different blocks of code based on the operator chosen (+ , -
, * , /). It avoids multiple if-else statements and makes the program cleaner and easier
to read.

🔹 Key Points about switch


●​ The switch statement is a multi-way branch.​

●​ Each case represents a possible operation.​

●​ The break statement is used to exit after a case executes.​

●​ The default case handles invalid inputs.​

🔹 Steps in Program
1.​ Input two numbers.​

2.​ Input the operation choice (+ , - , * , /).​

3.​ Use switch to perform the calculation.​

4.​ Display the result.​

5.​

🔹 Example C Program
#include <stdio.h>

int main() {

int a, b;
char op;

float result;

printf("Enter first number: ");

scanf("%d", &a);

printf("Enter second number: ");

scanf("%d", &b);

printf("Enter operator (+, -, *, /): ");

scanf(" %c", &op); // space before %c to consume newline

switch (op) {

case '+':

result = a + b;

printf("Result: %d + %d = %.2f\n", a, b, result);

break;

case '-':

result = a - b;

printf("Result: %d - %d = %.2f\n", a, b, result);

break;

case '*':

result = a * b;

printf("Result: %d * %d = %.2f\n", a, b, result);

break;
case '/':

if (b != 0) {

result = (float)a / b;

printf("Result: %d / %d = %.2f\n", a, b, result);

} else {

printf("Error: Division by zero not allowed!\n");

break;

default:

printf("Invalid operator!\n");

return 0;

🔹 Sample Output
Enter first number: 12

Enter second number: 4

Enter operator (+, -, *, /): /


Result: 12 / 4 = 3.00

Enter first number: 15

Enter second number: 5

Enter operator (+, -, *, /): -

Result: 15 - 5 = 10.00

This C program implements a simple calculator that allows users to perform basic arithmetic
operations such as addition, subtraction, multiplication, and division. It begins by prompting the
user to enter two numerical values and an arithmetic operator (+, -, *, or /). Once the input is
provided, the program uses a switch statement to evaluate the operator and determine which
mathematical operation should be executed. Each case in the switch corresponds to one of the
four operations and computes the result accordingly, which is then displayed on the screen with
appropriate formatting. The division operation is handled carefully by including a conditional
check to prevent division by zero, which could otherwise cause the program to crash or produce
an undefined result.

The program also includes a default case to catch any invalid operators entered by the user,
enhancing its robustness and user-friendliness. The use of the switch statement not only
makes the program more structured and readable but also simplifies the logic by avoiding
multiple nested if-else statements. This approach makes it easier to maintain and extend the
program in the future—for instance, by adding more operations like modulus or exponentiation
without disrupting the existing structure. Additionally, the program demonstrates key
programming concepts such as user input handling, conditional decision-making, and arithmetic
computation, making it an excellent example of how decision-control statements in C can be
applied to real-world problems. Overall, this program is a simple yet effective way to illustrate
the use of the switch statement in creating interactive and functional applications.

🔹 Conclusion
The switch-case statement is highly effective in building menu-driven programs like
calculators. It allows clear separation of cases and avoids complex nested if-else structures.
This makes the program readable, maintainable, and efficient.
5: Write Syntax, Flowchart and develop C
Program to find the student grade using
else-if ladder.
🔹 Introduction
In C programming, the else-if ladder is used when there are multiple conditions to be checked
one after another. It is very useful in grading systems, where marks fall into different ranges and
each range corresponds to a grade.

🔹 Syntax of Else-If Ladder


if (condition1) {

// statements

else if (condition2) {

// statements

else if (condition3) {

// statements

else {

// default statements

}
🔹 Example C Program
#include <stdio.h>

int main() {

int marks;

printf("Enter student marks: ");

scanf("%d", &marks);
if (marks >= 90) {

printf("Grade: A\n");

else if (marks >= 75) {

printf("Grade: B\n");

else if (marks >= 60) {

printf("Grade: C\n");

else if (marks >= 40) {

printf("Grade: D\n");

else {

printf("Grade: F (Fail)\n");

return 0;

🔹 Sample Output
Enter student marks: 85
Grade: B

Enter student marks: 35

Grade: F (Fail)

🔹 Conclusion
The else-if ladder provides a clear way to test multiple conditions in sequence. In this example,
it is used to assign grades based on marks. This is a practical application of decision-making in
C programming.

6: Draw a flowchart to find the max of


three numbers and explain.
🔹 Introduction
In C programming, finding the maximum of three numbers is a common problem in
decision-making. By comparing numbers step by step using conditional statements, we can
determine the largest among them. Flowcharts help visualize the logic before coding.

🔹 Explanation of Logic
1.​ Start the program.​

2.​ Input three numbers a, b, c.​

3.​ Compare a with b and c. If a is greatest, then a is maximum.​

4.​ Else compare b with c. If b is greatest, then b is maximum.​

5.​ Otherwise, c is maximum.​

6.​ Display the maximum value and stop.​


🔹 Flowchart (Image)
CODE

#include <stdio.h>

int main() {
int a, b, c, max;

// Input three numbers


printf("Enter three numbers: ");
scanf("%d %d %d", &a, &b, &c);

if (a >= b && a >= c) {


max = a;
}
else if (b >= a && b >= c) {
max = b;
}
else {
max = c;
}

// Display the maximum number


printf("The maximum of the three numbers is: %d\n", max);

return 0;
}

🔹 Sample Output
Enter three numbers: 12 45 30
The maximum of the three numbers is: 45

Explanation

The given C program is designed to find the maximum among three numbers entered by the
user. It begins with including the standard input-output header file <stdio.h> to use functions
like printf() and scanf(). Inside the main() function, three integer variables a, b, and c
are declared to store the user inputs, and another variable max is declared to store the
maximum value. The program first prompts the user to enter three numbers using printf()
and then takes input through scanf().
The logic for finding the maximum is implemented using if–else if–else decision-making
statements. The first condition if (a >= b && a >= c) checks whether a is greater than or
equal to both b and c. If this condition is true, then a is the maximum and is assigned to the
variable max. If the first condition is false, then the else if (b >= a && b >= c) condition
is checked to determine whether b is greater than or equal to both a and c. If true, then b is
assigned to max. If both the above conditions are false, it means that c is the largest, and hence
the final else block assigns c to max. After the maximum value is determined, the program
displays the result using printf(). Finally, the program ends by returning 0, which indicates
successful execution. This program effectively demonstrates the use of conditional operators to
compare multiple values and determine the greatest among them.

(ii) Write the pseudocode for finding


Simple Interest.
🔹 Introduction
In C programming and general problem solving, pseudocode helps in writing the steps of a
problem in a human-readable format before converting it into actual code. Simple Interest (SI)
is a fundamental calculation in finance and mathematics, and it can be easily implemented in C.
The formula for simple interest is:

SI=P×R×T100SI = \frac{P \times R \times T}{100}SI=100P×R×T​

Where:

●​ P → Principal amount​

●​ R → Rate of interest​

●​ T → Time (in years)​


🔹 Pseudocode for Simple Interest
BEGIN

INPUT Principal (P), Rate (R), Time (T)

COMPUTE SI = (P * R * T) / 100

PRINT "Simple Interest = ", SI

END

🔹 Flowchart
C Program for Simple Interest

#include <stdio.h>

int main() {
float P, R, T, SI;

// Input values
printf("Enter Principal amount: ");
scanf("%f", &P);

printf("Enter Rate of Interest: ");


scanf("%f", &R);

printf("Enter Time (in years): ");


scanf("%f", &T);

// Calculate Simple Interest


SI = (P * R * T) / 100;

// Display result
printf("Simple Interest = %.2f\n", SI);

return 0;
}

🔹 Explanation
This C program is designed to calculate Simple Interest (SI) based on the user’s input of
Principal (P), Rate of Interest (R), and Time (T) in years. The program begins with including
the header file <stdio.h> which allows us to use input and output functions like printf()
and scanf(). Inside the main() function, four floating-point variables P, R, T, and SI are
declared. Floating-point data type is chosen because values like rate of interest or time may not
always be integers (for example, 7.5% or 2.5 years).
The program then prompts the user to enter the principal amount, rate of interest, and time.
These inputs are read using scanf() and stored in their respective variables. After collecting
the inputs, the formula for simple interest is applied:

SI=P×R×T100SI = \frac{P \times R \times T}{100}SI=100P×R×T​

This formula multiplies the principal, rate, and time, and divides the product by 100 to get the
interest. The calculated simple interest is then stored in the variable SI. Finally, the result is
displayed on the screen using printf(), formatted to two decimal places for clarity. The
program then returns 0, which indicates successful execution.

In summary, this program demonstrates how to take input from the user, apply a mathematical
formula, and display the result using conditional and arithmetic operators in C. It provides a
simple but practical example of real-world financial calculations implemented through
programming.

You might also like