0% found this document useful (0 votes)
6 views71 pages

C Module 2 & 3 Notes

The document provides an overview of operators and expressions in C programming, detailing types of operators (unary, binary, ternary) and their usage in expressions. It explains arithmetic, relational, logical, and assignment operators, along with decision-making statements like if, if-else, and switch. Additionally, it covers type conversion, precedence, and associativity of operators, along with practical examples to illustrate these concepts.

Uploaded by

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

C Module 2 & 3 Notes

The document provides an overview of operators and expressions in C programming, detailing types of operators (unary, binary, ternary) and their usage in expressions. It explains arithmetic, relational, logical, and assignment operators, along with decision-making statements like if, if-else, and switch. Additionally, it covers type conversion, precedence, and associativity of operators, along with practical examples to illustrate these concepts.

Uploaded by

anupriyaag.aiml
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Module 2 Notes

OPERATORS AND EXPRESSIONS

INTRODUCTION
Operators are symbols that perform operations on data (variables/constants).
Expressions combine operands and operators to produce a result.
Example expression:
a+b*c
Here:
 operands → a, b, c
 operators → +, *
Key point
 Expressions are evaluated using precedence and associativity rules.
Example Program
#include <stdio.h>
int main() {
int a = 10, b = 5;
int result = a + b * 2; // multiplication happens first
printf("Result = %d", result);
return 0;
}

CLASSIFICATION BASED ON NUMBER OF OPERANDS


Types
1. Unary operator → operates on 1 operand
2. Binary operator → operates on 2 operands
3. Ternary operator → operates on 3 operands

Unary Operators
Examples
 ++a (pre-increment)
 a++ (post-increment)
 --a (pre-decrement)
 -a (negation)
Syntax
operator operand
or
operand operator
Example Program
#include <stdio.h>
int main() {
int x = 5;
printf("%d\n", ++x); // 6
printf("%d\n", x--); // prints 6, then x becomes 5
return 0;
}

Binary Operators
Examples
 Arithmetic → + - * / %
 Relational → < > <= >= == !=
 Logical → && ||
 Assignment → = += -=
Syntax
operand1 operator operand2
Example Program
#include <stdio.h>
int main() {
int a = 7, b = 3;
printf("Sum = %d\n", a + b);
printf("Product = %d\n", a * b);
return 0;
}

Ternary Operator
Syntax
condition ? expression1 : expression2
Meaning
 If condition is true → expression1 executes
 Else → expression2 executes
Example Program
#include <stdio.h>
int main() {
int n = 10;
(n % 2 == 0) ? printf("Even") : printf("Odd");
return 0;
}
CLASSIFICATION BASED ON TYPE OF OPERATION

Arithmetic Operators
Operators
Operator Meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus (remainder)
Important Rules
 / between two integers → integer division
 % allowed only for integers
 % gives remainder

Syntax
result = operand1 operator operand2;

Example Program
#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;
}

Conversion of Expressions
When an expression uses multiple data types, C converts lower-rank types into higher-rank
types automatically.
Type hierarchy
char → int → float → double
Example
int + float → float
float + double → double

Example Program
#include <stdio.h>
int main() {
int a = 5;
float b = 2.5;
float c = a + b; // a converted to float
printf("c = %.2f", c);
return 0;
}

Type Conversion
Two Types
1. Implicit conversion → automatic
2. Explicit conversion (type casting) → forced by programmer

1. Implicit Conversion
Automatically converts lower→higher type.
Example
int a = 10;
float b = a + 2.5; // a becomes 10.0

2. Explicit Conversion (Type Casting)


Syntax
(type) expression
Example Program
#include <stdio.h>
int main() {
int a = 7, b = 2;
float c = (float)a / b; // prevents integer division
printf("%.2f", c);
return 0;
}

Need for Explicit Type Conversion


Why Needed?
 Prevents loss of accuracy
 Avoid unwanted integer division
 Ensures correct result
Example
Without casting:
7/2=3
With casting:
(float)7 / 2 = 3.5

Example Program
#include <stdio.h>
int main() {
int x = 7, y = 2;

float wrong = x / y;
float correct = (float)x / y;
printf("Wrong = %.2f\n", wrong);
printf("Correct = %.2f\n", correct);

return 0;
}

Modes of Arithmetic Expressions


1. Integer Arithmetic
Both operands are integers → result is integer.
Example
5+2=7
5/2=2

2. Real Arithmetic
If at least one operand is float → result float.
Example
5 + 2.0 = 7.0

3. Mixed Arithmetic
C converts integer → float.

Example Program
#include <stdio.h>
int main() {
int a = 5;
float b = 2.0;
float c = a + b; // mixed arithmetic
printf("%f", c);
return 0;
}
Precedence of Arithmetic Operators
Order (Highest → Lowest)
1. ()
2. ++ --
3. * / %
4. + -

Example
a+b*c
Multiplication happens first.

Example Program
#include <stdio.h>
int main() {
int a = 2, b = 3, c = 4;
int result = a + b * c;
printf("%d", result); // 14
return 0;
}

Associativity of Operators
When operators have the same precedence, associativity decides the order.
Examples
Operators Associativity

+ - * / % Left → Right

= += -= Right → Left

Example Program
#include <stdio.h>
int main() {
int a = 10;
int b = 20;
int c = 30;

int result = a + b + c; // left to right


printf("%d", result);
return 0;
}
RELATIONAL OPERATORS

Relational operators compare two [Link] result is always 1 (true) or 0 (false).


List of Relational Operators
Operator Meaning

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

== Equal to

!= Not equal to

Syntax
expression1 operator expression2

Example
a>b
x == y
marks >= 35
Example Program
#include <stdio.h>
int main() {
int a = 10, b = 20;

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;
}
LOGICAL OPERATORS
Logical operators combine multiple conditions.
Logical Operators
Operator Meaning

