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

C PROG. M1 FULL NOTES

The document outlines the programming course 'Programming in C' for KTU's 2024 scheme, covering fundamental concepts such as C history, programming necessity, compilers, variables, data types, and best practices. It details modules on C fundamentals, arrays, functions, pointers, and file handling, along with practical instructions for setting up the Code::Blocks IDE and writing basic programs. Additionally, it explains constants, identifiers, keywords, and various data types in C, including their memory allocation and usage.

Uploaded by

edwint6904
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

C PROG. M1 FULL NOTES

The document outlines the programming course 'Programming in C' for KTU's 2024 scheme, covering fundamental concepts such as C history, programming necessity, compilers, variables, data types, and best practices. It details modules on C fundamentals, arrays, functions, pointers, and file handling, along with practical instructions for setting up the Code::Blocks IDE and writing basic programs. Additionally, it explains constants, identifiers, keywords, and various data types in C, including their memory allocation and usage.

Uploaded by

edwint6904
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

PROGRAMMING IN C (KTU - 2024 Scheme)

Common to Group A & B (Semester – 2)

C is often referred to as the 'mother of all programming languages.'

Module 1 : C Fundamentals

Module 2 : Arrays & Strings

Module 3 : Functions , Structures and Strings

Module 4 : Pointers and Files

A Brief History of C

C programming has a rich history that traces its roots back to earlier programming languages:

1. ALGOL 60: Introduced structured programming and influenced later languages.


2. BCPL (Basic Combined Programming Language): Designed for writing system
software.
3. B: A simplified version of BCPL developed by Ken Thompson.
4. C: Developed by Dennis Ritchie in 1972-73 at Bell Labs. It was created to rewrite the
UNIX operating system and has since become one of the most widely used languages
in the world.

The Need for Programming and the Role of Compilers

Why Do We Need Programming?

Programming is essential to interact with and harness the power of computers. However,
computers operate in binary code (1s and 0s), which is impossible for humans to write or
debug efficiently. Programming languages, such as C, Python, or Java, allow us to write
instructions in a way that is easier for humans to understand.

The Role of Compilers in Bridging the Gap

A compiler is a special program that acts as a translator between humans and machines. It
converts high-level programming code (written in human-readable languages like C) into
machine code (binary) that a computer can execute. Here's why compilers are indispensable:

1. Translating Code

Compilers take your source code and translate it into a machine-readable format. For
example:
• High-level code: printf("Hello, World!");
• Compiled machine code: 01101000 01100101 ... (binary instructions).

C Fundamentals
THE C CHARACTER SET

C uses the uppercase letters A to Z, the lowercase letters a to z, the digits 0 to 9, and certain special
characters as building blocks to form basic program elements (e.g., constants, variables, operators,
expressions, etc.).

C uses certain combinations of these characters, such as \b, \n and \t,to represent special conditions
such as backspace, newline and horizontal tab, respectively. These character combinations are
known as escape sequences.

Constants (Literals) in C

In C programming, constants are fixed values that do not change during the execution of a
program. Constants make your code more readable and easier to maintain, as they represent
meaningful, unchanging data.
Types of Constants in C

1. Integer Constants
o These are whole numbers without any fractional part.
o Examples:
 10
 -45
 0

Rules for Integer Constants:

o Must not have a decimal point.


o Can be written in decimal (base 10), octal (base 8, starts with 0), or
hexadecimal (base 16, starts with 0x or 0X).

2. Floating-point Constants
o These represent real numbers with fractional parts.
o Examples:
 3.14
 -0.001
 2.5E3 (scientific notation for 2.5 × 10^3).

Rules for Floating-point Constants:

o Must have at least one digit and a decimal point.


o Can optionally include an exponent part (E or e).

3. Character Constants
o A single character enclosed in single quotes (' ').
o Examples:
 'A'
 '9'
 '#'

Rules for Character Constants:

o Can represent printable characters, escape sequences (like \n, \t), or even
ASCII values.

4. String Constants
o A sequence of characters enclosed in double quotes (" ").
o Examples:
 "Hello, World!"
 "12345"
Rules for String Constants:

o Always ends with a null character (\0) automatically.


o Cannot span multiple lines without special techniques.

Identifiers

Identifiers are names given to various elements of a program, such as variables, functions,
and arrays. They help in uniquely identifying these elements in the code.

Rules for Identifiers:

• Names can contain letters, digits and underscores


• Names must begin with a letter or an underscore (_)
• Names are case-sensitive (myVar and myvar are different variables)
• Names cannot contain whitespaces or special characters like !, #, %,
etc.
• Reserved words (such as int) cannot be used as names

Examples of Valid Identifiers:

x // Single letter
Y12 // Letters followed by digits
sum_1 // Letters, digits, and underscore
temperature // Readable name
names // Simple word
area // Descriptive

Examples of Invalid Identifiers:

Identifier Reason
8sum Starts with a digit.
x' Contains an illegal character (').
order-no Contains a hyphen (-).
error flag Contains a blank space.
Best Practices for Identifiers:

1. Choose meaningful names to represent their purpose.


Example:
Instead of x, use radius if it represents the radius of a circle.
2. Avoid excessively long names.
Example:
Use future_value instead of future_value_of_an_investment.
3. Follow naming conventions, such as using lowercase letters for variables and
underscores (_) to separate words.

Keywords

Keywords are reserved words in C with standard, predefined meanings. These cannot be used
as identifiers.

List of Standard Keywords in C:

auto extern sizeof break float static


case for struct char goto switch
const if typedef continue int union
default long unsigned do register void
double return volatile else short while
enum signed
Setting Up Code::Blocks for C Programming

IDE Used

The IDE used in this series is Code::Blocks.

Instructions to Download and Install Code::Blocks

1. Visit the Download Page:


o Follow this link: https://www.codeblocks.org/downloads/binaries/.
2. Select the Appropriate File:
o Download the file that matches your operating system (Windows, Linux, macOS).
o Ensure you download the version that includes the compiler. For example:
codeblocks-20.03mingw-setup.exe.
3. Install Code::Blocks:
o Run the downloaded setup file.
o Follow the installation instructions on the screen.
4. Open Code::Blocks:
o After installation, launch Code::Blocks.

Creating and Running Your First Program

1. Create a New Project:


o Open Code::Blocks and select Create a New Project.
o Choose the Console Application and select C as the programming language.
2. Open the main.c File:
o Navigate to the project folder within Code::Blocks.
o Open the pre-generated main.c file.
3. Write Your Code:
o Modify the main.c file or write your program.
4. Compile and Run:
o Click on Build and Run (or press F9) to compile and execute your program.

Sample Program: Print "Hello, World!"

#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0;
}

Steps:

1. Copy the code into the main.c file.


2. Compile and run to see the output:
Output:

3. Hello, World!
Variables in C

