100% found this document useful (1 vote)
74 views399 pages

C Programming Complete Notes

The document provides an overview of programming, defining a program as a set of instructions for computers, and emphasizes the importance of learning programming languages for effective human-machine communication. It covers key concepts such as algorithms, syntax, data types, and the role of compilers, along with practical examples and explanations of programming fundamentals. Additionally, it discusses the significance of operating systems, variables, and operators in programming.

Uploaded by

hackerkali038
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
74 views399 pages

C Programming Complete Notes

The document provides an overview of programming, defining a program as a set of instructions for computers, and emphasizes the importance of learning programming languages for effective human-machine communication. It covers key concepts such as algorithms, syntax, data types, and the role of compilers, along with practical examples and explanations of programming fundamentals. Additionally, it discusses the significance of operating systems, variables, and operators in programming.

Uploaded by

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

❑ What is a Program?

•Definition: A program is a set of instructions that tells a computer what


tasks to perform.

•How It Works: Similar to a recipe guiding a chef, a program guides a


computer to complete actions step-by-step.

•Examples:
•Smartphone App: The app for a smart home system is a program that
lets you control lights or the thermostat from your phone.

•Remote Control for TV: The remote is like a program that sends
instructions to the TV to change channels, adjust volume, or turn on/off.

•Calculator App: A simple program that performs math operations when


you input numbers.
❑ Why We Need to Learn Programming Languages?

Definition: Programming is the way humans communicate with


computers, using special languages to give them instructions. Just like
we use words to communicate with each other, we use programming
languages (like Python, Java, or C++) to communicate with machines.

Example:
•Human-to-Human Communication: When we talk or text, we use
language to share information and ask each other to do things.

•Human-to-Machine Communication: With programming, we “talk” to


computers, telling them what to do, like instructing a robot to move or
telling an app to send a message.
❑ Why We Need to Communicate with Machine?
•Machines are like dumb devices; they require clear instructions to
function.

•By giving them commands, we can make them work efficiently


and accurately.

•Communication with machines helps automate repetitive tasks,


saving us time.

•It reduces the chance of human error, leading to better results.

•Machines can analyze data and solve complex problems faster


than humans.
❑ Can You Give a Program Directly to a
Machine?

NO
❑ Can You Give a Program Directly to a Machine?

Translator Machine
readable output
/complier
(0101010110)
❑ Can You Give a Program Directly to a Machine?

Machine Language:
•Definition: Binary code executed by the CPU.
•Challenges:
• Complex and hard to read.
• CPU-specific (not portable).
• Difficult to debug.

Alternatives:

•Assembly Language: Easier than machine language uses mnemonics.


•High-Level Languages: User-friendly (e.g., C, Python) compiled to machine
code.
❑ Learning a Programming Language:
• Definition: Understanding how to write code in a specific language.

• Key Aspects:
[Link]: Code structure and rules.
[Link]: Meaning of the code.
[Link] Structures: Ways to store data.
4. Control Structures: Managing code flow (loops, conditionals).
5. Problem-Solving: Implementing solutions with code.

• Benefits:
•Automation: Automate tasks.
•Software Development: Build applications.
•Career Opportunities: Jobs in tech fields.
❑ Why is Learning Programming Important?

Example: ATM User vs. ATM Programmer


1. ATM User:
•What They Do: Withdraw cash, check balance.
•Skills: Basic operations; no need for programming knowledge.

2. ATM Programmer:
•What They Do: Develop ATM software, design functions and security
features.
•Skills: Knowledge of programming languages, database management, and
technical skills.
❑ Every Programming Language to must have
Feature

Monitor

CPU

Keyboard

1) To read Fetch Input Coming From KeyBoard

2) Display Output On Screen


❑ Operating System:

Definition: Software that manages computer hardware and software resources,


providing common services for computer programs.

Platform Dependent OS
An operating system that is designed to work only on a specific type of
hardware or platform.

Examples:
Windows (x86/x64), macOS (Apple
hardware), and Android (ARM devices)
Linux.
❑ Windows

Translator .exe
/complier (runnable File)

The C program will compile to .exe file that can be run on Windows.
❑ Linux

Translator .out
/complier (runnable File)

The C program will compile to .out file that can be run on Linux.
❑ list of common file types along with their extensions
and associated software
❑ What is Algorithm:
An algorithm is a step-by-step set of instructions designed to perform a
specific task or solve a particular problem. In computer science, algorithms
are foundational for programming, guiding computers to execute tasks
efficiently and accurately.

❖ Example: Algorithm for Adding Two Numbers

•Start
•Take two numbers as input (A and B)
•Add the numbers: Sum = A + B
•Output the result: Sum
•End
❑ What is Syntax:
Syntax is the set of rules that defines the correct structure of code in a
programming language. It specifies how commands, keywords, and symbols
should be arranged.

❖ Example: In C, to print text


❖:
• printf("Hello, World!");
❑ What is Complier:
A compiler is a program that translates high-level code (like C, Java) into
machine code or binary code that a computer can understand and execute.

01001001010
0101010010100
complier machine
readable
Kickstart Your Coding: Installation and Setup Guide

• What’s an IDE and Why use one?


• why an IDE Makes Coding Easier
• How to set it up on windows
• How to get started on mac
❑ What’s an IDE and Why use one?
❑ why an IDE Makes Coding
Easier
❑ Basic Structure of a C Program

#include <stdio.h>

int main() {
printf(“Coding SeeKho");
return 0;
}
❑ .c vs .h extensions
❑ Recap:

❖ What is a program?
❖ Why do we need to learn programming languages?
❖ Why is it necessary to communicate with machines?
❖ Can we give a program directly to a machine?
❖ What are the components of learning a programming language?
❖ Why is learning programming important?
❖ What is an Operating System (OS)?
❖ What are platform-dependent operating systems?
❖ What’s an IDE, and why use one?
❖ What file extensions are generated when compiling a C program for
different operating systems?
❑ Variable

Being able to vary (change)

Example: Example :
y=3x
Email id:
x y=3x
Password: 1 3
2 6
3 9
❑ Variable just like container:

T =1 Rice Sugar Tea

T =2
Sugar Tea Rice
❑ How Variables are Stored in Memory

Identifier
a =10

Store 10
4001

10

Memory Address of a
❑ Key Rules for Identifiers in C:

•Allowed Characters: Identifiers can include letters (A-Z, a-z), digits (0-9), and underscores (_))

•Starting Character: They must start with a letter or an underscore. (e.g., count, _total )
.

•Case Sensitivity: Identifiers are case-sensitive, so Value and value are considered different .

•Reserved Words: Identifiers cannot be keywords (like int, return, for, etc.).
❑ Examples of Valid and Invalid Identifiers

•Valid: myVar, _temp, count2, max_value

•Invalid: 2ndValue (starts with a digit), int (a reserved word)

❑ Common Uses of Identifiers in C:

•Variable Names: int age;

•Function Names: void calculate();

•Array Names: int numbers[5];


Understanding the Need for Data Types in C :

Google Map: Your location

Choose destination

Atm Pin: abcd

1234
❑ Data Types in c

Primitive Derived user defined


int array structure
Float pointer union
char string enum
Void & other typedef
Signed short int
Short int
Unsigned short int

Signed int
int
Unsigned int

signed long int


Integer long int
Unsigned long int

Signed long long int


long long int
Unsigned long long int
1 n bit =2^n byte
0
8 bit=1byte=2^3

Data Type Typical Size (Bytes) Range (Signed) Range (Unsigned) Example (Signed) Example (Unsigned)
unsigned short x =
short int 2 –32,768 to 32,767 0 to 65,535 short int x = -32768;
65535;
–2,147,483,648 to unsigned int x =
int 4 0 to 4,294,967,295 int x = -2147483648;
2,147,483,647 4294967295;
–2,147,483,648 to
0 to 4,294,967,295
4 (or 8 on some 2,147,483,647 (or long int x = - unsigned long x =
long int (or larger on 8-byte
systems) larger on 8-byte 2147483648L; 4294967295UL;
systems)
systems)

unsigned long long
9,223,372,036,854,7 0 to long long x = -
x=
long long int 8 75,808 to 18,446,744,073,709, 9223372036854775
1844674407370955
9,223,372,036,854,7 551,615 807LL;
1615ULL;
75,807
n bit ( int/short/long int/long long int)

Unsigned: n bit =>2^n Values 0 to 2^n-1

Signed : n bit =>2^n Values