&& Logical AND

! Logical NOT

🔹 Logical AND (&&)


True only when both conditions are true.
Example
(age > 18) && (marks >= 35)

🔹 Logical OR (||)
True if any one condition is true.
Example
(temp > 40) || (rain == 1)
🔹 Logical NOT (!)
Reverses truth value.
Example
! (a == b)

Example Program
#include <stdio.h>
int main() {
int age = 20;
int marks = 30;
printf("AND = %d\n", (age > 18 && marks >= 35));
printf("OR = %d\n", (age > 18 || marks >= 35));
printf("NOT = %d\n", !(marks >= 35));

return 0;
}

ASSIGNMENT OPERATORS
Assignment operators assign values to variables.
List of Assignment Operators
Operator Meaning

= Simple assignment

+= Add and assign

-= Subtract and assign

*= Multiply and assign

/= Divide and assign

%= Modulus and assign

Syntax
variable operator value;
Examples:
a += 5; // same as a = a + 5;
b *= 3; // same as b = b * 3;
Example Program
#include <stdio.h>
int main() {
int a = 10;
a += 5; // now a = 15
a -= 3; // now a = 12
a *= 2; // now a = 24
a /= 4; // now a = 6
printf("Final Value of a = %d", a);
return 0;
}

DECISION MAKING AND BRANCHING

INTRODUCTION
Decision-making statements allow a program to choose different paths based on conditions.
These statements check conditions using relational and logical operators.
Example decisions:
 Is the number positive or negative?
 Which number is largest?
 Should a menu option run?
C supports the following decision statements:
1. if
2. if-else
3. nested if
4. else-if ladder
5. switch

SELECTION / BRANCHING STATEMENTS


Select one block of code among many based on conditions.
List:
1. if statement
2. if-else statement
3. nested if
4. else-if ladder
5. switch statement

THE IF STATEMENT (One-way selection)


IDENTIFY EVEN AND ODD NUMBER

if executes a block ONLY WHEN the condition is true.


Condition to check even:
n % 2 == 0

Syntax
if (condition) {
statements;
}
Example Program – Even/Odd
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
if (n % 2 == 0) {
printf("Even");
}
return 0;
}
If number is odd → no output (one-way selection).

PROGRAM TO FIND MAXIMUM OF TWO NUMBERS


Condition:
if (a > b)

Example Program
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);

if (a > b) {
printf("Largest = %d", a);
}
return 0;
}

FIND LARGEST OF 3 NUMBERS


Using nested if.

Example Program
#include <stdio.h>
int main() {
int a, b, c;
printf("Enter 3 numbers: ");
scanf("%d %d %d", &a, &b, &c);

if (a > b) {
if (a > c)
printf("Largest = %d", a);
else
printf("Largest = %d", c);
}
else {
if (b > c)
printf("Largest = %d", b);
else
printf("Largest = %d", c);
}
return 0;
}
CHECK WHETHER NUMBER IS POSITIVE OR NEGATIVE
Condition:
n>0

Example Program
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);

if (n > 0)
printf("Positive");
return 0;
}
Zero gives no message (one-way selection).

THE IF-ELSE STATEMENT (Two-way selection)


If condition is true → if block executes
Else → else block executes

Syntax
if (condition) {
statements;
}
else {
statements;
}

PROGRAM 1 – Check Even/Odd using if-else


#include <stdio.h>
int main() {
int n;
scanf("%d", &n);

if (n % 2 == 0)
printf("Even");
else
printf("Odd");
return 0;
}
PROGRAM 2 – Find Larger of Two Numbers
#include <stdio.h>
int main() {
int a, b;
scanf("%d %d", &a, &b);

if (a > b)
printf("Larger = %d", a);
else
printf("Larger = %d", b);

return 0;
}

PROGRAM 3 – Leap Year Check


Leap year logic:
(year % 400 == 0)
OR (year % 4 == 0 AND year % 100 != 0)
#include <stdio.h>
int main() {
int year;
scanf("%d", &year);

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


printf("Leap year");
else
printf("Not leap year");

return 0;
}

NESTED IF STATEMENT
Explanation
if inside another if
Used for multi-level decisions.

Syntax
if (condition1) {
if (condition2) {
statements;
}
}
Example – Find largest of 3 numbers (nested if)

ADVANTAGES & DISADVANTAGES


Advantages
 Accurate multi-layer checking
 Useful for hierarchical decisions
Disadvantages
 Code readability decreases
 Hard to maintain

ELSE-IF LADDER
Explanation
Used when multiple conditions must be checked.

Syntax
if (condition1)
statements;
else if (condition2)
statements;
else if (condition3)
statements;
else
default statements;
Example – Grade Based on Marks
#include <stdio.h>
int main() {
int marks;
scanf("%d", &marks);

if (marks >= 90)


printf("Grade A");
else if (marks >= 80)
printf("Grade B");
else if (marks >= 70)
printf("Grade C");
else
printf("Fail");

return 0;
}

FIND ROOTS OF A QUADRATIC EQUATION


Quadratic:
ax² + bx + c
Discriminant:
D = b*b - 4*a*c
Cases:
 D > 0 → Real & distinct
 D = 0 → Real & equal
 D < 0 → Imaginary
Program
#include <stdio.h>
#include <math.h>

int main() {
float a, b, c, D, r1, r2;

scanf("%f %f %f", &a, &b, &c);

D = b*b - 4*a*c;

if (D > 0) {
r1 = (-b + sqrt(D)) / (2*a);
r2 = (-b - sqrt(D)) / (2*a);
printf("Real and distinct roots: %.2f, %.2f", r1, r2);
}
else if (D == 0) {
r1 = r2 = -b / (2*a);
printf("Real and equal roots: %.2f", r1);
}
else {
printf("Imaginary roots");
}

return 0;
}

