0% found this document useful (0 votes)
17 views30 pages

CS Q&A -2

In C programming, tokens are the smallest meaningful units, categorized into six types: keywords, identifiers, constants, strings, operators, and special symbols. The document also explains format specifiers like %d for integers and %f for floating-point numbers, as well as arithmetic operators and I/O operations. Additionally, it covers control statements such as if, switch, break, and continue, along with type conversion and their differences.

Uploaded by

Prajeen.p
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)
17 views30 pages

CS Q&A -2

In C programming, tokens are the smallest meaningful units, categorized into six types: keywords, identifiers, constants, strings, operators, and special symbols. The document also explains format specifiers like %d for integers and %f for floating-point numbers, as well as arithmetic operators and I/O operations. Additionally, it covers control statements such as if, switch, break, and continue, along with type conversion and their differences.

Uploaded by

Prajeen.p
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/ 30

Definition of Tokens in C: li

In C programming, tokens are the smallest meaningful units in a program. They are the
building blocks of a C program and are used to construct statements and expressions.

Types of Tokens in C:

There are six types of tokens in C:

1.​ Keywords
2.​ Identifiers
3.​ Constants
4.​ Strings
5.​ Operators
6.​ Special Symbols

Any 4 Types of Tokens:

1.​ Keywords – Reserved words that have a special meaning in C (e.g., int, return,
if, while).
2.​ Identifiers – Names given to variables, functions, arrays, etc. (e.g., sum, main,
num1).
3.​ Operators – Symbols used for operations (e.g., +, -, *, /).
4.​ Constants – Fixed values that do not change during program execution (e.g., 3.14,
100, 'A').

In C programming, %d and %f are format specifiers used in functions like printf() and
scanf() to specify the type of data being printed or read.

1. %d (Integer Format Specifier)


●​ Used for integer (int) values.
●​ %d stands for "decimal integer", meaning it prints numbers in base 10.

Example (Printing an Integer)​


#include <stdio.h>