2^n -1 2^n-1

Range=-2^(n-1) to 2^(n-1)
Float

float double

long double
Data Type Size (bytes) Approximate Range Example

float 4 ±1.5 × 10⁻⁴⁵ to ±3.4 × 10³⁸ float a = 3.14f;

double b =
double 8 ±5.0 × 10⁻³²⁴ to ±1.7 × 10³⁰⁸
3.141592653589793;

long double c =
±3.4 × 10⁻⁴⁹³² to ±1.1 × 10⁴⁹³²
long double 8 (or 16 on some systems) 3.1415926535897932384
(depends on architecture)
62643383279502884L;
Signed

char

unsigned
Data Type Size (bytes) Range Example
–128 to 127 (or 0 to
char 1 255 if unsigned by char ch = 'A';
default)
signed char sch = -
signed char 1 –128 to 127
42;
unsigned char uch =
unsigned char 1 0 to 255
250;
Format Specifier Description Example
%d Signed integer printf("%d", -42);
%u Unsigned integer printf("%u", 42);
%f Floating-point number printf("%f", 3.14);
%c Single character printf("%c", 'A');
%s String of characters printf("%s", "Hello");
Hexadecimal integer
%x printf("%x", 255);
(lowercase)
%o Octal integer printf("%o", 8);
printf("%p",
%p Pointer address
(void*)&var);
printf("100%%
%% Percent sign
done");
❑ printf – printing output

•Printf is used to display text and variables on the screen.

• You provide a format string, which can include text and format
specifiers (like %d for integers, %f for floats, etc.) that tell printf how to
display the data.
•You need to provide format specifiers and variable addresses where the input data should

❑ scanf– reading input

•scanf is used to take input from the user and store it in


variables.

•You need to provide format specifiers and variable


addresses where the input data should be stored.
1. Which of the following is the correct way to declare an integer variable in C?
- A) int number = "10"
- B) float number = 10
- C) int number = 10
- D) char number = 10

2. What will be the output of the following code?

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

- A) a = 5
- B) a = %d
- C) a = a
- D) Error

3. Which format specifier is used to read a floating-point number using `scanf`?


- A) `%d`
- B) `%f`
- C) `%c`
- D) `%s`
4. What will be the output of the following code?

#include <stdio.h>
int main() {
int x = 10;
printf("%d %d %d\n", x, x++, ++x);
return 0;
}

- A) `10 11 11`
- B) `10 10 11`
- C) `10 11 12`
- D) Undefined behavior

5. Which of the following is a correct way to take an integer input from the user?
- A) `scanf("%d", age);`
- B) `scanf("%d", &age);`
- C) `scanf("%f", &age);`
- D) `printf("%d", &age);`

6. What is the size of a `char` data type in C?


- A) 1 bit
- B) 1 byte
- C) 2 bytes
- D) 4 bytes
Operator

10+20=30

operands
❑ Operators:
Operators are symbols that tell the compiler to perform specific
operations, such as mathematical, logical, or bitwise operations, on
data values. They act on variables or values to produce a result.

Example: In the expression a + b, the + symbol is an operator that


adds the values of a and b.

❑ Operands:

Operands are the values or variables on which the operator acts. In an


expression, operands are the data items that operators manipulate.
Example: In the expression a + b, a and b are operands, while + is the
operator acting on these operands.
❑ Expression Example with Operators and Operands:

Consider c = a + b * 2;
•Operators: =, +, *
•Operands: a, b, 2, and `c
❑ Types Of Operators:

OPERATORS

Unary Ternary Binary


(1 operands) (3 Operands) (2 Operands)

Arithmetic Logical Binary Relational


Operators Type
Unary
++,-- Unary Operator
operator
+,-*,/,% Arithmetic Operator
<,<=,>,>=,==,!= Relational operator
Binary &&,||,! Logical Operator
Operator &,|,<<,>>,-,^ Bitwise Operator
=,+=,-=,*=,%= Assignment Operator
Ternary ?:
Operator
Assignment Operator(=)

#include<stdio.h>
20
void main(){
10
int a=10;
a= 20;

}
a=b+c; valid
b=10 c=20

b+c=a;invalid

a=30
10=a
Lvalue=Rvalue

10=20
LHS

Variable Literal Expression


a=10 10=a a+b=10(invalid)
(valid) (invalid)

a= ; (RHS missing before ;)


=10;(Missing variable (LHS) )
a=10(;is Missing)
❖ Arithmetic Operators(+,-,*,%,/)

32

3+5*4

23
Precedence order:
% Modulas Operator

a % b : Remainder when a is Divided by b

14%5 =4
12%2=0
2%5=2
3%7=3

Note : Both Operand Must be int data type


otherwise error ex:1.2%2===check karo
Note 1: Both Operand Must be int data type otherwise error
ex:1.2%2===check karo

Note 2:Sign of result of % Operator is same as 1st Operand


Ex:-15%7=-1;
15%-7=1;
a=1+3*5 1+15=16

Example 1: Multiplication, Division, Modulus (*, /, % - Left to Right Associativity)

int result = 20 / 5 * 2 % 3;

Steps of Evaluation (Left to Right):


[Link]: 20 / 5 = 4
[Link]: 4 * 2 = 8
[Link]: 8 % 3 = 2
Answer:
result = 2
Behaviors of Operator => Operands

5/2= 2 =>both operands are Integer type


5.0/2=2.5 =>float,int=>float
5/2.0=2.5=>int,float=>float
5.0/2.0=>float ,float=>float
Use of operator:

153
Print last digit=153%10=3;
Print last two digit=153%100=53;

153
Print 2nd last digit=(153/10) %10=5;
❑ Concept of Swapping

Rice sugar
Swapping of number with
temp variable

➢ Swapping with a Temporary Variable


Before swapping
[Link]
[Link] two numbers, a and b
[Link] a in temp a=10 b=20
[Link] a = b
[Link] b = temp
[Link] the swapped values of a and b Afther swapping
[Link]
a=20 b=10
#include <stdio.h>

int main() {
int a, b, temp;

printf("Enter two numbers: ");


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

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

temp = a;
a = b;
b = temp;

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

return 0;
}
Swapping of number without
temp variable

➢ Swapping without a Temporary Variable Before swapping

•Start a=10 b=20


•Input two numbers, a and b
•Set a = a + b
•Set b = a - b Afther swapping
•Set a = a - b
•Output the swapped values of a and b a=20 b=10
•End
#include <stdio.h>

int main() {
int a, b;

printf("Enter two numbers: ");


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

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

a = a + b;
b = a - b;
a = a - b;

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

return 0;
}
Average of marks for different subjects :

"Think Like Compiler"

•Start
•Declare variables to store the sum of numbers and the
Enter marks for five subjects:
average. Subject 1: 85
•Input 5 numbers.
•Calculate the sum of the 5 numbers.
Subject 2: 90
•Calculate the average using the formula: Subject 3: 78
Subject 4: 88
Subject 5: 92
Total marks: 433.00
•Display the average. Average marks: 86.60
•End
#include <stdio.h>

int main() {
int a, b, c, d, e;
float avg;

printf("Enter 5 numbers: ");


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

avg = (a + b + c + d + e) / 5.0;

printf("Average = %.2f\n", avg);

return 0;
}
Celsius to Fahrenheit :

Programming with
•Start Real-Life Example:
•Input: Get the temperature in Celsius Celsius to Fahrenheit
from the user. Conversion
•Convert: Apply the formula to convert
Celsius to Fahrenheit: •Input: Doctor measures body
temperature in Celsius (e.g.,
37°C).
•C is the input temperature in Celsius. •Convert: Use the formula
•F is the converted temperature in to convert Celsius to Fahrenheit.
Fahrenheit. •Output: 37°C = 98.6°F.
•Output: Display the converted
temperature in Fahrenheit.
•End
#include <stdio.h>

int main() {
float celsius, fahrenheit;

printf("Enter temperature in Celsius: ");


scanf("%f", &celsius);

fahrenheit = (celsius * 9 / 5) + 32;

printf("Temperature in Fahrenheit = %.2f\n", fahrenheit);

return 0;
}
Temperature conversion :
Power Calculation
#include <stdio.h>
#include <math.h>

int main() {
double base, exponent, result;

printf("Enter base: ");


scanf("%lf", &base);

printf("Enter exponent: ");


scanf("%lf", &exponent);

result = pow(base, exponent);

printf("Result = %.2lf\n", result);

return 0;
}
#include <stdio.h>

int main() {
int base, exponent;
long long result = 1;

printf("Enter base: ");


scanf("%d", &base);

printf("Enter exponent: ");


scanf("%d", &exponent);

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


result *= base;
}

printf("Result = %lld\n", result);

return 0;
}
Simple Interest (SI)

Imagine you invest $1,000 in a savings account that


•Start the program. offers an annual interest rate of 5% for 3 years. The
•Input the principal amount, rate of Simple Interest (SI) can be calculated as:
interest, and time period from the •Principal (P) = $1000
user. •Rate (R) = 5% per year
•Calculate the Simple Interest using •Time (T) = 3 years
the formula: ​ Using the formula, the Simple Interest will be:

•Display the result (Simple Interest) to


the user.
•End the program.
Thus, the interest earned over 3 years would be
$150.
#include <stdio.h>

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

printf("Enter Principal amount: ");


scanf("%f", &P);

printf("Enter Rate of Interest: ");


scanf("%f", &R);

printf("Enter Time in years: ");


scanf("%f", &T);

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

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

return 0;
}
Compound Interest (CI)
#include <stdio.h>
#include <math.h>

int main() {
float P, R, T, A, CI;

printf("Enter Principal amount: ");


scanf("%f", &P);

printf("Enter Rate of Interest: ");


scanf("%f", &R);

printf("Enter Time in years: ");


scanf("%f", &T);

A = P * pow((1 + R / 100), T);


CI = A - P;

printf("Compound Interest = %.2f\n", CI);


printf("Total Amount = %.2f\n", A);

return 0;
}
Statement/expressions
Statement/expressions
Relational operators(Binary Operators)

Used to compare values, resulting in a Boolean value (1 for true, 0 for false).
Relational operators
Relational operators
Relational operators
Relational operators

❑ Precedence and Associativity of


Relational Operators :
•<=, <, >, >=

❑ Precedence and Associativity:


•All relational operators have the same
precedence.
•They follow left-to-right (L-to-R) associativity.
Relational Operators ka
Kamaal
Logical Operators

1. Logical AND(&&) Binary Operator


2. Logical OR(||)
3. Logical NOT(!) Unary Operator
L

The result of logical operator is always either 0 or 1


[Link] AND(&&)

a && b Non –zero(true)

Non zero(true) Non -zero(true)

Laddu tabhi milenge jab aapne padhai ki hai aur homework


khatam kiya hai, warna kuch nahi milega!
[Link] AND(&&)

Laddu tabhi milenge jab aapne padhai ki hai aur homework


khatam kiya hai, warna kuch nahi milega!

a b a &&b output
T T T 1
T F F 0
F T F 0
F F F 0
[Link] OR(||) (CHOICE)

a || b Non –zero(true)

Non zero(true) zero/Non-zero

Laddu tabhi milenge agar aapne padhai ki hai ya homework


khatam kiya hai, bas ek bhi kaam kiya ho toh chalega!
[Link] OR(||)

Laddu tabhi milenge agar aapne padhai ki hai ya homework


khatam kiya hai, bas ek bhi kaam kiya ho toh chalega!

a b a ||b output
T T T 1
T F T 1
F T T 1
F F F 0
[Link] NOT(!)

Laddu tabhi milenge jab aapne padhai nahi chhodi hai, warna
kuch nahi milega!

!a output
!T F
!F T
Short –circuit evaluation

a && b zero(0)

zero NO matter Never


Whether this is Evaluated
non-zero or zero
the result is zero
Short –circuit evaluation

a || b 1

non-zero NO matter Never


Whether this is Evaluated
non-zero or zero
the result is 1
Precedence Order of
Operators

||

Precedence Order of Operators yeh batata hai ki ek expression


mein kis operator ka evaluation pehle hoga aur kis ka baad
mein.
Logical operator ka use
kaha hai?

||
1. Age Verification
for Voting

•Start.
•Declare age.
•Prompt and read the user's age.
•Set canVote to 1 if age is between 18 and
100; otherwise, set it to 0.
•Print "Yes" if canVote is 1, otherwise print
"No."
•End.
#include <stdio.h>

int main() {
int age;

printf("Enter your age: ");


scanf("%d", &age);

if (age >= 18) {


printf("You are eligible.\n");
} else {
printf("You are NOT eligible.\n");
}

return 0;
}
year % 100 != 0 or year % 400 == 0
Logical operator ka use
kaha hai?

||
1. Leap year checker year % 4
== 0

•Start.
•Declare year.
•Prompt and read the user's input for the year.
•Set isLeapYear to 1 if:
year % 100 != 0 or year % 400 == 0
•year is divisible by 4, and
•(year is not divisible by 100 or is divisible by 400).
•Print "Yes" if isLeapYear is 1, otherwise print
"No."
•End.
#include <stdio.h>

int main() {
int year;

printf("Enter a year: ");


scanf("%d", &year);

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


printf("%d is a Leap Year.\n", year);
} else {
printf("%d is NOT a Leap Year.\n", year);
}

return 0;
}
year % 100 != 0 or year % 400 == 0
Modify Operator
Increment the Decrement
value of a the value of a
variable by 1 variable by 1
||
Increment(++) Decrement(--)

Pre-increment Post-increment Pre-decrement Post-decrement


(++a) (a++) (--a) (a--
year % 100 != 0 or year % 400 == 0
year % 100 != 0 or year % 400 == 0
Increment Operator(++)

a=5
||
1. Pre- Increment(++a):(पहले बढ़ाओ ++, फिर print करो)

a=a+1 (a++)

a=6
year % 100 != 0 or year % 400 == 0
Post –increment(a++)

||
1. Post-increment(a++):(पहले print करो, फिर बढ़ाओ ++) a=5
a++

a=a+1
a=6 result=5
year % 100 != 0 or year % 400 == 0
Increment Operator(++)

1. Pre- Increment(++a):(पहले
|| Post-increment(a++):(पहले
बढ़ाओ ++, फिर print करो) print करो, फिर बढ़ाओ ++)

i=10

++i=i+1=11
year % 100 != 0 or year % 400 == 0
Increment Operator(++)

1. Pre- Increment(++a):(पहले
|| Post-increment(a++):(पहले
बढ़ाओ ++, फिर print करो) print करो, फिर बढ़ाओ ++)

j=i++
j=++i
j=i
i=i+1
i=i+1
j=i
year % 100 != 0 or year % 400 == 0
Pre –decrement(--a)

||
1. Pre-decrement(--a):(पहले घट़ाओ --, फिर print करो) a=5
--a

a=a-1
a=4 result=4
year % 100 != 0 or year % 400 == 0
Post –Decrement(a--)

||
1. Post-decrement(a--):(पहले print करो, फिर घट़ाओ --) a=5
a--

a=a-1
a= 4 result=5
year % 100 != 0 or year % 400 == 0
C standard rule

❑ Ek variable
||ko ek hi baar increment/decrement karo in Result
one line. Varna side effects aayenge. vary
complier
to
complier
Why use
Number System Binary
Number
system ?
[Link] Number System: 10 symbols (0,1,2,3,4,5,6,7,8,9)

[Link] Number System :2 symbols(0,1)

[Link] Number System:8 symbols(0,1,2,3,4,5,6,7)

10,11,12,13,14,15,16
[Link] Number System: 16 symbols(0 -9 ,A,B,C,D,E,F)
Decimal Number System
Computers use binary because it's simpler and more efficient to
represent data with only two states (0 and 1) using electrical signals.
Binary Number System
Decimal to Binary
Binary to Decimal
Octal Number System:
Decimal to Octal:
Octal to decimal:
Hex-decimal Number System:
Decimal to Hexa-decimal :
Hexa-decimal to decimal:
Bitwise Operator:

[Link] OR(|)
[Link] AND(&&)
[Link] XOR(^)
[Link] not(~) Unary Opeartor

5. Bitwise left shift(<<)


[Link] right shift(>>)
Bitwise Not(~)

a ~a

0 1

1 0
Bitwise OR(|):

Dono me se eke bhi one hai to or karne per output 1hi aayga

a b a|b
0 0 0
0 1 1
1 0 1
1 1 1
Bitwise OR(|):
0011 (binary of 3)

1011(binary of 11)

1011
Bitwise AND(|):

Dono me se eke bhi ZERO hai to AND karne per output 0 hi aayga

a b a&&b
0 0 0
0 1 0
1 0 0
1 1 1
Bitwise AND(&&):
0011 (binary of 3)

&&

1011(binary of 11)

0011 (matching positions in both numbers)


Bitwise AND(&&):
0011 (binary of 3)

&&

1011(binary of 11)

0011 (matching positions in both numbers)


Bitwise X-OR(^):

Dono me bhi same hai to x-or karne per output 0 hi aayga

a b a^b
0 0 0
0 1 1
1 0 1
1 1 0
Bitwise X-OR(^):
0011 (binary of 3)

1011(binary of 11)

1000
Bitwise left shift(<<):binary operator
c=10<<1

How many times we


Shift by 10 need to shift

c=20

C=a<<b;
C=a*2^b;
Bitwise left shift(<<):

0 0 0 0 0 0 1 0 1 0

10<<1
Popped
out

0 0 0 0 0 1 0 1 0 0

Empty
space
Bitwise right shift(>>):binary operator
c=10>>1

Shift by How many times we


need to shift
10/2^1

c=5

C=a>>b;
C=a/2^b
Bitwise right shift(>>):
Popped
out

0 0 0 0 0 0 1 0 1 0

10>>1=10/2^1

0 0 0 0 0 0 0 1 0 1
Empty
space
How to store Negative Number in computer Memory?

Signed magnitude
0,1
+7=111

1 0 0 0 0 1 1 1
-7=111

+ve=0
Signed bit 7 bit
magnitude
-ve=1
2`s complementation