SIMPLE CALCULATOR USING IF-ELSE LADDER


#include <stdio.h>
int main() {
int choice, a, b;
scanf("%d %d %d", &choice, &a, &b);

if (choice == 1)
printf("%d", a + b);
else if (choice == 2)
printf("%d", a - b);
else if (choice == 3)
printf("%d", a * b);
else if (choice == 4)
printf("%d", a / b);
else
printf("Invalid choice");

return 0;
}
CHECK TRIANGLE TYPE
Conditions:
 Equilateral → a == b == c
 Isosceles → any two sides equal
 Scalene → all sides different

Program
#include <stdio.h>
int main() {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);

if (a == b && b == c)
printf("Equilateral");
else if (a == b || b == c || a == c)
printf("Isosceles");
else
printf("Scalene");

return 0;
}

SWITCH STATEMENT

Used when decision depends on a single expression value.

Syntax
switch (expression) {
case value1: statements; break;
case value2: statements; break;
...
default: statements;
}

Rules
 Only int/char allowed
 break prevents fall-through
 default is optional

Example – Simple Calculator (Switch)


#include <stdio.h>
int main() {
int choice, a, b;
scanf("%d%d%d", &choice, &a, &b);

switch(choice) {
case 1: printf("%d", a + b); break;
case 2: printf("%d", a - b); break;
case 3: printf("%d", a * b); break;
case 4: printf("%d", a / b); break;
default: printf("Invalid choice");
}

return 0;
}

UNCONDITIONAL BRANCHING STATEMENTS

THE GOTO STATEMENT


Jumps to a labeled statement.
Not recommended (makes code confusing)

Syntax
goto label;
...
label:
statements;

Example
#include <stdio.h>
int main() {
int i = 1;

start:
printf("%d ", i);
i++;

if (i <= 5)
goto start;

return 0;
}

BREAK STATEMENT
Explanation
Used to exit:
 Loop
 Switch

Example
for (i = 1; i <= 10; i++) {
if (i == 5)
break;
}
CONTINUE STATEMENT
Explanation
Skips the remaining statements in loop and goes to next iteration.

Example
for (i = 1; i <= 5; i++) {
if (i == 3)
continue;
printf("%d ", i);
}

RETURN STATEMENT
Used to exit a function and optionally return a value.

Syntax
return value;

Example
int add(int a, int b) {
return a + b;
}

PROGRAMMING STYLE GUIDELINES


 Use meaningful names
 Proper indentation
 Comments for clarity
 Avoid too many nested structures
 Keep code modular

REPETITION (LOOPING)
Loops allow executing a block of code multiple times.
C provides:
1. while
2. for
3. do-while

CONCEPT OF A LOOP

A loop repeats a set of statements until a condition becomes false.


Types of loops:
1. Entry-controlled loops
 Condition tested before executing loop body
 while
 for
2. Exit-controlled loop
 Condition tested after executing loop body
 do-while (runs at least once)

General Syntax (All loops)


initialization;
while(condition) {
statements;
increment/decrement;
}

THE WHILE STATEMENT


Explanation
 Entry-controlled loop
 Executes only when condition is true
Syntax
while (condition) {
statements;
}

SUM OF NATURAL NUMBERS


Program
Sum of 1 to n.
#include <stdio.h>
int main() {
int n, i = 1, sum = 0;
scanf("%d", &n);

while(i <= n) {
sum += i;
i++;
}

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


return 0;
}
SUM OF SERIES 1 + x + x² + x³ + … + xⁿ
Logic
Use loop to calculate powers of x.
Program
#include <stdio.h>
int main() {
int x, n, i;
float sum = 1, term = 1;

scanf("%d %d", &x, &n);


for(i = 1; i <= n; i++) {
term = term * x;
sum += term;
}

printf("Sum = %.2f", sum);


return 0;
}
SUM OF INTEGERS READ FROM KEYBOARD
Continue reading until user enters 0.
Program
#include <stdio.h>
int main() {
int n, sum = 0;

printf("Enter numbers (0 to stop):\n");

scanf("%d", &n);
while(n != 0) {
sum += n;
scanf("%d", &n);
}

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


return 0;
}

PRINT NUMBERS FROM 1 TO 100


#include <stdio.h>
int main() {
int i = 1;

while(i <= 100) {


printf("%d ", i);
i++;
}

return 0;
}
REVERSE A GIVEN NUMBER
Logic:
 Extract digit using % 10
 Build reversed number
Program
#include <stdio.h>
int main() {
int n, rev = 0, digit;
scanf("%d", &n);
while(n > 0) {
digit = n % 10;
rev = rev * 10 + digit;
n /= 10;
}

printf("Reversed = %d", rev);


return 0;
}
CHECK FOR PALINDROME (INTEGER)
Palindrome: number == reversed number.
Program
#include <stdio.h>
int main() {
int n, temp, rev = 0, digit;
scanf("%d", &n);

temp = n;

while(temp > 0) {
digit = temp % 10;
rev = rev * 10 + digit;
temp /= 10;
}

if(n == rev)
printf("Palindrome");
else
printf("Not Palindrome");

return 0;
}

SUM OF DIGITS OF A NUMBER


#include <stdio.h>
int main() {
int n, sum = 0, digit;
scanf("%d", &n);

while(n > 0) {
digit = n % 10;
sum += digit;
n /= 10;
}

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


return 0;
}

BINARY TO DECIMAL CONVERSION


Logic:
Binary digits processed from right to left.
Program
#include <stdio.h>
#include <math.h>