In programming, data is stored in memory. Memory consists of numerous slots, each with a
unique address used to identify that location.

For human readability, we use variables to represent these memory locations.

A variable can be thought of as a box that can hold data. The type of data stored in a variable
can be an integer, floating-point number, character, or even multiple characters (strings).

Why Use Variables?

1. Human Readability: Variables provide a meaningful name to memory locations,


making code easier to read and maintain.
2. Abstraction: They abstract the complexity of directly dealing with memory
addresses.
3. Reusability: Variables can be reused throughout a program.
4. Type Safety: Variables have a defined data type, ensuring proper handling of the
data.

Using a Variable in C

1. Declaration and Initialization

Before using a variable, you must declare it to specify the data type and allocate memory.
Example:

int x; // Declaration: Allocates memory to store an integer


x = 10; // Initialization: Assigns the value 10 to the variable x

Alternatively, declaration and initialization can be done in a single step:

int x = 10; // Declaration and initialization

Explanation:

 int: Represents the integer data type.


 x: The variable name (can store integer values).
 10: The value assigned to the variable.

2. Updating a Variable

Once a variable is initialized, its value can be updated:

int x = 10;
x = 15; // Updates the value of x to 15

Note: Declaration is needed only once for a variable.

How Much Memory is Allocated?

 An int variable typically occupies 2 to 4 bytes of memory, depending on the system


architecture.
 1 byte = 8 bits, and all data is stored in binary form. For example, characters and
numbers are converted into binary before being stored in memory.

Example: Adding Two Numbers

Let’s write a program to calculate the sum of two numbers stored in variables.

Code:

#include <stdio.h>

int main() {
int number_1 = 10; // Declare and initialize the first variable
int number_2 = 20; // Declare and initialize the second
variable
int sum = number_1 + number_2; // Add the two numbers and store the
result in sum

printf("Result = %d", sum); // Print the sum using %d format specifier


return 0;
}
Output:

Sum = 30

Explanation of Code

1. #include <stdio.h>: Includes the standard input/output library to use functions like
printf.
2. int number_1 = 10;: Declares and initializes the first integer variable.
3. int number_2 = 20;: Declares and initializes the second integer variable.
4. int sum = number_1 + number_2;: Adds number_1 and number_2 and stores the
result in the sum variable.
5. printf("Res = %d\n", sum);: Displays the value of sum using %d.

What is %d in printf?

 %d:Format specifier used to print decimal (integer) values.


 Example:

int x = 25;
printf("The value of x is: %d\n", x);

Output:

The value of x is: 25

Other Common Format Specifiers:

Format Specifier Data Type Example Output


%d Signed integer (decimal) 25, -10
%u Unsigned integer 42
%f Floating-point number 3.14
%c Single character A
%s String (sequence of characters) Hello

Summary

1. Variables: Represent memory locations and store data of specific types.


2. Declaration and Initialization: Allocate memory and assign values to variables.
3. Updating Values: A variable’s value can be updated anytime after initialization.
4. printf with %d: Used to display integer values in a program.
Data Types in C

Data types in the C programming language are used to define the type of value a variable can
store. They also determine the memory size allocated to the variable and how the stored value
is interpreted.

Classification of Data Types

1. Primary Data Types


2. Derived Data Types
3. Enumeration Data Types
4. Void Data Type

I. Primary Data Types

These are the fundamental building blocks of data types in C:

1. int (Integer)

 Used to store integer values (whole numbers).


 Memory size: Typically 2 bytes (16 bits) or 4 bytes (32 bits) depending on the
machine.
 Range : -2,147,483,648 to 2,147,483,647
 Format specifier: %d
 Example:

int age = 21;

2. char (Character)

 Used to store a single character.


 Memory size: 1 byte (8 bits) in most compilers.
 Format specifier: %c
 Example:

char grade = 'A';

3. float

 Used to store decimal numbers with single precision, providing about 7 decimal digits of
precision.
 Memory size: 4 bytes (32 bits).
 Format specifier: %f
 Example:

float pi = 3.1415926;
4. double

 Used to store decimal numbers with double precision, , offering about 15-16 decimal
digits of precision and is generally used when higher accuracy is required.
 Memory size: 8 bytes (64 bits).
 Format specifier: %lf
 Example:

double precisionValue = 3.141592653589793;

II. Memory and Format Specifiers

Data Type Memory (Bytes) Format Specifier


int 2 or 4 %d
char 1 %c
float 4 %f
double 8 %lf

III. Data Type Qualifiers or Data Type Modifiers

In C, data type modifiers are the keywords used to modify the original sign or length/range of
values of normal data types.

Common qualifiers include:

Size Qualifier:

 short: Reduces the size of an integer.


 long: Increases the size of an integer.

Sign Qualifier:

 signed: Allows both positive and negative values.


 unsigned: Only allows positive values

Examples of Qualified Data Types

1. short int:
o Requires less memory than int , Requires : 2 bytes
o Range : -32,768 to 32,767
o Example:

short int smallNumber = 32767;


2. long int:
o Requires more memory than int , Requires : 4 or 8 bytes
o Example:

long int bigNumber = 2147483647;

Note : usually 8 bytes for long long.

3. unsigned int:
o Does not reserve a bit for the sign, doubling the positive range.
o unsigned integers are used to store values that are non-negative, meaning they
are either zero or positive.
o Range : 0 to 4,294,967,295
o Example:

unsigned int positiveOnly = 65535;

Modifier Combinations Examples:

 unsigned short int


 signed long int
 unsigned long long int

1. unsigned short int:

 Meaning: It is an unsigned integer type that occupies less memory than a standard
int (2 bytes).
 Range: It can store only positive values, ranging from 0 to 65535.

2. signed long int: or long int:

 Meaning: It is a signed integer type that typically occupies 4 bytes (32 bits), but its
size can vary depending on the platform (on some systems, it may be 8 bytes or 64
bits).
 Range: It can store both negative and positive values, typically ranging from
-2,147,483,648 to 2,147,483,647

3. unsigned long long int:

 Meaning: It is an unsigned integer type that typically occupies 8 bytes (64 bits).
 Range: It can store only positive values, typically ranging from
0 to 18,446,744,073,709,551,615
IV. Derived Data Types

Derived types are built using the primary data types:

 Arrays: Collection of elements of the same type.


 Pointers: Store the address of a variable.
 Structures: Group of variables of different types.
 Unions: Share the same memory location for multiple members.

V. Enumeration Data Types

Enumeration types (enum) are used to define a set of named integral constants.

 Example:

enum Colors { RED, GREEN, BLUE };


Colors favoriteColor = GREEN;

VI. Void Data Type

The void data type represents the absence of a value.

Additional Notes

1. Size Variation Across Machines:


o The size of data types like int, float, and double depends on the platform
and compiler.
o Typically:
 short int: 2 bytes
 long int: 4 or 8 bytes
 float: 4 bytes
 double: 8 bytes
2. Unsigned Types:
o Provide a larger range of positive values by using all bits for the magnitude.
3. Usage in Applications:
o Choose appropriate types and qualifiers to optimize memory usage and ensure
compatibility.
Size and Range of Data Types (Standard Values)

Data Type Size (Bytes) Range


char 1 -128 to 127 (signed)
unsigned char 1 0 to 255
int 4 -2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,967,295
short int 2 -32,768 to 32,767
unsigned short 2 0 to 65,535
long int 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 ~6 decimal places
double 8 ~15 decimal places
long double 16 ~19 decimal places

5. Example Program
#include <stdio.h>

int main() {
int a = 10;
float b = 3.14;
char c = 'A';
unsigned int d = 100;

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


printf("Float: %.2f\n", b);
printf("Character: %c\n", c);
printf("Unsigned Integer: %u\n", d);

return 0;
}
What do you mean by formatted Input? Explain in detail the prototype of scanf() function in c
including its argument list and return type. (KTU July 2021 – 2019 Scheme) – 7 Marks

Formatted Input in C

Formatted input refers to reading data from the user (or an input source) in a specific
structure or format defined by the programmer. The C function scanf provides this
functionality by allowing the programmer to specify a format string that dictates how the
input should be taken and stored in variables.

Prototype of scanf()

The prototype of scanf() is:

int scanf(format specifier, argument list);

Breakdown of Components

1. int (Return Type):


o The return type is an integer.
o It indicates the number of input items successfully matched and assigned.

It returns total number of Inputs Scanned successfully

o EOF (-1): Input stream ended or an error occurred.

2. const char *format (First Argument):


o It contains:
 Format specifiers like %d, %f, %c, etc.
o Example: "Enter %d and %f" tells scanf to expect an integer followed by a
float.
3. Argument List:
o A variable-length argument list that specifies the addresses of variables where
the input data will be stored.
o Example:

int x;
scanf("%d ", &x);
How scanf Works

1. Reads Input:
o Scans the input buffer and parses it according to the format string.
o Example: For %d, scanf skips whitespaces and reads the next integer.
2. Matches Format Specifiers:
o Interprets and converts the input based on the specifier.
o Example: %f reads a floating-point number, converts it to float, and assigns it
to the variable.
3. Assigns Values:
o Stores the converted values at the addresses provided.

Examples

1. Basic Example

#include <stdio.h>

int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num); // Reads an integer
printf("You entered: %d\n", num);
return 0;
}

2. Multiple Inputs

#include <stdio.h>

int main()
{
int a, b;
float c;
printf("Enter two integers and a float: ");
scanf("%d %d %f", &a, &b, &c);
printf("You entered: %d, %d, %.2f\n", a, b, c);
return 0;
}
Formatted and Unformatted Input/Output Functions in C

Explain formatted and unformatted I/O functions of C language with syntax and example. (June
2022 – 2019 Scheme) – 7 marks

Two types of I/O functions in C:

1. Formatted I/O Functions

2. Unformatted I/O Functions

1. Formatted I/O Functions

Formatted I/O functions allow inputs and outputs of various data types, including int, float, char,
etc., using format specifiers. These functions format the input and output according to specific
needs.

Example : printf() – Formatted Output function

Scanf() – Formatted Input function

They use format specifiers to define how data is displayed or accepted.

Functions in Formatted I/O

1. printf()

o Displays data on the console.

o Syntax:

o printf("Format Specifier", var1, var2, ..., varn);

2. scanf()

o Takes user input.

o Syntax:

o scanf("Format Specifier", &var1, &var2, ..., &varn);

o Example:

2. Unformatted I/O Functions

Unformatted I/O functions work only with character data and strings. They are not using any format
specifiers.

Why are they called unformatted I/O functions?

These functions lack formatting capabilities and directly deal with raw character data.
Functions in Unformatted I/O

1. getch()

The getch() function reads a single character input from the user without displaying it
on the console (echo-less input).
It does not require the user to press "Enter" after typing the character; the function
immediately returns the character as soon as a key is pressed. This function is declared in
conio.h
Syntax: char ch = getch();

Example:

#include <conio.h>
#include <stdio.h>
int main()
{
printf("Press any key: ");
char ch = getch();
printf("\nYou pressed: %c", ch);
return 0;
}
2. getche()

o Reads and echoes a character immediately.

o Syntax: char ch = getche();

3. getchar()

o Reads a single character. It is a part of standard library stdio.h

o Syntax: char ch = getchar();

Example:

#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: %c", ch);
return 0;
}
Output:

Enter a character: Z

You entered: Z

4. putchar()

o Outputs a single character.

o Syntax: putchar(variable_name);

5. gets()

o Reads a string from the user.

o Syntax: gets(char_array);

o Example:

#include <stdio.h>
int main() {
char name[50];
printf("Enter your name: ");
gets(name);
printf("Hello, %s!", name);
return 0;
}
Output:

Enter your name: Alice

Hello, Alice!

6. puts()

o Displays a string.

o Syntax: puts(identifier_name);
3. Formatted I/O vs. Unformatted I/O

Feature Formatted I/O Unformatted I/O

Data Types Supported All data types Only character and strings

Allows formatting via


Formatting No formatting allowed
specifiers

Examples printf(), scanf() getch(), putchar()


Explain any four types of operators used in C. (June 2023) - 7 marks
Explain different operators in C.(January 2024) - 8 marks
Explain arithmetic, logical and bitwise operators with examples (July 2021) – 7 marks

OPERATORS IN C

In C programming, operators are symbols used to perform operations on operands (variables,


constants, or expressions). They form the building blocks of a program and are used for arithmetic
calculations, logical decision-making, and many other tasks.

1. Arithmetic operators.

2. Relational operators.

3. Logical operators.

4. Assignment operators.

5. Increment and decrement operators.

6. Conditional operators.

7. Bitwise operators.

8. Special operators.

1. Arithmetic Operators

 Used to perform basic mathematical operations.

a=7,b=3

a%b=7%3=1
Example program :

#include <stdio.h>

int main() {

int a = 10, b = 5;

int c;

c = -a;

// Unary operators

printf("Value of c: %d\n",c);

// Binary arithmetic operators

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); // %% to escape %

return 0;

2. Relational (Comparison) Operators

Used to compare two values. The result is either true (1) or false (0).
Example:
#include <stdio.h>

int main()
{
int a = 30, b = 4;
printf("%d",a>b);
return 0;
}

3. Logical operators:

Logical operators in C are used to perform logical operations, often involving conditional
expressions. They return a value of either true (1) or false (0) depending on the condition.
The logical operators && and || are used when we want to test more than one condition and
make decisions.