1)+ve :as it is
0001
1`s complementation=1110
2)-ve :2`s complementation
+ 1
2`complementation= 1111
Programs

1. 1's Complement of a Number


2. 2's Complement of a Number
3. Swap Two Numbers Without Temporary Variable

Explain how XOR (^) is used to toggle a specific


bit in a number.
#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

int ones = ~num; // 1's complement

printf("1's Complement = %d\n", ones);

return 0;
}
#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

int twos = (~num) + 1;

printf("2's Complement = %d\n", twos);

return 0;
}
Ternary operator(? :)

condition ? expression1 : expression2;


False

True

•condition: This is the boolean expression to evaluate.


•expression1: This is executed if the condition evaluates to true (non-zero).
•expression2: This is executed if the condition evaluates to false (zero).
Concept:

"Ternary operator ka funda simple hai: agar condition sahi ho, to


pehla value; galat ho, to dusra value!"
a>b 10>20

false

c=b

c=a>b?a:b;
a>b 15>20

True

C=T?a:b

C=a

c=a>b?a:b;
Programs
num
1. Finding the Absolute Value of a Number
F

num <0

-(num)
Assigning Grades Based on Marks

Marks>=90 Marks>=75 Marks>=50

A B C D
4. Finding the Smallest of Three Numbers

X=10 Y=25 Z=5


➢ Flow Control Statements

•Example code:

void main() {
S1;
S2;
S3;
S4;
}
•Default flow: Sequential
•Looping: Executes multiple times (e.g., S1 → S2 → S3
in a loop)
➢ Control Flow Statements
[Link] Statements:
•if
•if-else
•if-else if- else
•if-else if
•Switch Statement
[Link] Statements (Repetition):
•for
•while
•do-while
[Link] Statements:
•continue
•break
•exit
•return
JK ka concept

Agar yeh sach hai, toh yeh kaam karna zaroori hai!
➢ Selection Statement ➢ Conditional Execution:
c
void main() {
If Statement S1;
S2;
•Default Behavior: Sequential if (condition) {
S3;
execution S4;
Example: S5;
}
void main() {
S1;
S6;
S2; S7;
S3; S8;
S4; }
S5;
S6; •If condition is true:
S7;
S8; Execute S3, S4, S5
}
•Then continue with S6, S7,
S8
Syntax
Syntax of if Statement in C Single Statement Case:

if (condition/expression)
if (condition/expression) { S1;

S1;
S2; if (condition/expression) {
S3; S1;
}
}
Program: Eligibility Checker
Program: Number Checker
Program: Student Result Checker
Program: Bank ATM Simulation
If-Else Statement
structure

if (expression) { if (chai_garam_hai) {
// Chai garam hai, toh piyo.
// Code block when the expression is true } else {
} // Chai thandi hai, toh usse
else { garam karo.
// Alternate block of code }
}
JK ka Concept

If-Else Statement

•If: Agar condition true hai (sahi hai),


toh yeh kaam karo.

•Else: Agar condition galat hai (false


hai), toh doosra kaam karo.
Detailed Workflow

S1;
S2; Flow Sequence:
[Link] the condition is True: S1 → S2 → S3 → S4
if (expression/condition) { → S7 → S8
S3;
S4; [Link] the condition is False: S1 → S2 → S5 → S6 →
S7 → S8
}
else {
S5;
S6;
}
S7;
S8;
Programs:

#include <stdio.h>

int main() {
int num;

printf("Enter a number: ");


scanf("%d", &num);

if (num % 2 == 0)
printf("%d is Even.\n", num);
else
printf("%d is Odd.\n", num);

return 0;
}
#include <stdio.h>
2. Simple ATM Withdrawal System
int main() {
int balance = 1000;
(C Program)
int amount;

printf("Welcome to the ATM\n");


printf("Enter amount to withdraw: ");
scanf("%d", &amount);

if (amount <= 0) {
printf("Invalid amount!\n");
}
else if (amount > balance) {
printf("Insufficient balance!\n");
}
else {
balance -= amount;
printf("Withdrawal successful!\n");
printf("Remaining Balance: %d\n", balance);
}

return 0;
}
Syntax
if (expression/condition)
{
// Code 1
}
else if (expression2/condition)
{
// Code 2
}
else
{
// Code 3
}
1. Grade Calculator
Switch case

Switch-Case:
•Works like a menu, where specific
tasks are performed based on your
choice.
•Each case handles a different option.
•default runs when no option matches.
Break:
•Used to exit a block once the task is completed.
•Mostly used in switch and loops.

Continue:
•Skips the current iteration in a loop and moves to the next step.
•It bypasses the remaining code of the current iteration and proceeds to the next
one.
For loop
Pattern understand kara
anni tyala loop madhe
chalwa
loop
Loop Break
Condition

Count++
count=count+1

Coding seekho
increment
initilization
Coding seekho
Print all even number upto n

print a to z

Print Reverse number

Print number from 1 to 100 but difference is 3


#include <stdio.h>

int main() {
int n;
printf("Enter value of n: ");
scanf("%d", &n);

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

return 0;
}
#include <stdio.h>

int main() {

for(char ch = 'a'; ch <= 'z'; ch++) {


printf("%c ", ch);
}

return 0;
}
#include <stdio.h>

int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);

for(int i = n; i >= 1; i--) {


printf("%d ", i);
}

return 0;
}
#include <stdio.h>

int main() {

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


printf("%d ", i);
}

return 0;
}
Table Printing

6 X 1=6
6 X 2=12
6 X3=18
6X4=24
6X5=30
6X6=36
6X7=42
6X8=48
6X9=54
6X10=60

x x i
n=6(constant)
#include <stdio.h>

int main() {
int n;
printf("Enter a number to print its table: ");
scanf("%d", &n);

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


printf("%d x %d = %d\n", n, i, n * i);
}

return 0;
}
Power of number:

n=4,power=3

4^3=4X4X4
Sum of n natural
numbers=n(n+1)/2

Sum=0;
Sum=sum+i
Sum of square of n natural number=n(n+1)(2n+1)/6

LOGIC 1: Sum=sum + i*i

LOGIC2: Sum of square of n natural number=n(n+1)(2n+1)/6


Factorial
Fact=1;
Fact=fact*I
=1x1=1
=1x2=2
n=5!=120 =2x3=6
i=1 X 2 X 3 X 4 X 5 =6x4=24
=24x5=120=5!

end
start
Prime numbers:

1 or n
1)"If a number n is divisible by any number
between 2 and n−1, then it is not a prime number."

2)"If n< 2, it's not a prime number because


negative numbers and 0 or 1 are not prime."
Fibonacci series of a number:

fibonacci 0, 1 ,1 ,2 ,3 ,5 ,8,13,21,34
+
Logic
Last Prev Curr

0 1 1

Curr =Prev + Last;


Last=Prev
1 1 2 Prev=Curr

1 2 3

2 3 5
#include <stdio.h>

int main() {
int n, a = 0, b = 1, next;

printf("Enter number of terms: ");


scanf("%d", &n);

printf("Fibonacci Series: ");

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


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

return 0;
}
Star pattern

*****
Nested for loop=>loop ke ander loop

printf(“*”);

Printf(“\n”);
***** Star pattern
***** Steps for Pattern Printing :
*****
[Link] Banao: Rows = i, Columns = j.
*****
***** 2.i=1 pe j dekho aur i=n pe bhi.

[Link] samjho, i aur j ka relation dhundo.

[Link] loop mein daal ke verify karo.


columns
Step 1
***** j=1 j=2 j=3 j=4 j=5
***** i=1 * * * * *
***** rows
i=2 * * * * *

***** i=3 * * * * *
i=4 * * * * *
*****
i=5 * * * * *

i=1 j=1,2,3,4,5
Step 2
i=2 j=1,2,3,4,5
i=3 j=1,2,3,4,5
i=4 j=1,2,3,4,5
i=5 j=1,2,3,4,5
***** Step 3 i=1 j<=5
***** i=2 j<=5
***** i=3 j<=5
i=4 j<=5
*****
i=5 j<=5
*****

Step 4 j<=5
*****
*****
*****
*****
***** condition
columns
10 10 10 10 10 Step 1 j=1 j=2 j=3 j=4 j=5 Number
i=1 pattern
10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 i=2 10 10 10 10 10
rows
10 10 10 10 10 i=3 10 10 10 10 10
10 10 10 10 10 i=4 10 10 10 10 10
i=5 10 10 10 10 10

i=1 j=1,2,3,4,5
Step 2
i=2 j=1,2,3,4,5
i=3 j=1,2,3,4,5
i=4 j=1,2,3,4,5
i=5 j=1,2,3,4,5
10 10 10 10 10 Step 3 i=1 j<=5
10 10 10 10 10 i=2 j<=5
10 10 10 10 10 i=3 j<=5
10 10 10 10 10 i=4 j<=5
10 10 10 10 10 i=5 j<=5

Step 4 j<=5
10 10 10 10 10
10 10 10 10 10
10 10 10 10 10
10 10 10 10 10
10 10 10 10 10
condition
columns
Step 1 Number
j=1 j=2 j=3 j=4 j=5
i=1 pattern
1 1 1 1 1
11111
i=2 2 2 2 2 2
22222 rows
33333 i=3 3 3 3 3 3
44444 4 4 4 4 4
i=4
55555
i=5 5 5 5 5 5

i=1 j=1,2,3,4,5
Step 2
i=2 j=1,2,3,4,5
i=3 j=1,2,3,4,5
i=4 j=1,2,3,4,5
i=5 j=1,2,3,4,5
Step 3 i=1 j<=5
i=2 j<=5
11111
22222 i=3 j<=5
33333 i=4 j<=5
44444
i=5 j<=5
55555

Step 4 i ko print
karo
11111
22222
33333
44444
55555
columns
Step 1
j=1 j=2 j=3 j=4 j=5
i=1 1 2 3 4 5
12345 Number
i=2 1 2 3 4 5 pattern
12345 rows
12345 i=3 1 2 3 4 5
12345 1 2 3 4 5
i=4
12345
i=5 1 2 3 4 5

i=1 j=1,2,3,4,5
Step 2
i=2 j=1,2,3,4,5
i=3 j=1,2,3,4,5
i=4 j=1,2,3,4,5
i=5 j=1,2,3,4,5
Step 3 i=1 j<=5
i=2 j<=5
11111
22222 i=3 j<=5
33333 i=4 j<=5
44444
i=5 j<=5
55555

Step 4 j ko print
karo
11111
22222
33333
44444
55555
Number
pattern
54321
54321
54321
54321
54321
columns
Step 1
j=1 j=2 j=3 j=4 j=5
i=1 1 4 9 16 25
1 4 9 16 25 i=2 1 4 9 16 25
1 4 9 16 25 rows
1 4 9 16 25 i=3 1 4 9 16 25
1 4 9 16 25 i=4 1 4 9 16 25
1 4 9 16 25
i=5 1 4 9 16 25

i=1 j=1,2,3,4,5
Step 2
i=2 j=1,2,3,4,5
i=3 j=1,2,3,4,5
i=4 j=1,2,3,4,5
i=5 j=1,2,3,4,5
Step 3 i=1 j<=5 Ascending
square pattern
i=2 j<=5
1 4 9 16 25
1 4 9 16 25 i=3 j<=5
1 4 9 16 25 i=4 j<=5
1 4 9 16 25
i=5 j<=5
1 4 9 16 25

Step 4 j *j ko
print karo
1 4 9 16 25
1 4 9 16 25
1 4 9 16 25
1 4 9 16 25
1 4 9 16 25
alphabets
pattern
columns
Step 1
j=1 j=2 j=3 j=4 j=5
i=1 a a a a a
aaaaa i=2 b b b b b
bbbbb rows
ccc c c i=3 c c c c c
ddddd i=4 d d d d d
eeeee
i=5 e e e e e

i=1 j=1,2,3,4,5
Step 2
i=2 j=1,2,3,4,5
i=3 j=1,2,3,4,5
i=4 j=1,2,3,4,5
i=5 j=1,2,3,4,5
Step 3 i=1 j<=5
i=2 j<=5
i=3 j<=5
aaaaa i=4 j<=5
bbbbb
ccc c c i=5 j<=5
Ascending
ddddd
square pattern
eeeee
i=1 a (5 times)
i=2 b(5 times)
i=3 c(5 times)
i=4 d(5 times)
i=5 e(5 times)
aaaaa
1) row = 1 bbbbb
2) row <= 5 ccc c c
3) name = 'a' + (row - 1) ddddd
= 'a' + (2 - 1) eeeee
= 'a' + 1
= 'b' (ASCII no: 97 + 1 = 98)

4) print name 5 times


5) row = row + 1
abcde
abcde
abcde
abcde
abcde
Logic 1
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15 [Link] = 1
16 17 18 19 20 [Link] <= 5
21 22 23 24 25 [Link] count (5 times)
count = count + 1
(repeat for each iteration)
4. row = row + 1
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
columns
Step 1
j=1 j=2 j=3 j=4 j=5
* i=1 *
**
*** i=2 * *
rows
**** i=3 * * *
*****
i=4 * * * *
i=5 * * * * *

i=1 j=1
Step 2
i=2 j=1,2
i=3 j=1,2,3
i=4 j=1,2,3,4
i=5 j=1,2,3,4,5
Step 3 i=1 j<=i
* i=2 j<=i
** i=3 j<=i
***
i=4 j<=i
****
***** i=5 j<=i

Step 4 j<=i
1
12
123
1234
12345
Update condition
Break
condition

Initialization
While loop
syntax

i=1(initialization)

Loop break
condition

Update conditions
do while loop
While loop
do while loop

1)Initialize 1)Initialize
2)break 2)update
3)update 3)break
Syntax of do while

1)Initialize

2)Update

3)break
Sum=0 Sum of N natural numbers

i=1

Sum= sum+ i
break continue

break ke neeche ka koi bhi Sirf wo condition na chale


statement nahi chalta baki ke sabhi condition chale
Introduction to Functions in C

Function ek aisa self-contained code ka block hota


hai jo kisi specific kaam ko perform karta hai. Isse ek
baar define karne ke baad, hum usse program mein kai
baar call (use) kar sakte hain bina baar-baar likhe. Yeh
code ko modular, reusable aur readable banata hai.
Real-Life Se Programming Connection:
Real Life Programming Equivalent
Add button on calculator add() function
Input values (5 and 3) Arguments (add(5, 3))
Result shown (8) Return value
Button code behind the
Function definition
scene
Function ek aisa system hai jo input leta
hai, kuch kaam karta hai, aur result deta
hai — jaise calculator mein add button.
Real life function example:

Real Life Example: Bhushan & Vinod

Bhushan: "Vinod ji, ek chai ho jaaye?“

Vinod: "Haan chaliye Bhushan ji, mood fresh


ho jaayega!“

Yahan har baar jab ye dono chai peene jaate


hain, wo ek hi kaam baar-baar karte hain –
matlab wo ek function jaisa hi kaam kar rahe
hote hain.
Element Real World C Code
Bhushan & Vinod ka Repeat hone waala
Function
chai jaana kaam
“Chai peene chalo”
Function Call chaiPeeneChalo();
bolna
Chai banana aur
Task detail Function Definition
peena
Syntax

return_type function_name (parameters) {

// code block
return value; // optional
}

• return_type: function kis type ka value return karega (jaise int, float, void, etc.)
• function_name: function ka naam
• parameters: input values (arguments)
• return: result return karta hai (agar void nahi hai)
Example 1: Simple Function with No Return
Types of Function

1. Library Functions
(Inbuilt Functions) 2. User-Defined Functions
1. Library Functions (Inbuilt Functions)

Definition:

Yeh functions C ke standard library mein pehle se defined hote hain. Hum
unhe direct use kar sakte hain, unka code likhne ki zarurat nahi hoti.

Example:

• printf() – output dene ke liye


• scanf() – input lene ke liye
• strlen() – string ki length nikalne ke liye
• sqrt() – square root nikalne ke liye
2. User-Defined Functions

Definition:

Yeh wo functions hote hain jo programmer khud banata hai kisi


specific task ko perform karne ke liye.

Use:
Code ko modular, reusable aur manageable banata hai.
Parameter vs Argument (Basic Difference)

Parameter Argument
Function call ke waqt use
1️⃣ Function definition mein use hota hai
hota hai
Ek variable hota hai jo value accept Ek actual value hoti hai jo
2️⃣
karta hai function ko di jati hai
3️⃣ Placeholder hota hai Real data hota hai
4️⃣ Syntax: void add(int a, int b) Syntax: add(5, 10);
• Parameter = Function ko bolte ho: "Mujhe do number chahiye."
• Argument = Jab function call hota hai: "Yeh lo 5 aur 10, add karo."
Types of User-Defined Functions in C

[Link]. Function Type Arguments Return Value


No arguments, No return
1
value
Arguments passed, No
2
return value
No arguments, Returns a
3
value
Arguments passed, Returns
4
a value
1. No Arguments, No Return Value
Explanation: Function mein na toh koi value pass ki jati hai,
na hi koi value return hoti hai
2. With Arguments, No Return Value
Explanation: Values pass ki jati hain, lekin koi return value nahi hoti.
3. No Arguments, With Return Value

Explanation: Function koi value return karta hai, lekin koi argument nahi
leta.
4. With Arguments and With Return Value
Explanation: Sabse common type – values pass bhi hoti
hain aur result return bhi hota hai.
Function Declaration
(Prototype):

C mein agar function ko main()


ke baad define kar rahe ho, toh
pehle uska prototype likhna
padta hai
function-based programs

1. Sum of Two Numbers 5. Print a Greeting Message

2. Check Even or Odd

3. Find Maximum of Two


Numbers
4. Calculate Square of a
Number
pointer

Pointer is a variable that store address of another variable

& = address-of operator

* = Value-at/Dereference
Operator
Syntax:
Data_type *var_name

Value at
address
operator
x
Int x=10 10

1000

Int y=&x 1000

1004
x
Int x=10 18

1000
Int y=&x
y

1000
*y=18

1004
x

5
1000
y

1000

10044
Z

1004

1008
1)Addition of two number using pointer

x a
1000 10 1000
2000 b
y 20 1004
1004

2004
Swapping of number with
temp variable using pointer

Before swapping
x=&a 1000 1004

a=10 b=20
y=&b
Afther swapping

temp=*x; a=20 b=10


*x=*y;
*y=temp
function parameter
passing methods

Call by value
Call by reference

*p=>address pe kya Rakha hai


&y=>address kya hai
1)call by value

Concept "Jo bhi humne pass kiya, usme koi change nahi hoga."

program that combines both Prime Number


In call by value theCheck
actualand
value of variable
Factorial cant beusing
Calculation changed if you change the value
of function parameter it is only changed for current function
functions
x

10

1000

a++ a

10
2)call by reference

Concept:
"Jo values humne pass ki, unme bhi changes honge."
x

10

1000

a++ a

1000
storage classes

storage classes define the scope, lifetime,


and visibility of variables and functions
auto Register

Types of storage classes

Static extern
1. Automatic (auto): "Temporary local hero – Block khatam, kaam khatam!"

•Default Class: Variables declared inside a function without any storage class
specifier are treated as auto.
•Scope: Local to the block or function in which it is declared.
•Lifetime: Exists only during the execution of the block or function.
•Keyword: auto (rarely used explicitly, as it is implicit).
•Example:
void func() {
auto int x = 10; // Same as 'int x = 10;’
printf("%d\n", x);
}
2. Register "Fastest memory racer – Turbo mode enabled!"

•Purpose: Stores the variable in a CPU register for faster access.

•Scope: Local to the block or function in which it is declared.

•Lifetime: Exists only during the execution of the block or function.

•Keyword: register.
•Notes:
•The compiler may ignore this request if no registers are available.
•Pointers to register variables are not allowed.
ALU(CPU)

5
5 2 x
0.1 sec +
7 2
y
processor 7
z
4 sec
RAM
3. Static: "Lifelong yaari – Value yaad rakhta hai!"

•Purpose:

•For variables inside a function: Retains their value between


function calls.

•For global variables: Restricts access to the same file


(internal linkage).

•Scope:

•Local variables: Limited to the function/block.

•Global variables: Limited to the file.


•Lifetime: Exists for the entire duration of the program.
•Keyword: static.
a=1 a=1

a=1

b=1,2,3

a=1 b=1
a=1 b=2
a=1 b=3
4. External (extern)
"Global mohalla superstar – Sab jagah dikhai deta hai!"

•Purpose: Allows global variables or functions to be shared across


multiple files.
•Scope: Global (extends across files where declared with extern).
•Lifetime: Exists for the entire duration of the program.
•Keyword: extern.
•Notes:
•extern does not allocate memory; it only declares a variable.
•Actual memory allocation happens in the definition.
fun1.c fun2.c
Recursion
Word 1

Word 2

Word 3

"Recursion: Function ka khud ko bulana


aur problem chhoti karte jaana."
Recursion

Recursion is a process in programming where a


function calls itself directly or indirectly to
solve a problem. It is used to solve problems
that can be broken down into smaller, similar
subproblems.

Key Characteristics of Recursion:


[Link] Case: The condition under which the
recursion stops. Without a base case, the
function would call itself infinitely.

[Link] Case: The part of the function


where it calls itself with a smaller or simpler
input.
In mathematical terms, a recursive function
defines a sequence or problem where the
"Ek bada problem
solution depends on smaller instances of itself.
chhote problems mein
tootke solve hota hai!"
For example, the factorial function n! is
defined recursively as:
if ( ? )
{
Small input (i/p)
Base case
Easy case
Can be answered directly
No recursion is needed
}
else
{
Hard/Complex case
Not easy
Cannot be answered directly
Recursion is needed
}
Here’s the same content in text format for your reference:

What and Why? Loops → Factorial of a number


n! = n × (n-1) × (n-2) × (n-3) ... 3 × 2 × 1
n! = n × (n-1)! 5! = 5 × 4 × 3 × 2 × 1
f(n) = n × f(n-1) → Recurrence Relation 5! = 5 × 4!
4! = 4 × 3 × 2 × 1
4! = 4 × 3!
int factorial(int n) {
if (n == 0) return 1; // Base case
return n * factorial(n - 1); // Recursive call
}
#include <stdio.h>

int factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);

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

return 0;
}
Printing JK 10 times

JK n==0

JK n-1
Sum of digits

1=>1
n>=0 n<10 2=>2
3=>3

125 1+2+5=8

n%10+sumofdigits(n/10)
Power of
number

int power(int base, int exp) {


if (exp == 0) return 1; // Base case
return base * power(base, exp - 1); //
Recursive call
}
Print number from 1 to N

#include <stdio.h>

void printNumbers(int n) {
if (n > 0) {
printNumbers(n - 1); // Recursive call
printf("%d ", n); // Print the number
}
}

int main() {
int N = 5;
printNumbers(N); // Output: 1 2 3 4 5
return 0;
}
Array

An array in C is a collection of elements of the same data type, stored in


contiguous memory locations. Arrays are used to store multiple values in a
single variable, making it easier to manage and manipulate groups of related
data.
Size=5

11 12 13 14 15
index 0 1 2 3 4
Declaring an Array

Data _type array_ name[size];


•Data _type: Type of elements in the array (e.g., int, float, char, etc.).

•Array _ name: Name of the array.

•size: Number of elements in the array.

Example:
int numbers[5]; // Declares an array of 5 integers
Initializing an
Array

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

int numbers[5] = {1, 2};


// Remaining elements are initialized to 0 1 2 0 0 0

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


Accessing Array Elements

numbers[0] = 10; // Assigns 10 to the first element

printf("%d", numbers[0]); // Prints the first element

10 20 30 40 50

0 1 2 3 4
Common Operations

Traversal: 11 12 13 14 15

0 1 2 3 5
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
Input from User:

0 1 2 3 4

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


scanf("%d", &numbers[i]);
}
Sum of Elements:
1 2 3 4 5
0 1 2 3 4

int sum = 0;

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


sum += numbers[i];
}

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


2D array

A 2D array is a collection of data arranged in rows


and columns, forming a grid-like structure. It is widely
used to represent tables, matrices, or grids in
programming.
cols

int arr[3][3];
// Declares a 3x3 array (3 rows, 3columns)
rows
// Static initialization
int arr[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

// Dynamic input
int arr[2][3];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &arr[i][j]);
}
}
Accessing
Elements

printf("%d", arr[1][2]); // Accesses the element at row 1, column 2

0 1 2
0
1 23
2
Simple Matrix Print Code in C
cols

0 1 2

0 1 2 3
1 4 5 6
rows
2 7 8 9
Enter number of rows: 3 matrix as input from the user and
Enter number of columns: 3 prints it
Enter elements of the matrix:
Enter element at position [1][1]: 1
Enter element at position [1][2]: 2
Enter element at position [1][3]: 3
Enter element at position [2][1]: 4
Enter element at position [2][2]: 5
Enter element at position [2][3]: 6
Enter element at position [3][1]: 7
Enter element at position [3][2]: 8
Enter element at position [3][3]: 9

The matrix is:


123
456
789
Addition of
matrices
Matrix A

Matrix B
C=A+B
Strings

In C, strings are essentially arrays of


characters that end with a null character
('\0'). This null character indicates the end of
the string
Declaring Strings

Using a Character Array:

char str[20]; // Can hold a string of up to 19 characters + 1 for '\0'


char str[] = "Hello"; // Implicitly null-terminated

Char str[20]={“AMIT”}

A M I T

‘\0’=It Represents string end


It is non printable character
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Char a[10];
a=“AMIT” not allowed in c
Methods to Take String Input

#include <stdio.h>

int main() {
char str[100]; // Declare a string with enough space
printf("Enter a string: ");
scanf("%s", str); // Reads input until a space or newline
printf("You entered: %s\n", str);
return 0;
}

Limitation: Cannot read strings with spaces (e.g., "Hello World"


will only store "Hello").
2. Using gets (Not Recommended)

#include <stdio.h> gets reads an entire line of input, including spaces,


but it is not safe because
it doesn't check for buffer overflow.
int main() {
char str[100];
printf("Enter a string: ");
gets(str); // Not safe! Avoid using it.
printf("You entered: %s\n", str);
return 0;
}

Warning: Avoid using gets in modern C programs. It has been removed in C11.
3. Using fgets (Recommended)
fgets is the safest way to take string input in C as it prevents
buffer overflows.

#include <stdio.h>

int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin); // Reads up to sizeof(str) - 1 characters
printf("You entered: %s", str);
return 0;
}
String Predefined function

In C, predefined string functions are available in the <string.h> library.


These functions are commonly used for string manipulation.

•strlen() - Get the length of a string.


•strcpy() - Copy one string to another.
•strcat() - Concatenate (append) one string to another.
•strcmp() - Compare two strings.
Using strlen()

1. Finding Length of a String

Without using strlen() Using strlen()


2. Copying a String

Without using strcpy() Using strcpy()


Using strlen()

3. Concatenating Strings

Without using strcat() Using strcat()


Using strlen()

4. Comparing Strings

Without using strcmp() Using strcmp()


Reverse String

‘a’ ‘b’ ‘h’ ‘i’ ‘s’ ‘h’ ‘e’ ‘k’ ‘\0’


‘a’ ‘b’ ‘h’ ‘i’ ‘s’ ‘h’ ‘e’ ‘k’ ‘\0’

0 1 2 3 4 5 6 7 8

t
len = strlen(a); ‘a’ ‘b’ ‘h’ ‘i’ ‘s’ ‘h’ ‘e’ ‘k’ ‘\0’

for (i = 0; i < len / 2; i++) { 0 1 2 3 4 5 6 7 8

t = a[i];
a[i] = a[len - i - 1];
a[len - i - 1] = t;

}
Palindrome

Example 1:

Input: madam
String: m a d a m
Index: 0 1 2 3 4

Step-by-Step Comparisons:
[Link] a[0] (m) with a[4] (m) → Match
[Link] a[1] (a) with a[3] (a) → Match
[Link] a[2] (d) with a[2] (d) → Match
Result: All characters match → Palindrome
Example 2: Input: hello

String: h e l l o
Index: 0 1 2 3 4

Step-by-Step Comparisons:
[Link] a[0] (h) with a[4] (o) → Mismatch
Result: Mismatch found → Not a Palindrome
Static memory allocation

Static memory allocation ka matlab hota hai ki memory ka size


compile time par hi fix ho jata hai, aur program run hone ke
dauran wo change nahi hota.
Key points:
1. Compile Time Allocation – Memory ka size aur location compile
hone ke samay decide hota hai.

2. Fixed Size – Ek baar memory allocate ho gayi to program execution


ke dauran uska size change nahi hota.

3. Storage Location – Ye memory stack ya data segment me allocate


hoti hai (global/static variables ke liye data segment, local ke liye
stack).
#include <stdio.h>

int main() {
int arr[5]; // 5 integers ke liye memory compile time par allocate
printf("Example\n");
return 0;
}

Advantages:
• Fast execution (kyunki memory pehle hi allocate ho gayi hai).
• Memory management simple hota hai.

Disadvantages:
• Memory ka size fix hai, agar zyada chahiye to badal nahi sakte.
• Agar extra memory allocate kar di to waste ho sakti hai.
Dynamic memory allocation

Dynamic memory allocation ka matlab hai ki memory ka size run time


(program execution ke dauran) decide hota hai, aur hum apne hisaab
se memory ko allocate ya free kar sakte hain.

Key Points:

1. Run Time Allocation – Memory execution ke samay allocate hoti hai.


2. Flexible Size – Program chalate waqt hum jitni memory chahiye utni le sakte hain,
aur zarurat hone par badha/ghata sakte hain.
3. Storage Location – Ye memory heap area me allocate hoti hai.
4. Manual Management – Programmer ko memory allocate karni (malloc, calloc) aur
free karni (free) padti hai.
Memory Allocation

Malloc () Calloc() Realloc() free()


malloc
2000

2000 6

malloc() ka full form hai Memory Allocation.


Ye C language ka ek standard library function hai jo dynamic memory allocation ke
liye use hota hai.
ptr = (castType*) malloc(size_in_bytes);
Calloc()

calloc() ka full form hai Contiguous Allocation.


Ye bhi C ka ek dynamic memory allocation function hai, lekin isme ek
special feature hota hai — ye allocated memory ko zero se initialize karke
deta hai.

1000 1004 1008 1012 1016

1000 11 22 44

x
ptr = (castType*) calloc(number_of_blocks, size_of_each_block);
realloc()

realloc() ka full form hai Re-Allocation.


Ye C ka ek dynamic memory function hai jo pehle se allocated memory ka size badalne ke
liye use hota hai, bina purani values khoye (jitni fit hoti hain, utni preserve hoti hain).

1000 1004 1008 1012 1016 1020 1024


67 22 44 44 61
1000

y
ptr = (castType*) realloc(old_ptr, new_size_in_bytes);
free()

free() C ka ek function hai jo dynamically allocated memory ko release (deallocate)


karne ke liye use hota hai.

free(pointer);

pointer → wo address jo malloc(), calloc(), ya realloc() se allocate hua tha.


1. malloc() – Memory allocate karta hai (garbage values hoti hain).
2. calloc() – Memory allocate karta hai aur sab values 0 se initialize karta hai.
3. realloc() – Pehle se allocated memory ka size change karta hai, purani
values preserve karta hai.
4. free() – Dynamically allocated memory ko release karta hai.
Structure

A structure is a collection of variables (of different or same data types) grouped


together under one name. Each member of a structure has its own memory
location.

Syntax
struct StructureName {
dataType member1;
dataType member2;
// ...
};
Person

Char int float

Name age height


Person
Char int float

Name age height


Person
Char int float

Name age height

Person

Char int float

Name age height


UNION

A union is similar to a structure, but it uses a shared memory for all its
members. This means only one member can hold a value at any given
time.

Syntax:
union UnionName {
dataType member1;
dataType member2;
// ...
};
Union Data
LCM,HCF(GCD)

LCM kya hota hai ?

LCM ka full form hai "Lowest Common Multiple", jiska matlab hota hai:
Sabse chhota aisa number jo diye gaye sabhi numbers se poori tarah
divide ho jaye (ya jisme sabhi numbers ka multiple aa jaye).
4 6
8 12
12 18
16 24
20 30
24 36
28 42
32 48
36 54
40 60
44 66
48 72
52 78
56 84
60 90
LCM=12
(sabse chota common multiple)
Highest common multiple(HUM BATA NAHI
SAKTE)
8%2=0
8/2=4
4 6
for(int i=1;i<=100;i++){

If(i%x==0 && i%y==0){

printf(“Lcm is %d”,i);
break;
}
for(int i=1;i<=100;i++){

If(i%x==0 && i%y==0){

printf(“Lcm is %d”,i);
break;
}
X=1000 Y=2000
for(int i=1;i<=100;i++){

If(i%x==0 && i%y==0){

printf(“Lcm is %d”,i);
break;
}
Inka 1 se check karna start
karoge to time waste hoga
Case 1: Common factor hai → LCM < multiplication
Example: 4 and 6
• Multiplication = 4 × 6 = 24
• LCM = 12 (chhota kyunki 4 aur 6 me common factor 2 hai)

Case 2: No common factor (coprime numbers) → LCM =


multiplication
Example: 4 and 5
• Multiplication = 4 × 5 = 20
• LCM = 20 (same kyunki common factor 1 hi hai)

Case 3: Same number → LCM = same number


Example: 7 and 7
• Multiplication = 7 × 7 = 49
• LCM = 7 (bohot chhota kyunki dono same hain)
for(int i=1;i<=100;i++){

If(i%x==0 && i%y==0){


Pehle dono me se bada number choose karte
hain (LCM usse chhota ho hi nahi sakta).
printf(“Lcm is %d”,i);
break;
}
Ternary operator(? :)

condition ? expression1 : expression2;


False

True

• condition: This is the boolean expression to evaluate.


• expression1: This is executed if the condition evaluates to true (non
• expression2: This is executed if the condition evaluates to false (zer
Concept:

"Ternary operator ka funda simple hai: agar condition sahi ho, to


pehla value; galat ho, to dusra value!"
a>b 10>20

false

c=b

c=a>b?a:b;
for(int i = x>y ? x:y;i<=x*y;i++){

If(i%x==0 && i%y==0){

printf(“Lcm is %d”,i);
break;
}
Max=4>6?4:6

Step max value max % 4 == 0? max % 6 == 0? Result


1 6 (6%4 = 2) (6%6 = 0) Continue
2 7 Continue
3 8 (8%4 = 0) (8%6 = 2) Continue
4 9 Continue
5 10 Continue
6 11 Continue
7 12 (12%4=0) (12%6=0) LCM found
HCF(Highest Common Factor)

HCF ka full form hai Highest Common Factor, jise GCD (Greatest
Common Divisor) bhi bolte hain.
Ye wo sabse bada number hota hai jo dono (ya zyada) numbers ko
poori tarah divide karta hai bina remainder ke.

Example:
Find HCF of 12 and 18
Factors of 12: 1, 2, 3, 4, 6, 12
Factors of 18: 1, 2, 3, 6, 9, 18
Common factors: 1, 2, 3, 6
HCF = 6
• Factors of 4 → 1, 2, 4
• Factors of 6 → 1, 2, 3, 6
• Common factors → 1, 2
HCF = 2

LCF(lowset common factor)= hamesha 1 rahta hai


HCF Inn dono ka
inse chota hi hai
8%2=0
8/2=4
for(int i= x<y ? x:y;i>0;i--){
If(x%i==0 && y%i==0){
Printf(“GCD is%d”,i);
break;
}
}
b=123%10=3
Sum Of Digits
S=0+3=3
X=123/10

b=12%10=2 Enter a number: 123


S=3+2=5
X=12/10 Sum of digits = 6

b=1%10=1
S=5+1=6
X=1/10=0
(loop break condititon)
Armstrong number
153

a=153%10=3

y=x/10=153/10=15

b=y%10=15%10=5

c=15/10=1
x=153

t=153%10=3,5,1

s=s+(t*t*t)=0+(3*3*3)=27
=27+(5*5*5)=152
=152+(1*1*1)=153
y=y/10
y/10=153/10=15
=15/10=1
=1/10=0

x==s
b=123%10=3
Sum Of Digits
S=0+3=3
X=123/10

b=12%10=2 Enter a number: 123


S=3+2=5
X=12/10
Sum of digits = 6

b=1%10=1
S=5+1=6
X=1/10=0
(loop break condititon)
b=123%10=3 Reverse of Number
S=0*10+3=3
X=123/10

Enter a number: 123


b=12%10=2 Reversed number = 321
S=3*10+2=32
X=12/10

b=1%10=1
S=32*10+1=321
X=1/10=0
(loop break condititon)
b=121%10=1 palindrome number
S=0*10+1=1
X=123/10

Enter a number: 121


b=12%10=2 Reversed number = 121
S=1*10+2=12
X=12/10

b=1%10=1
S=12*10+1=121
X=1/10=0
(loop break condititon)
File handling

File Handling in C:
File handling in C allows us to create, read, write, and manipulate files
on the system. The standard library <stdio . h> provides functions to handle
files.
Basic File Operations:

1. Creating and Opening a File – fopen()

2. Reading from a File – fscanf(), fgets()

3. Writing to a File – fprintf(), fputs()

4. Closing a File – fclose()

5. Other Operations – fgetc(), fputc(), fread(), fwrite()


RAM HDD

Char[]={“JK”}
fp

[Link]
buffer

100

[Link]
File Handling Functions in C

Function Meaning / Use


File open करने के लिए इस्ते माल होता है । Mode के साथ
fopen()
file खोल जात है (जैसे "r", "w", "a")।
Open क गई file को close करता है ताकक memory free हो
fclose()
जाए।
fprintf() File में formatted data लिखने के लिए।
fscanf() File से formatted data पढ़ने के लिए।
fputc() File में single character लिखने के लिए।
fputs() File में string (character array) लिखने के लिए।
fgetc() File से single character पढ़ने के लिए।
fgets() File से एक line/string पढ़ने के लिए।
fwrite() File में binary data या blocks लिखने के लिए।
fread() File से binary data या blocks पढ़ने के लिए।
File Opening Modes

Mode Meaning / Use


"r" File को read करने के लिए खोल ता है । अगर file exist नह ीीं करत तो NULL return
करे गा।
"r+" File को read और write दोनोीीं के लिए खोल ता है । File exist होना जरूर है ।
"rb" File को binary read mode में खोल ता है ।
"rb+" File को binary read/write mode में खोल ता है ।
File को write करने के लिए खोल ता है । अगर file exist है तो उसका content delete
"w"
हो जाएगा। अगर file exist नह ीीं करत तो नई file create करे गा।
"w+" File को read और write दोनोीीं के लिए खोल ता है । प राना content delete हो जाएगा।
"wb" File को binary write mode में खोल ता है । प राना content delete हो जाएगा।
"wb+" File को binary read/write mode में खोल ता है । प राना content delete हो जाएगा।
"a" File को append (data जोड़ने) के लिए खोल ता है । प राना data safe रहता है ।
"a+" File को read और append दोनोीीं के लिए खोल ता है । प राना data safe रहता है ।
"ab" File को binary append mode में खोल ता है । प राना data safe रहे गा।
"ab+" File को binary read/append mode में खोल ता है । प राना data safe रहे गा।
Part 02

File में Data लिखने के लिए File से Data पढ़ने के लिए


fputs() fgets()
fputc() fgetc()
fprintf() fscanf()
Hello Friends
तो:
• Index: 0 1 2 3 4 5 6 7 8 9 10 11 12
• Data: H e l l o F r i e n d s
• Total characters = 13 (spaces सहहत)

इसलिए fgets(a, 13, fp); exactly "Hello Friends" पढ़ ल े गा।


File में Data लिखने के लिए File से Data पढ़ने के लिए
fputs() fgets()
fputc() fgetc()
fprintf() fscanf()
PART -03

You might also like