int main() {
int bin, dec = 0, i = 0, digit;
scanf("%d", &bin);

while(bin > 0) {
digit = bin % 10;
dec += digit * pow(2, i);
i++;
bin /= 10;
}

printf("Decimal = %d", dec);


return 0;
}
DECIMAL TO BINARY CONVERSION
Logic:
Repeated division by 2 and store remainder.

#include <stdio.h>
int main() {
int n, bin = 0, place = 1, rem;
scanf("%d", &n);

while(n > 0) {
rem = n % 2;
bin += rem * place;
place *= 2;
n /= 2;
}

printf("Binary = %d", bin);


return 0;
}
GCD AND LCM (Euclid’s Algorithm)
GCD Logic:
while (b != 0)
r=a%b
a=b
b=r

Program
#include <stdio.h>
int main() {
int a, b, x, y, r;
scanf("%d %d", &a, &b);
x = a; y = b;

while(b != 0) {
r = a % b;
a = b;
b = r;
}

int gcd = a;
int lcm = (x * y) / gcd;

printf("GCD = %d\nLCM = %d", gcd, lcm);


return 0;
}

THE FOR STATEMENT


Explanation
Used when number of iterations is known.
Syntax
for(initialization; condition; increment) {
statements;
}

DISPLAY NUMBERS FROM 1 TO n


#include <stdio.h>
int main() {
int n, i;
scanf("%d", &n);

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


printf("%d ", i);
}

return 0;
}
DISPLAY ODD NUMBERS WITHIN n
for(i = 1; i <= n; i++) {
if(i % 2 != 0)
printf("%d ", i);
}

DISPLAY EVEN NUMBERS WITHIN n


for(i = 1; i <= n; i++) {
if(i % 2 == 0)
printf("%d ", i);
}

DISPLAY ODD AND EVEN NUMBERS SIDE BY SIDE


#include <stdio.h>
int main() {
int n, i;

scanf("%d", &n);
printf("Odd\tEven\n");

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


printf("%d\t%d\n", i, i + 1);
i++;
}

return 0;
}
DISPLAY NUMBERS FROM n DOWN TO 1
for(i = n; i >= 1; i--) {
printf("%d ", i);
}
COMPARISON OF WHILE LOOP AND FOR LOOP
while →
 Condition before loop
 Used when number of iterations unknown
for →
 All 3 parts (init, condition, increment) in one line
 Best when iterations are fixed

7.3.7 SUM OF FIRST NATURAL NUMBERS


sum = n * (n + 1) / 2;
OR using loop:
sum += i;

SUM OF SQUARES OF FIRST n NATURAL NUMBERS


sum += i * i;

SUM EVEN AND ODD NUMBERS USING TWO LOOPS


Program
int even = 0, odd = 0;

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


if(i % 2 == 0)
even += i;

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


if(i % 2 != 0)
odd += i;

SUM EVEN & ODD USING A SINGLE LOOP


for(i = 1; i <= n; i++) {
if(i % 2 == 0)
even += i;
else
odd += i;
}

FACTORIAL OF A NUMBER
Program
int fact = 1;
for(i = 1; i <= n; i++)
fact *= i;

VARIATIONS IN FOR LOOP


C allows:
 missing initialization
 missing condition (infinite loop)
 missing increment part
Example
for( ; ; ) // infinite loop

SUM OF INTEGERS BETWEEN n1 AND n2 DIVISIBLE BY 5


for(i = n1; i <= n2; i++)
if(i % 5 == 0)
sum += i;

FIND SQUARE ROOT OF A NUMBER


Using Newton–Raphson method or sqrt().
printf("%.2f", sqrt(n));

PRINT N FIBONACCI NUMBERS


int a = 0, b = 1, next;

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


printf("%d ", a);
next = a + b;
a = b;
b = next;
}

NESTED LOOPS
Used for:
 Patterns
 Multiplication tables
 Matrix operations
Example
for(i = 1; i <= 3; i++) {
for(j = 1; j <= 3; j++) {
printf("%d ", j);
}
printf("\n");
}

DO-WHILE LOOP
Syntax
do {
statements;
} while(condition);
Always executes at least once.

DIFFERENCE BETWEEN WHILE AND DO-WHILE


while do-while

condition checked first body runs first

may run 0 times runs minimum once

SUM OF NATURAL NUMBERS USING DO-WHILE


do {
sum += i;
i++;
} while(i <= n);

Module 3 Notes
ARRAYS

CONCEPT OF ARRAYS (Why Arrays?)


An array is a collection of multiple values of the same data type stored in contiguous
memory locations, accessed using an index.
Why arrays?
Without arrays:
 You would create individual variables: marks1, marks2, marks3, …
 Hard to manage with loops
 Harder for large data (100, 1000 values)
With arrays:
int marks[100];
 Easy to store large datasets
 Easy to loop
 Memory is continuous
 Index begins at 0
Memory Diagram (Example)
int a[5] = {10,20,30,40,50};

Index: 0 1 2 3 4
Value: 10 20 30 40 50
Address:100 102 104 106 108 (example)

Why arrays make life easier


#include <stdio.h>
int main() {
int a[5], i;

printf("Enter 5 numbers: ");


for(i = 0; i < 5; i++)
scanf("%d", &a[i]);
printf("You entered: ");
for(i = 0; i < 5; i++)
printf("%d ", a[i]);

return 0;
}

CLASSIFICATION OF ARRAYS
There are two types:
1️⃣ Single-dimensional arrays
2️⃣ Two-dimensional arrays (Chapter continues later)
SINGLE-DIMENSIONAL ARRAYS

A linear arrangement of elements.


General Syntax
data_type array_name[size];
Example:
int marks[50];
float prices[10];
char letters[100];
Accessing elements
array_name[index]

Program (Input + Output array)


#include <stdio.h>
int main() {
int a[5], i;

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


scanf("%d", &a[i]);
for(i = 0; i < 5; i++)
printf("%d ", a[i]);

return 0;
}