#include <stdio.h>

int main()
{
int a = 30, b = 4;
printf("%d",(a>b && a>10 && b<5 && a==30));
return 0;
}

The logical NOT (!) operator inverts the logical value of an operand:

#include <stdio.h>

int main()
{
int a = 30, b = 0;
printf("%d",!(a>b));
return 0;
}
4. Assignment Operators

 Used to assign values to variables

Assignment operator is '='.

Compound Operators : +=, -=, *=, /=, %=

Compound operators are shorthand operators in C that perform an operation and assignment
in a single step. For example:

#include <stdio.h>
int main() {
int a = 10, b = 5;
a += b; // Equivalent to a = a + b
printf("After a += b, a = %d\n", a);
a -= b; // Equivalent to a = a - b
printf("After a -= b, a = %d\n", a);
a *= b; // Equivalent to a = a * b
printf("After a *= b, a = %d\n", a);
a /= b; // Equivalent to a = a / b
printf("After a /= b, a = %d\n", a);
a %= b; // Equivalent to a = a % b
printf("After a %%= b, a = %d\n", a);
return 0;
}

5. Increment and Decrement Operators in C

C provides two very useful operators that are not commonly found in many other languages:

1. Increment Operator (++)


2. Decrement Operator (--)

Definition

1. The increment operator (++) adds 1 to the operand. Eg : a++ , ++a


2. The decrement operator (--) subtracts 1 from the operand. Eg: a-- , --a
3. Both are unary operators (they operate on a single operand).
Types of Increment and Decrement

Statement Meaning
++a Pre-increment
a++ Post-increment
--a Pre-decrement
a-- Post-decrement

Behavior

1. Standalone Usage:
Both ++a and a++ (or --a and a--) behave the same when used as standalone
statements.

Example:

int a = 5;
++a; // Increments a to 6
a++; // Increments a to 7

2. In Expressions (RHS of Assignment): The behavior differs when used in an


assignment or expression.

Example Table:

Statement Meaning Explanation


b = ++a; Pre-increment First increments a by 1, then assigns the value of a to b.
b = a++; Post-increment First assigns the value of a to b, then increments a by 1.
b = --a; Pre-decrement First decrements a by 1, then assigns the value of a to b.
b = a--; Post-decrement First assigns the value of a to b, then decrements a by 1.

Examples

#include<stdio.h>
int main() {
int a = 5, b;
b = ++a; // Pre-increment: a becomes 6, then b = 6
printf("a = %d, b = %d\n", a, b);
b = a--; // Post-decrement: b = 6, then a becomes 5
printf("a = %d, b = %d\n", a, b);
return 0;
}
6. Conditional operators.

Conditional operators in C are often referred to as ternary operator because they take three
operands. The syntax and use of the conditional operator (?:) provide a short way to perform
simple conditional checks and assignments.

Syntax:
condition ? expression1 : expression2;

How It Works:

1. condition: An expression that evaluates to either true (non-zero) or false (zero).


2. expression1: The value that is returned if the condition is true.
3. expression2: The value that is returned if the condition is false.

#include <stdio.h>

int main()
{
int a = 10, b = 20;
int max;
// Using the conditional operator to find the maximum
max = (a > b) ? a : b;
printf("The maximum is: %d\n", max);
return 0;
}

7. Bitwise operators

Bitwise operators are used to perform operations on the binary representations of integers.
1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of
two numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and
the second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and
the second operand decides the number of places to shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.

8. Special Operators

Comma Operator (,)

 Description: Allows multiple expressions to be evaluated in a single statement.

sizeof Operator

 Description: Returns the size (in bytes) of a data type or variable.


 Syntax:

sizeof(type or variable);

Pointer Operators (* and &)

 Description: Used for working with pointers.


o * (Dereference operator): Accesses the value stored at a pointer.
o & (Address-of operator): Returns the address of a variable.

dot operator (.)

 Description: Used to access members of a structure

Cast Operator

 Description: Used to explicitly convert one data type to another.

Syntax:

(type) expression;
Example:

float a = 5.5;

int b = (int)a; // Converts float to int

printf("%d", b); // Output: 5

What is type casting? Name the inbuilt functions available in C language. What is the difference
between type casting and type conversion? (UQ – July 2021)

Implicit Conversion (Type Promotion)

 Definition: Implicit conversion, also known as type promotion, occurs automatically


when the compiler converts a smaller data type into a larger data type or when it
adjusts data types for compatibility in expressions.
 Example:

#include <stdio.h>
int main() {
int a = 5;
float b = 2.5;
float result = a + b; // 'a' is implicitly converted to float
printf("Result: %.2f\n", result); // Output: 7.50
return 0;
}

Explicit Conversion (Type Casting)

 Definition: Explicit conversion, also called type casting, is done manually by the
programmer to convert one data type to another using the cast operator (type).
 Key Points:
o Performed manually by the programmer.
o Requires the cast operator (type).

 Example:

#include <stdio.h>
int main() {
float a = 5.7;
int b = (int)a; // Explicitly cast 'a' to int
printf("After casting: %d\n", b); // Output: 5
return 0;
}
Inbuilt Functions Available in C for Type Conversion

C provides a few standard library functions to help with explicit type conversions. Here are
some of the common ones:

 atof(): used to convert the data type string into the data type float.
 atoi():used to convert the data type string into the data type int.
 atbol():used to convert the data type string into the data type long.
 itoba():used to convert the data type int into the data type string.
 ltoa():used to convert the data type long into the data type string.

Difference Between Type Casting and Type Conversion

Feature Type Casting Type Conversion


Explicitly converting a variable from one data Implicit conversion done
Definition
type to another using the cast operator (type). automatically by the compiler.
Performed automatically by the
Control Performed manually by the programmer.
compiler.
Done using the cast operator (type) or specific Occurs during operations
Usage
conversion functions. involving mixed data types.
Adding int and float promotes
Example (int)3.5 converts 3.5 to 3.
int to float.
Explain any four types of operators used in C. (June 2023) - 7 marks
Explain different operators in C.(January 2024) - 8 marks
Explain arithmetic, logical and bitwise operators with examples (July 2021) – 7 marks

OPERATORS IN C

In C programming, operators are symbols used to perform operations on operands (variables,


constants, or expressions). They form the building blocks of a program and are used for arithmetic
calculations, logical decision-making, and many other tasks.

1. Arithmetic operators.

2. Relational operators.

3. Logical operators.

4. Assignment operators.

5. Increment and decrement operators.

6. Conditional operators.

7. Bitwise operators.

8. Special operators.

1. Arithmetic Operators

 Used to perform basic mathematical operations.

a=7,b=3

a%b=7%3=1
Example program :

#include <stdio.h>

int main() {

int a = 10, b = 5;

int c;

c = -a;

// Unary operators

printf("Value of c: %d\n",c);

// Binary arithmetic operators

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); // %% to escape %