int main() {

int num = 25;


printf("The number is: %d\n", num);

return 0;

Output:​
The number is: 25

●​

Example (Reading an Integer from Input)​


int num;

scanf("%d", &num); // Reads an integer from user input

●​

2. %f (Floating-Point Format Specifier)


●​ Used for floating-point numbers (float).​

●​ %f prints numbers with decimal points (default: 6 decimal places).​

Example (Printing a Floating-Point Number)​



#include <stdio.h>

int main() {

float pi = 3.14159;

printf("Value of pi: %f\n", pi);

return 0;

Output:​

Value of pi: 3.141590

●​ (Notice it prints 6 decimal places by default.)​


Controlling Decimal Places with %.nf​

printf("%.2f", pi); // Prints: 3.14

●​

Example (Reading a Floating-Point Number from Input)​



float num;

scanf("%f", &num); // Reads a float from user input

●​

Summary

Format Specifier Data Type Example

%d int (integer) printf("%d", 42); →


42

%f float (floating-point) printf("%f", 3.14); →


3.140000

Arithmetic Operators in C

An arithmetic operator in C is used to perform mathematical operations such as addition,


subtraction, multiplication, division, and modulus.

Types of Arithmetic Operators


Operator Symbol Example Description

Addition + a + b Adds two numbers

Subtraction - a - b Subtracts second


number from first

Multiplication * a * b Multiplies two


numbers
Division / a / b Divides first number
by second (quotient)

Modulus % a % b Returns remainder


of division

Example Program
#include <stdio.h>

int main() {
int a = 10, b = 3;

printf("Addition: %d\n", a + b); // 10 + 3 = 13


printf("Subtraction: %d\n", a - b); // 10 - 3 = 7
printf("Multiplication: %d\n", a * b); // 10 * 3 = 30
printf("Division: %d\n", a / b); // 10 / 3 = 3 (integer division)
printf("Modulus: %d\n", a % b); // 10 % 3 = 1 (remainder)

return 0;
}

Output:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1

Difference Between Formatted and Unformatted Input/Output in C

In C programming, input/output (I/O) operations can be categorized into formatted and


unformatted based on how they handle data.

1. Formatted Input/Output
Formatted I/O functions allow the programmer to specify format specifiers to control the
format of input and output.

Common Formatted I/O Functions


●​ printf() → Displays formatted output
●​ scanf() → Reads formatted input

Example (Formatted I/O)


#include <stdio.h>

int main() {
int age;
float height;

printf("Enter your age and height: ");


scanf("%d %f", &age, &height); // Input as integer and float

printf("You are %d years old and %.2f meters tall.\n", age, height);
return 0;
}

Output (if user enters 25 5.8):


You are 25 years old and 5.80 meters tall.

Key Features of Formatted I/O: ✔ Uses format specifiers (%d, %f, etc.)​
✔ Controls the way data is displayed or read​
✔ More precise but requires careful input formatting

2. Unformatted Input/Output
Unformatted I/O functions handle data without any specific format. They work with
characters and strings without using format specifiers.

Common Unformatted I/O Functions


Function Description

getchar() Reads a single character from input

putchar() Prints a single character to output

gets() (unsafe, avoid using) Reads a string (until newline)

puts() Prints a string followed by a newline

Example (Unformatted I/O)


#include <stdio.h>

int main() {
char name[50];

printf("Enter your name: ");


gets(name); // Reads a string (avoid using for security reasons)

printf("Hello, ");
puts(name); // Prints the string with a newline

return 0;
}

Output (if user enters John):


Hello, John

Key Features of Unformatted I/O: ✔ Works with characters and strings​


✔ Does not require format specifiers​
✔ Simpler but less control over formatting

Comparison Table
Feature Formatted I/O Unformatted I/O

Functions Used printf(), scanf() getchar(), putchar(),


gets(), puts()

Data Types Works with all data types Works mostly with
(int, float, char, etc.) characters and strings

Format Specifiers Required (%d, %f, etc.) Not required

Control Over Output High Low

Example Output %.2f for 2 decimal places No control over decimals

When to Use?

●​ Use Formatted I/O (printf(), scanf()) when dealing with numbers, precise
formatting, or structured input.
●​ Use Unformatted I/O (getchar(), puts()) when handling single characters or
simple string outputs.
Type Conversion in C

Type conversion in C refers to changing one data type into another to ensure proper
operations between different types of variables.

Types of Type Conversion


There are two types of type conversion in C:

1.​ Implicit Type Conversion (Automatic Type Conversion)


2.​ Explicit Type Conversion (Type Casting)

1. Implicit Type Conversion (Automatic Type


Conversion)
●​ Performed automatically by the compiler.
●​ Happens when a smaller data type is converted into a larger data type to prevent
data loss.
●​ Example of Automatic Promotion Order:​
char → short → int → long → float → double → long double

Example (Implicit Conversion)


#include <stdio.h>

int main() {
int num = 5;
float result = num + 2.5; // int is converted to float automatically

printf("Result: %f\n", result); // Output: 7.500000


return 0;
}

Explanation:

●​ num is an int, but when added to 2.5 (a float), it automatically converts to


float.

2. Explicit Type Conversion (Type Casting)


●​ Manually forced by the programmer using the type cast operator ((type)).
●​ Used when conversion is necessary but not performed automatically.
●​ Can cause data loss if converting from a larger type to a smaller type.
Example (Explicit Conversion)
#include <stdio.h>

int main() {
double pi = 3.14159;
int truncated_pi = (int) pi; // Type casting double to int

printf("Original: %f\n", pi);


printf("After Type Casting: %d\n", truncated_pi); // Output: 3
return 0;
}

Explanation:

●​ (int) pi converts the double value 3.14159 into an int, removing the decimal
part.

Difference Between Implicit and Explicit Conversion


Feature Implicit Conversion Explicit Conversion (Type
Casting)

Performed by Compiler Programmer

Syntax Automatic Uses (type)

Data Loss No Possible

Example int → float (int) 3.14 → 3


automatically

Break and Continue Statements in c

The break and continue statements are used to control the flow of loops (for, while,
do-while) and switch cases in C.
1. break; Statement
●​ The break statement terminates the loop or switch statement immediately.
●​ When break is encountered inside a loop, the program exits the loop and moves to
the next statement after the loop.

Example: Using break in a Loop

#include <stdio.h>

int main() {

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

if (i == 5) {

break; // Exits the loop when i == 5

printf("%d ", i);

return 0;

Output:

1234

Explanation:

●​ The loop starts from 1 and runs up to 10, but when i == 5, the break statement
stops the loop immediately.

Example: Using break in a switch Case

#include <stdio.h>
int main() {

int num = 2;

switch (num) {

case 1:

printf("One\n");

break;

case 2:

printf("Two\n");

break; // Exits switch, preventing execution of further cases

case 3:

printf("Three\n");

break;

default:

printf("Invalid\n");

return 0;

Output:

Two

Explanation:

●​ Without break, the program would continue executing the next cases.

2. continue; Statement
●​ The continue statement skips the rest of the current iteration and moves to the
next iteration of the loop.
●​ Unlike break, continue does not terminate the loop—it just skips some code.

Example: Using continue in a Loop

#include <stdio.h>

int main() {

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

if (i == 3) {

continue; // Skips printing when i == 3

printf("%d ", i);

return 0;

Output:

1245

Explanation:

●​ When i == 3, continue skips the printf() statement and moves to the next
iteration.

Key Differences Between break and continue

Feature break continue


Effect Exits the loop completely Skips current iteration and
moves to next

Works In Loops (for, while, Only in loops (for, while,


do-while), switch do-while)

Example Output (for i=1 1 2 (loop stops) 1 2 4 5 (skips 3, loop


to 5, break at 3) continues)

if Statement in C and Its Types

In C programming, the if statement is a conditional control statement used to execute a


block of code only if a specified condition is true.

1. Simple if Statement
●​ The if statement checks a condition. If the condition is true, it executes the block
inside {}.
●​ If the condition is false, it skips the block.

Syntax:

if (condition) {

// Code to execute if condition is true

Example:

#include <stdio.h>

int main() {
int num = 10;

if (num > 0) {

printf("Number is positive.\n");

return 0;

Output:

Number is positive.

Explanation: Since num > 0 is true, the printf() statement is executed.

2. if-else Statement
●​ Adds an else block to execute when the if condition is false.

Syntax:

if (condition) {

// Executes if condition is true

} else {

// Executes if condition is false

Example:

#include <stdio.h>
int main() {

int num = -5;

if (num > 0) {

printf("Number is positive.\n");

} else {

printf("Number is negative.\n");

return 0;

Output:

Number is negative.

Explanation: Since num > 0 is false, the else block executes.

3. if-else if-else Ladder


●​ Used when multiple conditions need to be checked sequentially.
●​ The program checks conditions one by one until a true condition is found.

Syntax:

if (condition1) {

// Executes if condition1 is true

} else if (condition2) {

// Executes if condition2 is true


} else {

// Executes if none of the above conditions are true

Example:

#include <stdio.h>

int main() {

int num = 0;

if (num > 0) {

printf("Number is positive.\n");

} else if (num < 0) {

printf("Number is negative.\n");

} else {

printf("Number is zero.\n");

return 0;

Output:

Number is zero.

Explanation: Since num > 0 and num < 0 are false, the else block executes.
4. Nested if Statement
●​ An if statement inside another if statement.
●​ Used when one condition depends on another condition.

Syntax:

if (condition1) {

if (condition2) {

// Executes if both condition1 and condition2 are true

Example:

#include <stdio.h>

int main() {

int num = 15;

if (num > 0) { // First condition

if (num % 5 == 0) { // Second condition

printf("Number is positive and divisible by 5.\n");

return 0;

Output:
Number is positive and divisible by 5.

Explanation:

●​ num > 0 is true, so it checks the inner if statement.


●​ num % 5 == 0 is also true, so the message prints.

Comparison of if Statement Types

Type Description Example Condition

Simple if Executes code only if if (x > 0)


condition is true

if-else Executes one block for true, if (x > 0) else


another for false

if-else if-else Checks multiple conditions if (x > 0) else if (x


in sequence < 0) else

Nested if if inside another if if (x > 0) { if (x %


2 == 0) }

Switch Statement in C

A switch statement in C is a multi-way decision-making control statement that


executes one out of many possible code blocks based on a variable’s value. It is an
alternative to multiple if-else if statements and improves code readability.
Syntax of switch Statement
switch (expression) {

case value1:

// Code to execute if expression == value1

break;

case value2:

// Code to execute if expression == value2

break;

...

default:

// Code to execute if no cases match

●​ The expression is usually an int or char (floating-point values are not allowed).
●​ Each case specifies a possible value for expression and executes the
corresponding code.
●​ The break statement exits the switch after a case is executed (without break,
execution continues to the next case).
●​ The default case executes if no cases match (optional).

Example: Basic switch Statement


#include <stdio.h>

int main() {

int day = 3;

switch (day) {
case 1:

printf("Monday\n");

break;

case 2:

printf("Tuesday\n");

break;

case 3:

printf("Wednesday\n");

break;

case 4:

printf("Thursday\n");

break;

case 5:

printf("Friday\n");

break;

default:

printf("Invalid day\n");

return 0;

Output:

Wednesday

Explanation:
●​ day = 3, so case 3 executes.
●​ The break statement prevents further execution.

Example: switch Without break (Fall-through


Behavior)
If break is omitted, the execution continues to the next case.

#include <stdio.h>

int main() {

int num = 2;

switch (num) {

case 1:

printf("One\n");

case 2:

printf("Two\n");

case 3:

printf("Three\n");

default:

printf("Invalid\n");

return 0;

Output:
Two

Three

Invalid

Explanation:

●​ num = 2, so case 2 starts executing.


●​ No break, so it continues executing case 3 and default.

Example: Using char in a switch Statement


#include <stdio.h>

int main() {

char grade = 'B';

switch (grade) {

case 'A':

printf("Excellent\n");

break;

case 'B':

printf("Good\n");

break;

case 'C':

printf("Average\n");

break;

default:

printf("Fail\n");
}

return 0;

Output:

Good

Explanation:

●​ grade = 'B', so case 'B' executes.

Example: Using switch with default Case


The default case executes if no case matches.

#include <stdio.h>

int main() {

int num = 10;

switch (num) {

case 1:

printf("One\n");

break;

case 2:

printf("Two\n");

break;
default:

printf("Not 1 or 2\n");

return 0;

Output:

Not 1 or 2

Explanation:

●​ Since num = 10, and no case matches, the default case executes.

Key Features of switch Statement


✔ Faster than multiple if-else if statements for simple value matching.​
✔ Uses break to stop execution after a case.​
✔ Supports int and char but not floating-point (float, double) values.​
✔ default is optional but useful as a fallback.

Difference Between if-else and switch

Feature if-else switch

Conditions Can evaluate any Works with int, char


expression values only
Complexity Used for range-based Used for exact value
conditions (x > 10) matching (x == 10)

Execution Checks all conditions (if no Jumps directly to the


else) matched case

break needed? No Yes (to stop execution)

Looping Statements in C

Looping statements in C are used to execute a block of code multiple times based on a
condition. This helps in reducing code repetition and improving efficiency.

Types of Loops in C
C provides three types of loops:

1.​ for Loop → Used when the number of iterations is known.


2.​ while Loop → Used when the number of iterations is unknown (condition-based).
3.​ do-while Loop → Similar to while, but guarantees at least one execution.

1. for Loop
The for loop is used when the number of iterations is known beforehand.

Syntax:

for (initialization; condition; update) {

// Code to execute
}

●​ Initialization → Sets the starting value.


●​ Condition → Loop runs while this is true.
●​ Update → Changes the variable in each iteration.

Example: Print numbers 1 to 5

#include <stdio.h>

int main() {

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

printf("%d ", i);

return 0;

Output:

12345

Explanation:

●​ i = 1 (initialization)
●​ i <= 5 (condition checked before each iteration)
●​ i++ (increment i after each loop)

2. while Loop
The while loop is used when the number of iterations is not known in advance. It
executes as long as the condition is true.

Syntax:
while (condition) {

// Code to execute

Example: Print numbers 1 to 5

#include <stdio.h>

int main() {

int i = 1;

while (i <= 5) {

printf("%d ", i);

i++;

return 0;

Output:

12345

Explanation:

●​ while (i <= 5) checks the condition before each execution.


●​ i++ increases the value of i after each iteration.

3. do-while Loop
The do-while loop is similar to while, but it always executes at least once, even if the
condition is false.

Syntax:

do {

// Code to execute

} while (condition);

Example: Print numbers 1 to 5

#include <stdio.h>

int main() {

int i = 1;

do {

printf("%d ", i);

i++;

} while (i <= 5);

return 0;

Output:

12345

Explanation:

●​ The block inside do executes before checking the condition.


●​ The loop runs as long as i <= 5.

Key Differences Between Loops

Feature for Loop while Loop do-while Loop

Use Case When iterations are When iterations are When at least one
known unknown execution is
required

Condition Check Before the loop Before each After each iteration
starts iteration

Execution May never execute May never execute Executes at least


Guarantee if condition is false if condition is false once

Example: Infinite Loop


If a loop's condition never becomes false, it runs forever (infinite loop).

Example: Infinite while Loop

#include <stdio.h>

int main() {

while (1) { // Condition is always true

printf("This is an infinite loop!\n");

return 0;

}
Press Ctrl + C to stop execution manually.

Loop Control Statements


●​ break; → Exits the loop immediately.
●​ continue; → Skips the current iteration and moves to the next.

Example: Using break;

#include <stdio.h>

int main() {

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

if (i == 3) {

break; // Stops loop when i == 3

printf("%d ", i);

return 0;

Output:

12

Example: Using continue;

#include <stdio.h>
int main() {

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

if (i == 3) {

continue; // Skips iteration when i == 3

printf("%d ", i);

return 0;

Output:

1245

Summary

●​ for Loop → Use when iterations are fixed.


●​ while Loop → Use when condition-based looping is needed.
●​ do-while Loop → Use when at least one execution is needed.
●​ break; → Exits loop immediately.
●​ continue; → Skips current iteration, continues the next one.

You might also like