DECLARATION OF SINGLE-DIMENSIONAL ARRAYS


Syntax:
data_type array_name[size];
Examples:
int age[10];
float sal[20];
char name[30];
Rules:
 Size must be positive integer
 Index range: 0 to size-1

Program – Declaring and accessing


#include <stdio.h>
int main() {
int age[3] = {20, 25, 30};

printf("%d", age[1]); // 25
return 0;
}

STORING VALUES IN ARRAYS


Values stored by:
 Direct assignment
 Using loops
 Using initialization lists
Direct assignment
a[0] = 10;
a[1] = 20;
Using loop
for(i = 0; i < n; i++)
scanf("%d", &a[i]);

INITIALIZATION OF SINGLE-DIMENSIONAL ARRAYS


Syntax:
data_type array_name[size] = {v1, v2, ... };
Example:
int a[5] = {10, 20, 30, 40, 50};
If fewer values are provided:
int a[5] = {1, 2}; // remaining become 0
Without specifying size:
int a[] = {1,2,3,4};

Program – Array initialization + display


#include <stdio.h>
int main() {
int a[] = {5, 10, 15, 20, 25};
int i;

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


printf("%d ", a[i]);
return 0;
}
INITIALIZING ALL SPECIFIED MEMORY LOCATIONS
int a[5] = {0};
Meaning:
a = {0, 0, 0, 0, 0}
PARTIAL ARRAY INITIALIZATION
int a[5] = {1, 2};
Result:
a = {1, 2, 0, 0, 0}

INITIALIZATION WITHOUT SIZE


int a[] = {10, 20, 30};
Compiler calculates size = 3.

ARRAY INITIALIZATION WITH A STRING


char name[] = "ANU";
Stored as:
'A' 'N' 'U' '\0'
ASSIGNING VALUES TO ARRAYS
Arrays cannot be assigned directly:
❌ Not allowed:
a = b;
✔ Allowed:
for(i=0;i<n;i++)
a[i] = b[i];

READING AND WRITING SINGLE-DIMENSIONAL ARRAYS


Reading:
for(i=0;i<n;i++)
scanf("%d", &a[i]);
Writing:
for(i=0;i<n;i++)
printf("%d", a[i]);

ARRAYS AND FUNCTIONS


Two ways:
Passing individual elements:
function(a[i]);
Passing whole array:
function(a, size);

Program – Passing whole array


#include <stdio.h>

void display(int a[], int n){


for(int i=0;i<n;i++)
printf("%d ", a[i]);
}

int main(){
int a[] = {1,2,3,4,5};
display(a,5);
}

PROGRAMMING EXAMPLES

Addition of N elements
int sum = 0;
for(i = 0; i < n; i++)
sum += a[i];

Sum of positive & negative numbers


Use if-condition.

Largest of N numbers
Use a loop to track max.

Fibonacci numbers using arrays


f[0] = 0; f[1] = 1;
f[i] = f[i-1] + f[i-2];

SEARCHING
Two methods.

LINEAR SEARCH (Sequential)


Check each element one-by-one.

Program
for(i=0;i<n;i++){
if(a[i] == key){
found = 1;
break;
}
}

BINARY SEARCH
Works only on sorted arrays.
Algorithm:
1. mid = (low + high)/2
2. If key == a[mid] → found
3. If key < a[mid] → search left
4. Else → search right

BUBBLE SORT
Repeatedly compare adjacent values and swap.

EVALUATE POLYNOMIAL (Horner’s Method)


value = (((a0)x + a1)x + a2)x + …

TWO-DIMENSIONAL ARRAYS
Matrix form.
Syntax:
int a[3][3];

DECLARATION OF 2-D ARRAYS


data_type array_name[row][col];

INITIALIZATION OF 2-D ARRAYS


int a[2][2] = {{1,2},{3,4}};

ADDITION OF TWO MATRICES


Element-wise addition:
c[i][j] = a[i][j] + b[i][j];

PRODUCT OF TWO MATRICES


Use nested loops:
c[i][j] += a[i][k] * b[k][j];

STRING CONCEPTS
What is a string?
A sequence of characters terminated by '\0'.
Example:
char name[] = "ANU";
Stored as:
'A' 'N' 'U' '\0'
Why strings?
 To store text
 Used for names, addresses, messages
Key Points:
 String length does not include '\0'
 String size must include space for '\0'

DECLARING A STRING VARIABLE


Syntax:
char string_name[size];
Examples:
char name[20];
char city[50];
char ch[5] = {'H','e','l','l','o'}; // ❌ no '\0' → NOT a proper string
char ch2[6] = {'H','e','l','l','o','\0'}; // ✔ correct

Initializing Strings
Method 1: Using double quotes (recommended)
char name[] = "Anu";
Compiler automatically adds '\0'.
Method 2: Using character array
char name[4] = {'A','n','u','\0'};
Method 3: Empty initialization
char s[50] = "";

STRING INPUT/OUTPUT FUNCTIONS

Formatted input: scanf()


Syntax:
scanf("%s", string_var);
Limitation:
 Stops at space
Example:
Input: Anu Girish
Stored: "Anu"

Program
#include <stdio.h>
int main() {
char name[20];
scanf("%s", name);
printf("Name = %s", name);
return 0;
}

String conversion code %s


Used in:
printf("%s", str);
scanf("%s", str);
fprintf(file,"%s",str);

Edit set conversion code


To accept strings with spaces:
scanf("%[^\n]", str);
Meaning: read until newline.
Example:
Enter sentence: I love coding
Stored: "I love coding"

INPUT/OUTPUT FUNCTIONS FOR STRINGS

Token-Oriented I/O: scanf(), printf()


 Input until space
 Output entire string