return 0;

2. Relational (Comparison) Operators

Used to compare two values. The result is either true (1) or false (0).
Example:
#include <stdio.h>

int main()
{
int a = 30, b = 4;
printf("%d",a>b);
return 0;
}

3. Logical operators:

Logical operators in C are used to perform logical operations, often involving conditional
expressions. They return a value of either true (1) or false (0) depending on the condition.
The logical operators && and || are used when we want to test more than one condition and
make decisions.

#include <stdio.h>

int main()
{
int a = 30, b = 4;
printf("%d",(a>b && a>10 && b<5 && a==30));
return 0;
}

The logical NOT (!) operator inverts the logical value of an operand:

#include <stdio.h>

int main()
{
int a = 30, b = 0;
printf("%d",!(a>b));
return 0;
}
4. Assignment Operators

 Used to assign values to variables

Assignment operator is '='.

Compound Operators : +=, -=, *=, /=, %=

Compound operators are shorthand operators in C that perform an operation and assignment
in a single step. For example:

#include <stdio.h>
int main() {
int a = 10, b = 5;
a += b; // Equivalent to a = a + b
printf("After a += b, a = %d\n", a);
a -= b; // Equivalent to a = a - b
printf("After a -= b, a = %d\n", a);
a *= b; // Equivalent to a = a * b
printf("After a *= b, a = %d\n", a);
a /= b; // Equivalent to a = a / b
printf("After a /= b, a = %d\n", a);
a %= b; // Equivalent to a = a % b
printf("After a %%= b, a = %d\n", a);
return 0;
}

5. Increment and Decrement Operators in C

C provides two very useful operators that are not commonly found in many other languages:

1. Increment Operator (++)


2. Decrement Operator (--)

Definition

1. The increment operator (++) adds 1 to the operand. Eg : a++ , ++a


2. The decrement operator (--) subtracts 1 from the operand. Eg: a-- , --a
3. Both are unary operators (they operate on a single operand).
Types of Increment and Decrement

Statement Meaning
++a Pre-increment
a++ Post-increment
--a Pre-decrement
a-- Post-decrement

Behavior

1. Standalone Usage:
Both ++a and a++ (or --a and a--) behave the same when used as standalone
statements.

Example:

int a = 5;
++a; // Increments a to 6
a++; // Increments a to 7

2. In Expressions (RHS of Assignment): The behavior differs when used in an


assignment or expression.

Example Table:

Statement Meaning Explanation


b = ++a; Pre-increment First increments a by 1, then assigns the value of a to b.
b = a++; Post-increment First assigns the value of a to b, then increments a by 1.
b = --a; Pre-decrement First decrements a by 1, then assigns the value of a to b.
b = a--; Post-decrement First assigns the value of a to b, then decrements a by 1.

Examples

#include<stdio.h>
int main() {
int a = 5, b;
b = ++a; // Pre-increment: a becomes 6, then b = 6
printf("a = %d, b = %d\n", a, b);
b = a--; // Post-decrement: b = 6, then a becomes 5
printf("a = %d, b = %d\n", a, b);
return 0;
}
6. Conditional operators.

Conditional operators in C are often referred to as ternary operator because they take three
operands. The syntax and use of the conditional operator (?:) provide a short way to perform
simple conditional checks and assignments.

Syntax:
condition ? expression1 : expression2;

How It Works:

1. condition: An expression that evaluates to either true (non-zero) or false (zero).


2. expression1: The value that is returned if the condition is true.
3. expression2: The value that is returned if the condition is false.

#include <stdio.h>

int main()
{
int a = 10, b = 20;
int max;
// Using the conditional operator to find the maximum
max = (a > b) ? a : b;
printf("The maximum is: %d\n", max);
return 0;
}

7. Bitwise operators

Bitwise operators are used to perform operations on the binary representations of integers.
1. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of
two numbers. The result of AND is 1 only if both bits are 1.
2. The | (bitwise OR) in C takes two numbers as operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two bits is 1.
3. The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of
two numbers. The result of XOR is 1 if the two bits are different.
4. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and
the second operand decides the number of places to shift.
5. The >> (right shift) in C takes two numbers, right shifts the bits of the first operand, and
the second operand decides the number of places to shift.
6. The ~ (bitwise NOT) in C takes one number and inverts all bits of it.

Bitwise AND Operator - &

The output of bitwise AND is 1 if the corresponding bits of two operands is 1. If either bit of
an operand is 0, the result of corresponding bit is evaluated to 0.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bit Operation of 12 and 25


00001100
& 00011001
________
00001000 = 8 (In decimal)

Example:

#include <stdio.h>

int main() {

int a = 12, b = 25;


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

return 0;
}
Output

Output = 8

Bitwise OR Operator: |

The output of bitwise OR is 1 if at least one corresponding bit of two operands is 1. In C


Programming, bitwise OR operator is denoted by |.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise OR Operation of 12 and 25


00001100
| 00011001
________
00011101 = 29 (In decimal)

Example
#include <stdio.h>

int main() {

int a = 12, b = 25;


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

return 0;
}

Output

Output = 29
Bitwise XOR (exclusive OR) Operator: ^

The result of bitwise XOR operator is 1 if the corresponding bits of two operands are
opposite. It is denoted by ^.

12 = 00001100 (In Binary)


25 = 00011001 (In Binary)

Bitwise XOR Operation of 12 and 25


00001100
^ 00011001
________
00010101 = 21 (In decimal)

Example : Bitwise XOR


#include <stdio.h>

int main() {

int a = 12, b = 25;


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

return 0;
}
Run Code

Output

Output = 21
Bitwise Complement Operator: ~

Bitwise complement operator is a unary operator (works on only one operand). It


changes 1 to 0 and 0 to 1. It is denoted by ~.

35 = 00100011 (In Binary)

Bitwise complement Operation of 35


~ 00100011
________
11011100 = 220 (In decimal)

Example : Bitwise complement


#include <stdio.h>

int main() {

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


printf("Output = %d\n", ~-12);

return 0;
}

Output

Output = -36
Output = 11
8. Special Operators

Comma Operator (,)

 Description: Allows multiple expressions to be evaluated in a single statement.

Syntax of Comma Operator in C:

The comma operator, is represented by the comma sign (,) placed between the
expressions we want to evaluate. A simple sample syntax is shown below:

expr1, expr2, expr3…….

The expressions expr1, expr2, expr3, etc., represent a sequence of expressions


separated by commas.

This syntax uses the comma operator in C to combine multiple expressions within a
single statement.

Each expression is evaluated sequentially from left to right, and the result of the entire
sequence is the value of the rightmost expression (expr3 in this case).

Example Code:

#include<stdio.h>

int main(){
int y;
int a = (y=3,y+1);
printf("%d", a);

return 0;
}

sizeof Operator

 Description: Returns the size (in bytes) of a data type or variable.


 Syntax:

sizeof(type or variable);

Pointer Operators (* and &)

 Description: Used for working with pointers.


o * (Dereference operator): Accesses the value stored at a pointer.
o & (Address-of operator): Returns the address of a variable.
dot operator (.)

 Description: Used to access members of a structure

Cast Operator

 Description: Used to explicitly convert one data type to another.

Syntax:

(type) expression;

Example:

float a = 5.5;

int b = (int)a; // Converts float to int

printf("%d", b); // Output: 5


What is type casting? Name the inbuilt typecasting functions available in C language.
What is the difference between type casting and type conversion? July 2021 – 7 Marks
Typecasting in C (Explicit Conversion)
Typecasting is the process of converting one data type into another explicitly.
- Performed manually by the programmer using the cast operator (type).
- Syntax: (type) expression.
Example 1: Integer to Float
int a = 10;
float b = (float)a / 3.0;
printf("%f", b); // Output: 3.333333

Example 2: Float to Integer


float x = 5.75;
int y = (int)x; // Explicitly cast 'x' to int
printf("%d", y); // Output: 5 (fractional part is discarded)

Example 3: Char to Integer


char ch = 'A'; // ASCII value of 'A' is 65
int a = (int)ch + 9; // Cast char to int
printf("%d", a); // Output: 74

Type Conversion (Implicit Conversion)


In type conversion, a data type is automatically converted into another data type by a
compiler at the compiler time.
- Performed automatically by the compiler.
- Happens when a smaller data type is converted to a larger data type (e.g., int to float).
Example:
int a = 5;
float b = 2.5;
float result = a + b; // 'a' is implicitly converted to float
printf("%f", result); // Output: 7.500000

Example with Mixed-Type Arithmetic


#include<stdio.h>
int main() {
int a = 5, b = 2;
float result;
// Without typecasting
result = a / b; // Integer division, result is 2.0
printf("Without typecasting: %f\n", result);
// With typecasting
result = (float)a / b; // Floating-point division
printf("With typecasting: %f\n", result);
return 0;
}
Output:
Without typecasting: 2.000000
With typecasting: 2.500000

Built-in Type Casting Functions in C Programming


C provides several built-in type casting functions to perform type casting in C
1. atof(): Converts a string to a double.
2. atoi(): Converts a string to an integer.
3. itoa(): Converts an integer to a string.
4. atoi(): Converts a binary string to an integer. These functions are particularly useful
when dealing with string-to-number or number-to-string conversions.
COMPARISON

Sl
.
TYPE CASTING TYPE CONVERSION
N
O

In type casting, a data type is converted into In type conversion, a data type is
1. another data type by a programmer using a converted into another data type by
casting operator. the compiler.

Type casting can be applied to both compatible Type conversion can only be applied to
2.
and incompatible data types. compatible data types.

A casting operator is required to explicitly No casting operator is needed for type


3.
perform type casting. conversion.

Type conversion is handled


Type casting is explicitly controlled by the
4. automatically by the compiler and
programmer and occurs at runtime.
occurs at compile time.
What is the importance of precedence and associativity? Write the table for operator
precedence (July 2021)

Write a C program that calculates and prints the result of the following expression:
result = 5 * (6 + 2) / 4 - 3. Explain how parentheses affect the precedence of operators in
this expression.(Model Question – 2024 Scheme)

Operator Precedence and Associativity in C

In C, operator precedence determines the order in which operators are evaluated in an


expression. Associativity defines how operators of the same precedence level are grouped
together—either left-to-right or right-to-left.

1. Operator Precedence in C

Operator precedence determines which operation is performed first when there are multiple
operators in an expression. Operators with higher precedence are evaluated before those
with lower precedence.

Precedence Table (Highest to Lowest)


Example 1: Multiplication vs Addition

int x = 15 + 20 * 3;
// '*' has higher precedence than '+', so evaluated as: 15 + (20 * 3) = 75

Parentheses Affect Precedence

In C, parentheses ( ) override operator precedence, ensuring that the enclosed expression is


evaluated first, regardless of the default precedence rules.

int y = (15 + 20) * 3;


// Parentheses override precedence: (15 + 20) * 3 = 105

2. Operator Associativity

If multiple operators of the same precedence level appear in an expression, associativity


determines the direction in which the operations are performed.

Types of Associativity

1. Left-to-Right Associativity: Operators at the same level are evaluated from left to right.
2. Right-to-Left Associativity: Operators at the same level are evaluated from right to left.

Example: Left-to-Right Associativity

int result = 10 - 4 - 2;
// Evaluated as: (10 - 4) - 2 = 4

Subtraction follows left-to-right associativity.


Example: Right-to-Left Associativity

int a = 10;
int b = 20;
int c = 30;
a = b = c; // Right-to-left: a = (b = c) → b gets 30, then a gets 30

Assignment (=) follows right-to-left associativity.

3. Examples of Operator Precedence and Associativity


#include <stdio.h>

int main() {
int a = 5, b = 10, c = 2, result;

result = a + b * c / 2 - 1 && b > c || a == c;

printf("Result: %d\n", result);


return 0;
}

// Evaluate
int a = 5, b = 10, c = 2, result;

result = a + b * c / 2 - 1 && b > c || a == c;

Multiplication (*) and Division (/) (Higher precedence, Left-to-Right)


b * c / 2 → 10 * 2 / 2 → 20 / 2 → 10

result = a + 10 - 1 && b>c || a == c

Addition (+) and Subtraction (-) (Left-to-Right)


a + 10 - 1 → 5 + 10 - 1 → 15 - 1 → 14

result = 14 && b>c || a == c

Relational Operator (b > c) (Higher than logical operators, Left-to-Right)


b > c → 10 > 2 → 1 (true)

result = 14 && 1 || a == c

Logical AND (&&) (Higher than ||, Left-to-Right)


14 && 1 → 1

result = 1 || a == c
Equality Operator (a == c)
a == c → 5 == 2 → 0 (false)

result = 1 || 0

Logical OR (||) (Lowest precedence, Left-to-Right)


1 || 0 → 1

Final output , result = 1

4. How to Control Precedence and Associativity

1. Use Parentheses () to explicitly define evaluation order.


2. Be aware of associativity when working with operators of the same precedence.
3. Avoid complex expressions that rely on precedence rules.

5. Summary

 Operator precedence determines which operation is performed first.


 Associativity determines whether operators at the same level are evaluated left-to-right or
right-to-left.
 Parentheses can override precedence to ensure correct evaluation order.

Write a C program that calculates and prints the result of the following expression:
result = 5 * (6 + 2) / 4 - 3. Explain how parentheses affect the precedence of operators in
this expression.(Model Question – 2024 Scheme)