10.4.2 Line-Oriented I/O: gets() and puts()


⚠️gets() is unsafe
Modern C uses fgets().
Syntax:
gets(str);
puts(str);
Example:
char msg[50];
gets(msg);
puts(msg);

10.4.3 getchar() and putchar()


Reads or prints a single character.
char c = getchar();
putchar(c);

10.4.4 getch(), getche(), putch()


Used in older compilers (Turbo C).

10.4.5 Testing the type of character


Functions:
isdigit(c)
isalpha(c)
islower(c)
isupper(c)
isspace(c)

10.4.6 Arrays of strings


A 2D character array:
char names[5][20];
Stores 5 strings, each max 19 chars + '\0'.

⭐ 10.5 STRING HANDLING FUNCTIONS (From <string.h>)

10.5.1 strlen() – String length


Counts characters until '\0'.
Syntax:
strlen(str);
Example:
strlen("ANU") → 3
Program:
#include <stdio.h>
#include <string.h>
int main() {
char s[] = "ANU";
printf("Length = %d", strlen(s));
}

10.5.2 strcpy() – Copy String


Copies source → destination.
Syntax:
strcpy(dest, src);
Program:
char a[20], b[20] = "Hello";
strcpy(a, b); // a = "Hello"

10.5.3 strlen() vs sizeof()


strlen("ABC") → 3
sizeof("ABC") → 4 (includes '\0')

10.5.4 strncpy() – Copy specified characters


Syntax:
strncpy(dest, src, n);

10.5.5 strcat() – Concatenate


strcat(dest, src);
Example:
"Hello" + "World" → "HelloWorld"

10.5.6 strncat() – Concatenate n characters


strncat(dest, src, n);
10.5.7 strcmp() – Compare strings
Syntax:
strcmp(s1, s2);
Return:
 0 → equal
 positive → s1 > s2
 negative → s1 < s2

10.5.8 strncmp() – Compare first n characters


strncmp(s1, s2, n);

⭐ 10.6 PROGRAMMING EXAMPLES

10.6.1 Reverse a string – strrev()


Manual logic:
swap characters from ends until middle.

Program:
#include <stdio.h>
#include <string.h>

int main() {
char s[50];
gets(s);

strrev(s);
printf("%s", s);
return 0;
}
10.6.2 Palindrome string
"madam" → palindrome
Program:
#include <stdio.h>
#include <string.h>

int main() {
char s[50];
gets(s);

char temp[50];
strcpy(temp, s);
strrev(temp);

if(strcmp(s, temp) == 0)
printf("Palindrome");
else
printf("Not Palindrome");
}

10.6.3 Read line and return length


gets(str);
printf("%d", strlen(str));

10.6.5 Remove all occurrences of a character


Logic:
Copy only characters != target.

10.6.7 Count number of 1’s in integer


Convert integer to string, count '1'.
10.6.8 Count vowels & consonants
Check using:
if(str[i] == 'a' || str[i] == 'e' ...)

10.6.9 Convert uppercase <-> lowercase


Using:
toupper()
tolower()

10.6.10 Count digits, spaces, others


Use isdigit(), isspace(), isalpha()

10.6.11 ASCII to integer


Use:
atoi(str);

10.6.12 Integer to ASCII


Use:
itoa(n, str, 10);

⭐ 10.7 USER-DEFINED STRING FUNCTIONS


(Functions written by programmer)

10.7.1 countchar(c, str)


Count occurrences of a character.

10.7.2 findchar(c, str)


Return position of character.

10.7.3 insertend(c, str)


Append character at end.

10.7.4 split string


Divide based on given position.

10.7.5 Search in array of strings


Loop compare string-by-string.

10.7.6 Function to return value of type char*


Return pointer to string.

10.7.7 atof() – ASCII to float


float x = atof("12.34");

🎉 CHAPTER 10 COMPLETED (Full Coverage)

⭐ If you want:
✔ A PDF of Chapter 9 & 10
✔ A combined textbook PDF (Chapter 4, 6, 7, 9, 10)
✔ Summary notes
✔ Flowcharts
✔ Question bank
✔ Programs-only booklet
Tell me what you want next.
You said:
programming examples for 10.6 and 10.7 nd for all subtopics
ChatGPT said:
Thought for 5s
Good — below are practical, ready-to-compile C programs covering every subtopic in
10.6 and 10.7 from your book.
Each item includes a short explanation, then a complete program you can paste into a C
compiler (gcc). I avoided unsafe gets() and non-standard strrev()/itoa() by implementing
equivalents.

10.6 — Programming examples (detailed programs)


10.6.1 — String reverse (implementing strrev)
Explanation: swap characters from ends until the middle.
/* reverse_string.c */
#include <stdio.h>
#include <string.h>

void reverse_str(char s[]) {


int i = 0, j = strlen(s) - 1;
while (i < j) {
char t = s[i];
s[i] = s[j];
s[j] = t;
i++; j--;
}
}

int main() {
char s[200];
printf("Enter a string: ");
if (!fgets(s, sizeof s, stdin)) return 0;
s[strcspn(s, "\n")] = '\0'; // remove newline
reverse_str(s);
printf("Reversed: %s\n", s);
return 0;
}

10.6.2 — Palindrome (string)


Explanation: reverse the string and compare.
/* palindrome_string.c */
#include <stdio.h>
#include <string.h>
#include <ctype.h>

void normalize(char *s) {


// optional: remove spaces and tolower for phrase palindrome
int i=0, j=0;
while (s[i]) {
if (!isspace((unsigned char)s[i])) s[j++] = tolower((unsigned char)s[i]);
i++;
}
s[j] = '\0';
}

void reverse_str(char s[]) {


int i=0, j=strlen(s)-1;
while(i<j){ char t=s[i]; s[i++]=s[j]; s[j--]=t; }
}

int main() {
char s[300], tmp[300];
printf("Enter string: ");
if(!fgets(s,sizeof s,stdin)) return 0;
s[strcspn(s,"\n")] = '\0';
strcpy(tmp, s);
normalize(tmp); // optional normalization
char rev[300];
strcpy(rev, tmp);
reverse_str(rev);
if(strcmp(tmp, rev) == 0) printf("Palindrome\n");
else printf("Not a palindrome\n");
return 0;
}

10.6.3 — Read a line and return the length (getline equivalent)


Explanation: use fgets and strlen.
/* getline_length.c */
#include <stdio.h>
#include <string.h>

int main() {
char line[1024];
printf("Enter a line: ");
if (!fgets(line, sizeof line, stdin)) return 0;
size_t len = strcspn(line, "\n"); // length without newline
printf("You entered (%zu chars): %.*s\n", len, (int)len, line);
return 0;
}

10.6.4 — Read set of text lines and print the longest


Explanation: read lines until EOF (Ctrl+D on Unix), track longest.
/* longest_line.c */
#include <stdio.h>
#include <string.h>

int main() {
char line[1024], longest[1024];
longest[0] = '\0';
printf("Enter lines (Ctrl+D to end):\n");
while(fgets(line, sizeof line, stdin)) {
if (strlen(line) > strlen(longest)) strcpy(longest, line);
}
if (longest[0]) {
longest[strcspn(longest, "\n")] = '\0';
printf("Longest line: %s\nLength: %zu\n", longest, strlen(longest));
} else {
printf("No input\n");
}
return 0;
}

10.6.5 — Remove all occurrences of a character: squeeze(s, c)


Explanation: copy only chars not equal to c.
/* squeeze.c */
#include <stdio.h>

void squeeze(char *s, char c) {


char *dst = s;
for (char *src = s; *src; ++src) {
if (*src != c) *dst++ = *src;
}
*dst = '\0';
}

int main() {
char s[200];
printf("Enter string: ");
if(!fgets(s,sizeof s,stdin)) return 0;
s[strcspn(s,"\n")] = '\0';
char ch;
printf("Character to remove: ");
if(scanf(" %c",&ch)!=1) return 0;
squeeze(s, ch);
printf("Result: %s\n", s);
return 0;
}

10.6.6 — Remove trailing blanks, tabs and newline: trim(s)


Explanation: remove leading/trailing whitespace (here implement trailing and leading).
/* trim.c */
#include <stdio.h>
#include <ctype.h>
#include <string.h>

void trim(char *s) {


// remove leading
char *start = s;
while(isspace((unsigned char)*start)) start++;
// shift left
if (start != s) memmove(s, start, strlen(start)+1);
// remove trailing
int i = strlen(s) - 1;
while(i >= 0 && isspace((unsigned char)s[i])) s[i--] = '\0';
}

int main() {
char s[300];
printf("Enter string with spaces/tabs: ");
if(!fgets(s,sizeof s,stdin)) return 0;
s[strcspn(s,"\n")] = '\0';
trim(s);
printf("Trimmed: '%s'\n", s);
return 0;
}

10.6.7 — Count number of 1's in integer


Explanation: count digit '1' in decimal representation.
/* count_ones.c */
#include <stdio.h>

int main() {
long long n;
printf("Enter integer: ");
if (scanf("%lld",&n)!=1) return 0;
if(n<0) n = -n;
int count = 0;
if(n==0) { printf("Number of '1's: 0\n"); return 0; }
while(n>0) {
if(n%10 == 1) count++;
n /= 10;
}
printf("Number of '1' digits: %d\n", count);
return 0;
}

10.6.8 — Count vowels and consonants


Explanation: traverse string, use isalpha.
/* vowels_consonants.c */
#include <stdio.h>
#include <ctype.h>

int main() {
char s[500];
printf("Enter text: ");
if(!fgets(s,sizeof s,stdin)) return 0;
int vowels=0, cons=0;
for (int i=0; s[i]; i++) {
char c = tolower((unsigned char)s[i]);
if (isalpha((unsigned char)c)) {
if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u') vowels++;
else cons++;
}
}
printf("Vowels: %d, Consonants: %d\n", vowels, cons);
return 0;
}

10.6.9 — Upper case to lower case and vice versa


Explanation: use toupper/tolower.
/* case_convert.c */
#include <stdio.h>
#include <ctype.h>

int main() {
char s[300];
printf("Enter text: ");
if(!fgets(s,sizeof s,stdin)) return 0;
for(int i=0; s[i]; ++i) {
if (islower((unsigned char)s[i])) s[i] = toupper((unsigned char)s[i]);
else if (isupper((unsigned char)s[i])) s[i] = tolower((unsigned char)s[i]);
}
printf("Converted: %s", s);
return 0;
}

10.6.10 — Count digits, white spaces and other characters


Explanation: use isdigit, isspace, isalpha.
/* count_types.c */
#include <stdio.h>
#include <ctype.h>

int main() {
char s[500];
printf("Enter text: ");
if(!fgets(s,sizeof s,stdin)) return 0;
int digits=0, spaces=0, others=0;
for(int i=0; s[i]; ++i) {
if (isdigit((unsigned char)s[i])) digits++;
else if (isspace((unsigned char)s[i])) spaces++;
else if (isalpha((unsigned char)s[i])) ; // ignore letter
else others++;
}
printf("Digits: %d, Spaces: %d, Others(punct): %d\n", digits, spaces, others);
return 0;
}

10.6.11 — Convert from ASCII to integer (atoi)


Explanation: use atoi (from <stdlib.h>) or implement own.
/* ascii_to_int.c */
#include <stdio.h>
#include <stdlib.h>