#include <stdio.h>

int main() {
int result;

// Calculating the expression


result = 5 * (6 + 2) / 4 - 3;

// Printing the result


printf("Result: %d\n", result);

return 0;
}
Parentheses can override precedence to ensure correct evaluation order.

Step-by-Step Calculation:

1. Parentheses first: 6+2=8


2. Multiplication (*) next: 5×8=40
3. Division (/) follows: 40÷4=10
4. Subtraction (-) last: 10−3=7

✅ Final Output:

Result: 7
Control Statements in C
Introduction
Control statements in C determine the flow of execution in a program. These statements
allow programmers to make decisions, loop through code, and jump to different parts of a
program based on conditions.

Types of Control Statements

Control statements in C are classified into three main categories:

1. Decision-Making Statements (Selection)


2. Looping Statements (Iteration)
3. Jump Statements (Control Transfer)

1. Decision-Making Statements (Selection Statements)


These statements allow the execution of a particular block of code based on a condition.

1.1 if Statement

The if statement executes a block of code only if the given condition is true.

Syntax:

if (condition)
{
// Code to execute if the condition is true
}

Example:

#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.\n");
}
return 0;
}
1.2 if-else Statement

The if-else statement provides an alternative block of code if the condition is false.

Syntax:

if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}

Example:

#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.");
}
else
{
printf("Number is negative.");
}
return 0;
}
1.3 if-else-if Ladder

This statement is used when there are multiple conditions to check.

Syntax:

if (condition1)
{
// Code for condition1
}
else if (condition2)
{
// Code for condition2
}
else
{
// Default block
}

Example:

#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.");
}
else if(num<0)
{
printf("Number is negative.");
}
else
{
printf("Number is Zero.");
}
return 0;
}
1.4 Nested if Statement

An if statement inside another if statement is called a nested if.

Example:

#include <stdio.h>
int main()
{
int temperature = 35;

if (temperature > 30)


{
if (temperature > 40)
{
printf("It's extremely hot outside.\n");
}

else
{
printf("It's a hot day.\n");
}
}
else
{
printf("The weather is pleasant.\n");
}

return 0;
}

Write a c program to read a character from the user and check whether it is a vowel or consonant.
(June 2022 – 2019 Scheme)

#include <stdio.h>

int main()
{
char ch;

// Read a character from the user


printf("Enter a character: ");
scanf("%c", &ch);

// Check if the character is a vowel (both uppercase and lowercase)


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
{
printf("The character %c is a vowel.\n", ch);
}
// Check if it is an alphabet but not a vowel (i.e., consonant)
else if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
{
printf("The character %c is a consonant.\n", ch);
}
else
{
printf("Invalid input! Please enter an alphabet.\n");
}

return 0;

1.5 switch Statement

The switch statement is used when there are multiple choices, and execution depends on the
value of a variable.

Syntax:

switch(expression)
{
case value1:
// Code for case 1
break;

case value2:
// Code for case 2
break;

default:
// Default case (optional)
}

Example:

#include <stdio.h>
int main()
{
char signal;
printf("Enter a character : ");
scanf("%c",&signal);
switch(signal) {
case 'R':
printf("Stop\n");
break;
case 'Y':
printf("Get Ready\n");
break;
case 'G':
printf("Go\n");
break;
default:
printf("Invalid Signal\n");
}
return 0;
}
Write a c program to implement basic arithmetic operations of a calculator using switch
constructs. (May 2024 – 2019 scheme)

#include <stdio.h>

int main() {
double num1, num2, result;
char op;

printf("Enter first number: ");


scanf("%lf", &num1);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &op);
printf("Enter second number: ");
scanf("%lf", &num2);

switch(op) {
case '+':
result = num1 + num2;
printf("Result: %.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case '/':
if (num2 != 0)
printf("Result: %.2lf / %.2lf = %.2lf\n", num1, num2, num1
/ num2);
else
printf("Error! Division by zero is not allowed.\n");
break;
default:
printf("Invalid operator!\n");
}

return 0;
}

Write a menu driven program to find the area of square,triangle,circle and rectangle according to
the choice given. (June 2023 – 2019 Scheme)

#include <stdio.h>
#include <math.h>

int main() {
int choice;
double area, side, base, height, radius, length, width;

// Display menu options


printf("1. Area of Square\n");
printf("2. Area of Triangle\n");
printf("3. Area of Circle\n");
printf("4. Area of Rectangle\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1: // Square
printf("Enter the side length of the square: ");
scanf("%lf", &side);
area = side * side;
printf("Area of Square: %.2lf\n", area);
break;

case 2: // Triangle
printf("Enter the base and height of the triangle: ");
scanf("%lf %lf", &base, &height);
area = 0.5 * base * height;
printf("Area of Triangle: %.2lf\n", area);
break;

case 3: // Circle
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
area = M_PI* radius * radius; // Using M_PI from math.h
printf("Area of Circle: %.2lf\n", area);
break;

case 4: // Rectangle
printf("Enter the length and width of the rectangle: ");
scanf("%lf %lf", &length, &width);
area = length * width;
printf("Area of Rectangle: %.2lf\n", area);
break;

default:
printf("Invalid choice! Please enter a number between 1 and
4.\n");
}

return 0;}
Control Statements in C
Introduction
Control statements in C determine the flow of execution in a program. These statements
allow programmers to make decisions, loop through code, and jump to different parts of a
program based on conditions.

Types of Control Statements

Control statements in C are classified into three main categories:

1. Decision-Making Statements (Selection)


2. Looping Statements (Iteration)
3. Jump Statements (Control Transfer)

1. Decision-Making Statements (Selection Statements)


These statements allow the execution of a particular block of code based on a condition.

1.1 if Statement

The if statement executes a block of code only if the given condition is true.

Syntax:

if (condition)
{
// Code to execute if the condition is true
}

Example:

#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.\n");
}
return 0;
}
1.2 if-else Statement

The if-else statement provides an alternative block of code if the condition is false.

Syntax:

if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}

Example:

#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.");
}
else
{
printf("Number is negative.");
}
return 0;
}
1.3 if-else-if Ladder

This statement is used when there are multiple conditions to check.

Syntax:

if (condition1)
{
// Code for condition1
}
else if (condition2)
{
// Code for condition2
}
else
{
// Default block
}

Example:

#include <stdio.h>
int main()
{
int num;
printf("Enter a number : ");
scanf("%d",&num);
if (num > 0)
{
printf("Number is positive.");
}
else if(num<0)
{
printf("Number is negative.");
}
else
{
printf("Number is Zero.");
}
return 0;
}
1.4 Nested if Statement

An if statement inside another if statement is called a nested if.

Example:

#include <stdio.h>
int main()
{
int temperature = 35;

if (temperature > 30)


{
if (temperature > 40)
{
printf("It's extremely hot outside.\n");
}

else
{
printf("It's a hot day.\n");
}
}
else
{
printf("The weather is pleasant.\n");
}

return 0;
}

Write a c program to read a character from the user and check whether it is a vowel or consonant.
(June 2022 – 2019 Scheme)

#include <stdio.h>

int main()
{
char ch;

// Read a character from the user


printf("Enter a character: ");
scanf("%c", &ch);

// Check if the character is a vowel (both uppercase and lowercase)


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
{
printf("The character %c is a vowel.\n", ch);
}
// Check if it is an alphabet but not a vowel (i.e., consonant)
else if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
{
printf("The character %c is a consonant.\n", ch);
}
else
{
printf("Invalid input! Please enter an alphabet.\n");
}

return 0;

1.5 switch Statement

The switch statement is used when there are multiple choices, and execution depends on the
value of a variable.

Syntax:

switch(expression)
{
case value1:
// Code for case 1
break;

case value2:
// Code for case 2
break;

default:
// Default case (optional)
}

Example:

#include <stdio.h>
int main()
{
char signal;
printf("Enter a character : ");
scanf("%c",&signal);
switch(signal) {
case 'R':
printf("Stop\n");
break;
case 'Y':
printf("Get Ready\n");
break;
case 'G':
printf("Go\n");
break;
default:
printf("Invalid Signal\n");
}
return 0;
}
Write a c program to implement basic arithmetic operations of a calculator using switch
constructs. (May 2024 – 2019 scheme)

#include <stdio.h>

int main() {
double num1, num2, result;
char op;

printf("Enter first number: ");


scanf("%lf", &num1);
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &op);
printf("Enter second number: ");
scanf("%lf", &num2);

switch(op) {
case '+':
result = num1 + num2;
printf("Result: %.2lf + %.2lf = %.2lf\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf - %.2lf = %.2lf\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf * %.2lf = %.2lf\n", num1, num2, result);
break;
case '/':
if (num2 != 0)
printf("Result: %.2lf / %.2lf = %.2lf\n", num1, num2, num1
/ num2);
else
printf("Error! Division by zero is not allowed.\n");
break;
default:
printf("Invalid operator!\n");
}

return 0;
}

Write a menu driven program to find the area of square,triangle,circle and rectangle according to
the choice given. (June 2023 – 2019 Scheme)

#include <stdio.h>
#include <math.h>

int main() {
int choice;
double area, side, base, height, radius, length, width;

// Display menu options


printf("1. Area of Square\n");
printf("2. Area of Triangle\n");
printf("3. Area of Circle\n");
printf("4. Area of Rectangle\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1: // Square
printf("Enter the side length of the square: ");
scanf("%lf", &side);
area = side * side;
printf("Area of Square: %.2lf\n", area);
break;

case 2: // Triangle
printf("Enter the base and height of the triangle: ");
scanf("%lf %lf", &base, &height);
area = 0.5 * base * height;
printf("Area of Triangle: %.2lf\n", area);
break;

case 3: // Circle
printf("Enter the radius of the circle: ");
scanf("%lf", &radius);
area = M_PI* radius * radius; // Using M_PI from math.h
printf("Area of Circle: %.2lf\n", area);
break;

case 4: // Rectangle
printf("Enter the length and width of the rectangle: ");
scanf("%lf %lf", &length, &width);
area = length * width;
printf("Area of Rectangle: %.2lf\n", area);
break;

default:
printf("Invalid choice! Please enter a number between 1 and
4.\n");
}

return 0;}

2. Looping Statements (Iteration)


Looping statements allow executing a block of code multiple times.

2.1 while Loop

Used when the number of iterations is unknown but the loop must continue while a condition
is true.

Syntax:

while(condition)
{
// Code to execute
}
Example: 1

#include <stdio.h>
int main()
{
int i = 0;
while(i < 10)
{
printf("TechTalkz\n");
i++;
}
return 0;
}

Example: 2

#include <stdio.h>
int main()
{
int i = 5;
while(i >= 1)
{
printf("%d\n", i);
i--;
}
return 0;
}

2.3 do-while Loop

Executes at least once, then continues as long as the condition is true.

Syntax:

do
{
// Code to execute

} while(condition);

Example:

#include <stdio.h>
int main() {
int i = 1;
do
{
printf("%d ", i);
i++;
} while(i <= 5);
return 0;
}
2.1 for Loop

Used when the number of iterations is known.

Syntax:

for(initialization; condition; increment/decrement)


{
// Code to execute
}

Example:

#include <stdio.h>
int main()
{
for(int i = 1; i <= 5; i++)
{
printf("%d ", i);
}
return 0;
}

//Sum of First n Natural Numbers


#include <stdio.h>

int main()
{
int n;
printf("Enter n = ");
scanf("%d",&n);
int sum = 0;
for(int i = 1; i <= n; i++) {
sum += i; // sum = sum + i
}
printf("Sum = %d", sum);
return 0;
}
3. Jump Statements (Control Transfer)
Jump statements alter the normal flow of execution.

3.1 break Statement

Used to exit a loop or switch case immediately.

Example (in a loop):

#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
if(i == 3)
{
break;
}
printf("%d ", i);
}
return 0;
}

3.2 continue Statement

Skips the current iteration and proceeds to the next.

Example:

#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++)
{
if(i == 3)
{
continue;
}
printf("%d ", i);
}
return 0;
}
3.3 goto Statement

Jumps to a labeled statement in the program.

Example:

#include <stdio.h>

int main ()
{
int n = 0;
if (n == 0
{
goto end;
}
printf("The number is: %d\n", n);
end:printf ("End of program");
return 0;
}
Q. Write a c Program to find the sum of first and last digit of a
number.

#include<stdio.h>

int main()

int num,first,last,sum;

printf("Enter a number : ");

scanf("%d",&num);

last = num%10;

first = num;

while(first >=10)

first = first/10

sum = first+last;

printf("Sum = %d",sum);

return 0;

/*Write a C program check if a number is present in a given list of


numbers. If present, give location of the number otherwise insert the
number in the list at the end*/

#include<stdio.h>

int main()

int n,i,key,found =0;

//input the size of array


printf("Enter the number of elements : ");

scanf("%d",&n);

int arr[n+1]; // Provide extra space for inserting an element

printf("Enter %d elements : ",n);

for(i=0;i<n;i++)

scanf("%d",&arr[i]);

printf("Enter number to be searched : ");

scanf("%d",&key);

for(i=0;i<n;i++)

if(arr[i]==key)

found = 1;

printf("Number found at position %d : ",i+1);

break;

if(!found)

arr[n] = key;

n++;

printf("Updated list : ");

for(i=0;i<n;i++)

printf("%d ",arr[i]);
}

return 0;

You might also like