int main() {
char s[100];
printf("Enter number as string: ");
if(!fgets(s,sizeof s,stdin)) return 0;
s[strcspn(s,"\n")] = '\0';
int val = atoi(s); // note: atoi doesn't detect errors robustly
printf("Integer value = %d\n", val);
return 0;
}
If you want robust conversion, use strtol.

10.6.12 — Convert integer to ASCII string (itoa)


Explanation: itoa is non-standard; implement manual version.
/* int_to_ascii.c */
#include <stdio.h>
#include <string.h>

void my_itoa(int n, char s[]) {


int i = 0, sign = n;
if (n < 0) n = -n;
do {
s[i++] = (n % 10) + '0';
n /= 10;
} while (n > 0);
if (sign < 0) s[i++] = '-';
s[i] = '\0';
// reverse s
for (int j = 0, k = i - 1; j < k; j++, k--) {
char t = s[j]; s[j] = s[k]; s[k] = t;
}
}

int main() {
int num;
char s[50];
printf("Enter integer: ");
if(scanf("%d",&num)!=1) return 0;
my_itoa(num, s);
printf("String: %s\n", s);
return 0;
}

10.7 — User-defined string functions (each with example)


10.7.1 — Frequency of character in string: countchar(c, str)
/* countchar.c */
#include <stdio.h>

int countchar(const char *s, char c) {


int count = 0;
while (*s) { if (*s++ == c) count++; }
return count;
}

int main() {
char s[200], ch;
printf("Enter string: ");
if(!fgets(s,sizeof s,stdin)) return 0;
s[strcspn(s,"\n")] = '\0';
printf("Enter char to count: ");
if(scanf(" %c",&ch)!=1) return 0;
printf("Count = %d\n", countchar(s, ch));
return 0;
}

10.7.2 — Position of character findchar(c, str) (first occurrence)


Return index or -1.
/* findchar.c */
#include <stdio.h>

int findchar(const char *s, char c) {


for (int i = 0; s[i]; ++i)
if (s[i] == c) return i;
return -1;
}

int main() {
char s[200], ch;
printf("Enter string: ");
if(!fgets(s,sizeof s,stdin)) return 0;
s[strcspn(s,"\n")] = '\0';
printf("Char to find: ");
if(scanf(" %c",&ch)!=1) return 0;
int pos = findchar(s, ch);
if (pos >= 0) printf("Found at index %d (0-based)\n", pos);
else printf("Not found\n");
return 0;
}

10.7.3 — Insert a character at the end: insertend(c, str)


Append char and null-terminate.
/* insertend.c */
#include <stdio.h>
#include <string.h>

void insertend(char *s, char c, size_t maxlen) {


size_t len = strlen(s);
if (len + 1 < maxlen) {
s[len] = c;
s[len+1] = '\0';
}
}

int main() {
char s[200];
printf("Enter string: ");
if(!fgets(s,sizeof s,stdin)) return 0;
s[strcspn(s,"\n")] = '\0';
char ch;
printf("Char to append: ");
if(scanf(" %c",&ch)!=1) return 0;
insertend(s, ch, sizeof s);
printf("After append: %s\n", s);
return 0;
}

10.7.4 — Split the string into two parts: split(s, pos)


Split at given index.
/* split_string.c */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void split_at(char *s, int pos, char **part1, char **part2) {


int n = strlen(s);
if (pos < 0) pos = 0;
if (pos > n) pos = n;
*part1 = malloc(pos+1);
*part2 = malloc(n - pos + 1);
memcpy(*part1, s, pos);
(*part1)[pos] = '\0';
strcpy(*part2, s + pos);
}

int main() {
char s[300];
printf("Enter string: ");
if(!fgets(s,sizeof s,stdin)) return 0;
s[strcspn(s,"\n")] = '\0';
int pos; printf("Position to split at (0-based): "); if(scanf("%d",&pos)!=1) return 0;
char *a,*b;
split_at(s,pos,&a,&b);
printf("Part1: '%s'\nPart2: '%s'\n", a, b);
free(a); free(b);
return 0;
}
10.7.5 — Search for a string in an array of strings
Return index of match or -1.
/* search_string_array.c */
#include <stdio.h>
#include <string.h>

int find_in_array(char arr[][30], int n, const char *key) {


for (int i=0;i<n;i++) if (strcmp(arr[i], key)==0) return i;
return -1;
}

int main() {
char arr[5][30] = {"apple","banana","cat","dog","elephant"};
char key[30];
printf("Enter key to search: ");
if(!fgets(key, sizeof key, stdin)) return 0;
key[strcspn(key,"\n")] = '\0';
int idx = find_in_array(arr, 5, key);
if (idx >=0) printf("Found at index %d\n", idx);
else printf("Not found\n");
return 0;
}

10.7.6 — Function that returns value of type char *


Example: return a pointer to a dynamically created string.
/* make_greeting.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *make_greeting(const char *name) {
size_t n = strlen(name);
char *res = malloc(n + 10);
if (!res) return NULL;
sprintf(res, "Hello, %s", name);
return res; // caller must free
}

int main() {
char name[100];
printf("Enter name: ");
if(!fgets(name,sizeof name,stdin)) return 0;
name[strcspn(name,"\n")] = '\0';
char *g = make_greeting(name);
if (g) {
printf("%s\n", g);
free(g);
}
return 0;
}

10.7.7 — ASCII to float (atof)


Example using atof from <stdlib.h> (or strtod for robustness).
/* ascii_to_float.c */
#include <stdio.h>
#include <stdlib.h>

int main() {
char s[100];
printf("Enter float as string: ");
if (!fgets(s, sizeof s, stdin)) return 0;
s[strcspn(s,"\n")] = '\0';
double x = atof(s); // weak error checking
printf("Value = %f\n", x);
return 0;
}

You might also like