SlideShare a Scribd company logo
C Programming Notes
What is Programming ?
Computer Programming is a medium for us to Communicate with
Computers
What is C?
C is a general-purpose programming language created by Dennis
Ritchie at the Bell Laboratories in 1972.
It is a very popular language, despite being old. The main reason for
its popularity is because it is a fundamental language in the field of
computer science.
Why Learn C?
● It is one of the most popular programming languages in the
world
● If you know C, you will have no problem learning other popular
programming languages such as Java, Python, C++, C#, etc,
as the syntax is similar
● C is very fast, compared to other programming languages, like
Java and Python
● C is very versatile; it can be used in both applications and
technologies
Variables
Variables are containers for storing data values, like numbers and
characters. It’s also the name of a memory location.
In C, there are different types of variables for example:
● int - stores integers (whole numbers), without decimals, such as
123 or -123
● float - stores floating point numbers, with decimals, such as 19.99
or -19.99
Written By : Akshay Bhagade
● Double - stores floating point numbers, with decimals, such as
19.99 or -19.99
● char - stores single characters, such as 'a' or 'B'. Characters are
surrounded by single quotes
E.g. int num = 34, float number = 45.7, char name = ’A’
The general rules for naming variables are:
● Names can contain letters, digits and underscores
● Names must begin with a letter or an underscore (_)
● Names are case-sensitive (myVar and myVar are different
variables)
● Names cannot contain whitespaces or special characters like !,
#, %, etc.
● Reserved words (such as int) cannot be used as names
Basic Data Types
The data type specifies the size and type of information the variable
will store.
Data
Type
Size Description Exam
ple
int 2 or 4
bytes
Stores whole numbers, without decimals 1
float 4 bytes Stores fractional numbers, containing one
or more decimals. Sufficient for storing
6-7 decimal digits
1.99
double 8 bytes Stores fractional numbers, containing one
or more decimals. Sufficient for storing
15 decimal digits
1.99
char 1 byte Stores a single character/letter/number,
or ASCII values
'A'
Written By : Akshay Bhagade
Format Specifiers
Format specifiers are used together with the printf() function to tell
the compiler what type of data the variable is storing. It is basically
a placeholder for the variable value.
Data Type Format Specifiers
● int %i or %d
● float %f
● double %lf or %f
● char %c
Keywords
These are reserved words,whose meaning is already known to the
compiler there are 32 keywords available in C
Auto double int struck
Break long else switch
Case return enum typedef
Char register extern union
Const short float unsigned
Continue signed for void
Default size of goto volatile
Do static if while
Written By : Akshay Bhagade
OUR FIRST C PROGRAM
#include <stdio.h>
int main() {
printf("Hello, I am Learning C Programming");
return 0;
}
BASIC STRUCTURE OF A C PROGRAMMING
Line 1: #include <stdio.h> is a standard input output header file library
that lets us work with input and output functions, such as printf() (used in
line 4). Header files add functionality to C programs.
Line 2: The int keyword indicates that the main function will return an
integer value. By convention, returning 0 indicates that the program
terminated successfully.
main(). This is called a function. Any code inside its curly brackets {} will be
executed.
Line 3: printf() is a function used to output/print text to the screen. In
our example, it will output "Hello, I am Learning C with Harry".
Line 4: return 0 ends the main() function.
Line 5: Do not forget to add the closing curly bracket } to actually end the
main function.
Note that: Every C statement ends with a semicolon ;
COMMENTS
Comments are used to clarify something about the program in plain
language.it is a way for us to add notes to our program.there are
two types of comments in C
1. Single line comment : //This is a comment
2. Multi line comment : /* This is a multi
line comment *
Comments in a C program are not executed and ignored
Written By : Akshay Bhagade
Receiving input from the user
In order to take input from the user and assign it to a variable, we
use scanf() function.
Syntax for using scanf ;
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("You entered: %dn", number);
return 0;
}
Note: & is important
& is the “address of” operator and it means that the supplied value
should be copied to the address which is indicated by variable i.
CHAPTER 1- PRACTICE SET
Q1. Write a c program to calculate area of a rectangle
(a) Using hard coded inputs
(b) Using inputs supplied by the user
Q2. Calculate the area of a circle and modify the same program to
calculate the circumference of the circle.
Q3. Write a program to convert celsius (Centigrade degree
temperature to fahrenheit)
Written By : Akshay Bhagade
Chapter 2- INSTRUCTIONS AND OPERATORS
Operators are used to perform operations on variables and values.
Types of Operator:
● Arithmetic operators
● Assignment operators
● Comparison operators
● Logical operators
● Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
Written By : Akshay Bhagade
Operator Name Description Example
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from
another
x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable
by 1
++x
-- Decrement Decreases the value of a
variable by 1
--x
Assignment Operators
Assignment operators are used to assign values to variables.
Operator example Same as
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
Comparison Operators
Comparison operators are used to compare two values (or variables). This
is important in programming, because it helps us to find answers and
make decisions.
The return value of a comparison is either 1 or 0, which means true (1) or
false (0). These values are known as Boolean values.
Operator Name Example Description
== Equal Equal to x == y Returns 1 if the values are
equal
!= Not equal x != y Returns 1 if the values are
not equal
> Greater than x > y Returns 1 if the first value
is greater than the second
value
Written By : Akshay Bhagade
< Less than x < y Returns 1 if the first value
is less than the second
value
>= Greater than or
equal to
x >= y Returns 1 if the first value
is greater than, or equal
to, the second value
<= Less than or
equal to
x <= y Returns 1 if the first value
is less than, or equal to,
the second value
Logical Operators
You can also test for true or false values with logical operators.
Operator Name Example Description
&& Logical and x < 5 && x < 10 Returns 1 if both statements are
true
|| Logical or x < 5 || x < 4 Returns 1 if one of the
statements is true
! Logical not !(x < 5 && x <
10)
Reverse the result, returns 0 if
the result is 1
Booleans
Very often, in programming, you will need a data type that can only have
one of two values, like:
● YES / NO
● ON / OFF
● TRUE / FALSE
A boolean variable is declared with the bool keyword and can only take
the values true or false:
● 1 (or any other number that is not 0) represents true
● 0 represents false
Written By : Akshay Bhagade
Chapter 3- Conditional Statements
The conditional statements are also known as Decision-Making
Statements and are used to evaluate one or more conditions and make
the decision whether to execute a set of statements or not. These
decision-making statements in programming languages decide the
direction of the flow of program execution.
● Conditional Operator (? :)
● If Statement
● If-else statement
● Ladder else-if statement
● Nested if-else statement
● Switch statement
Conditional Operator/Ternary Operator (? :)
Syntax:
(condition) ? Execute when condition true : Execute when condition false;
Example:
1) print the greater number between two numbers
#include <stdio.h>
int main() {
int a,b;
printf("enter a: ");
scanf("%d",&a);
printf("enter b: ");
scanf("%d",&b);
a>b ? printf("a is greater"): printf("b is greater");
return 0;
}
Written By : Akshay Bhagade
Output :
enter a: 13
enter b: 23
b is greater
2) Check the number is positive or negative
#include <stdio.h>
int main() {
int number;
printf("enter number: ");
scanf("%d",&number);
number > 0 ? printf("Number is Positive"): printf("Number is Negative");
return 0;
}
Output :
enter number: 23
Number is Positive
If Statement
if a certain condition is true then a block of statements is executed
otherwise not.
Syntax :
if(condition)
{
// Statements to execute if
// condition is true
}
Written By : Akshay Bhagade
Example:
1)
#include <stdio.h>
int main() {
if (20 > 18) {
printf("20 is greater than 18");
}
return 0;
}
Output :
20 is greater than 18
2)
#include <stdio.h>
int main() {
int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");
}
}
Output :
x is greater than y
If-Else Statement
if a certain condition is true then a if block of statements is executed if
condition false then else block will be executed.
Syntax :
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Written By : Akshay Bhagade
Example:
1) print the greater number between two numbers
#include <stdio.h>
int main() {
int a,b;
printf("enter a: ");
scanf("%d",&a);
printf("enter b: ");
scanf("%d",&b);
if(a > b){
printf("a is greater");
}else{
printf("b is greater");
}
return 0;
}
Output :
enter a: 23
enter b: 34
b is greater
2) Enter the percentage and check whether the student is pass or fail?
#include <stdio.h>
int main() {
int percentage ;
printf("enter total percentage: ");
scanf("%d",&percentage);
if(percentage >= 35){
printf("Student is Pass");
}else{
printf("Student is Fail");
}
return 0;
}
Written By : Akshay Bhagade
Output :
enter total percentage: 35
Student is Pass
More Questions :-
3) Enter the number and check whether the number is positive or
negative.
4) Enter the number and check whether the number is even or odd.
5) Enter the year and check whether it is Leap year or Not.
6) Enter the purchase and sold amount and declare whether the profit or
loss happened.
7) Enter the age to check if the person is eligible for voting or not.
Ladder If-Else-if Statement
The if else if statements are used when the user has to decide
among multiple options.
if a certain condition is true then the particular block of statements
is executed If none of the conditions is true, then the final else
statement will be executed.
Syntax :
if (condition1) {
// Code to execute if condition1 is true
}
else if (condition2) {
// Code to execute if condition1 is false and condition2 is true
}
else if (condition3) {
// Code to execute if condition1 and condition2 are false, and condition3 is
true
}
else {
// Code to execute if all above conditions are false
}
Written By : Akshay Bhagade
Example:
1) Take input from the user and print the number is positive or negative
or zero.
#include <stdio.h>
int main() {
int number;
printf("enter number: ");
scanf("%d",&number);
if(number > 0){
printf("you enter positive number...");
}
else if(number < 0){
printf("you enter negative number...");
}
else{
printf("you enter the zero...");
}
return 0;
}
Output :
enter number: 0
you enter the zero…
enter number: -8
you enter negative number...
enter number: 12
you enter positive number...
Written By : Akshay Bhagade
2) Write a program to find the maximum between three number
#include <stdio.h>
int main() {
int a, b, c;
// Get input from the user
printf("Enter three numbers: n");
scanf("%d",&a);
scanf("%d",&b);
scanf("%d",&c);
if(a > b && a > c ){
printf("%d is Greater...",a);
}
else if(b > a && b > c ){
printf("%d is Greater...",b);
}
else{
printf("%d is Greater...",c);
}
return 0;
}
Output :
Enter three numbers:
45
23
56
56 is Greater...
More Questions :-
3) Build the Calculator.
4) Write a c program to input marks of five subjects eng,hindi,mar,maths,
phy, calculate percentage and print grade according to the following.
- Grade Merit — > percentage in between 90-100.
- Grade Distinction — > percentage in between 75-90.
- Grade First Class— > percentage in between 60-75.
- Grade Second Class— > percentage in between 45-60.
- Grade Pass— > percentage in between 35-45.
- Fail — > percentage less than 35.
Written By : Akshay Bhagade
Nested If-Else Statement
A nested if-else statement is an if statement inside another if statement.
The general syntax of nested if-else statement in C is as follows:
Syntax :
if (condition1) {
/* code to be executed if condition1 is true */
if (condition2) {
/* code to be executed if condition is true */
} else {
/* code to be executed if condition is false */
}
} else {
/* code to be executed if condition1 is false */
}
Example:
1) Check the given number is positive or negative or zero. If the number
is positive then the check number is even or odd..
#include <stdio.h>
int main() {
int num = 7;
if (num > 0) {
printf("The number is positive.n");
if (num % 2 == 0) {
printf("The number is even.n");
} else {
printf("The number is odd.n");
}
} else {
if (num < 0) {
printf("The number is negative.n");
} else {
printf("The number is zero.n");
}
}
return 0;
}
Written By : Akshay Bhagade
Output :
The number is positive.
The number is odd.
Switch Statement
Switch case statement evaluates a given expression and based on the
evaluated value(matching a certain condition), it executes the statements
associated with it. Basically, it is used to perform different actions based
on different conditions(cases).
Rules of the switch case statement
Following are some of the rules that we need to follow while using the
switch statement:
1. In a switch statement, the “case value” must be of “char” and
“int” type.
2. There can be one or N number of cases.
3. The values in the case must be unique.
4. Each statement of the case can have a break statement. It is
optional.If there is no break statement found in the case, all the
cases will be executed present after the matched case.
5. The default Statement is also optional.
Syntax :
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if all cases are not matched;
}
Written By : Akshay Bhagade
Example:
1) print the value of the given number using the switch statement.
#include <stdio.h>
int main() {
int num = 2;
switch (num) {
case 1:
printf("Value is 1n");
break;
case 2:
printf("Value is 2n");
break;
case 3:
printf("Value is 3n");
break;
default:
printf("Value is not 1, 2, or 3n");
break;
}
return 0;
}
Output :
Value is 2
2) Write a c program to input the day number and print week day.
#include <stdio.h>
int main()
{
int day = 2;
switch (day) {
case 1:
printf("Monday");
break;
Written By : Akshay Bhagade
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid Input");
break;
}
return 0;
}
Output :
Tuesday
3) enter an alphabet and check whether it is vowel or consonant.
4) write a c program to input a month number and print no of days in that
month.
Written By : Akshay Bhagade
Chapter 4-Loops in C
Loops in programming are used to repeat a block of code until the
specified condition is reached. A loop statement allows programmers to
execute a statement or group of statements multiple times without
repetition of code.
● For Loop
● While Loop
● Do While Loop
● Nested For Loop
for Loop
for loop in C programming is a repetition control structure
that allows programmers to write a loop that will be executed a
specific number of times.
Syntax :
#include <stdio.h>
int main()
{
for (initialization; condition; increment/decrement){
// statements inside the body of loop
}
return 0;
}
Example : 1) print the 1 to 10 number.
#include <stdio.h>
int main() {
int i;
for (i = 1; i <= 10; i++)
{
printf("%d ", i);
}
return 0;
}
Written By : Akshay Bhagade
Output :
1 2 3 4 5 6 7 8 9 10
More Questions :-
1) print the sum of n natural number
2) print the factorial.
3) write a c program to print all even numbers between 1 to 100.
4) write a program to print a multiplication table of any number.
5) print Fibonacci Series.
While Loop
Syntax :
#include <stdio.h>
int main() {
// Initialization
while (condition) {
statement
increment/decrement
}
return 0;
}
Example :
1) print the 1 to 10 number.
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("%d", i);
i++;
}
return 0;
}
Output :
1 2 3 4 5 6 7 8 9 10
Written By : Akshay Bhagade
More Questions :-
1) print Fibonacci Series.
2) All the above question of for loops
Mid/Hard Level Questions :-
1) Take 10 numbers from the user and count how many there are
positive, negative and zero numbers.
2) print the sum of digits.If number is 56 then answer is 11 (5+6=11)
3) write a c program to check if a given number is prime or not.
4) print the reverse number for e.g. number is 156 then output is 651
5) Check the entered number is palindrome or not.
Do-while Loop
do/while will always be executed at least once, even if the condition
is false, because the code block is executed before the condition is
checked.
Syntax :
#include <stdio.h>
int main() {
// Initialization
do {
statement
increment/decrement
} while (condition);
return 0;
}
Example :
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d n", i);
i++;
}while (i <= 10);
return 0;
}
Written By : Akshay Bhagade
Output :
1 2 3 4 5 6 7 8 9 10
Nested for Loop
loop inside another loop. This is called a nested loop. The "inner
loop" will be executed one time for each iteration of the "outer loop"
Example :
#include <stdio.h>
int main() {
int i, j;
// Outer loop
for (i = 1; i <= 2; i++) {
printf("Outer: %dn", i);
// Inner loop
for (j = 1; j <= 3; j++) {
printf(" Inner: %dn", j);
}
}
return 0;
}
Output :
Outer: 1
Inner: 1
Inner: 2
Inner: 3
Outer: 2
Inner: 1
Inner: 2
Inner: 3
Written By : Akshay Bhagade
Star Pattern Questions :-
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Number left
half pyramid
*
* *
* * *
* * * *
* * * * *
left half
pyramid
* * * * *
* * * *
* * *
* *
*
Inverted left
half pyramid
*
* *
* * *
* * * *
* * * * *
right half
pyramid
* * * * *
* * * *
* * *
* *
*
inverted
right half
pyramid
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
floyd's
triangle
*****
* *
* *
* *
*****
hollow
rectangle;
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
triangle 1_0
******
******
******
******
******
solid rhombus
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
Num pyramid
Advance Pattern :
*
***
*****
*******
*********
*********
*******
*****
***
*
diamond pattern
* *
** **
*** ***
**** ****
**********
**********
**** ****
*** ***
** **
* *
butterfly Pattern
Jump Statements :-
- Break
- Continue
Written By : Akshay Bhagade
Break :-
The break statement can also be used to exit from a loop.
Example :
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
break;
}
printf("%d", i);
}
return 0;
}
Output :
0123
Continue:-
The continue statement skips one iteration (in the loop) if a specified
condition occurs, and continues with the next iteration in the loop.
Example :
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
printf("%d ", i);
}
return 0;
}
Output :
0 1 2 3 5 6 7 8 9
Written By : Akshay Bhagade
Chapter 5 - Arrays
Arrays are used to store multiple values in a single variable, instead
of declaring separate variables for each value. similar data items
stored in contiguous memory locations.
It can be used to store the collection of primitive data types such as
int, char, float, etc., and also derived and user-defined data types
such as pointers, structures, etc.
Syntax:
data_type array_name [size];
data_type array_name [size] = {value1, value2, ... valueN};
It is possible to initialize an array during declaration. For example,
int mark[5] = {46, 87, 81, 74, 90};
You can also initialize an array like this.
int mark[] = {46, 87, 81, 74, 90};
Example :
#include <stdio.h>
int main() {
int myNumbers[] = {46, 87, 81, 74, 90};
printf("%d", myNumbers[0]);
return 0;
}
Output :
46
Written By : Akshay Bhagade
Change an Array Element
To change the value of a specific element, refer to the index number:
#include <stdio.h>
int main() {
int myNumbers[] = {46, 87, 81, 74, 90};
myNumbers[0] = 66;
printf("%d", myNumbers[0]);
return 0;
}
Output :
66
Array with For loop
Also we caṇ print array elements with the for loop.
#include <stdio.h>
int main() {
int myNumbers[] = {46, 87, 81, 74, 90};
int i;
for(i = 0; i < 4; i++) {
printf("%dn", myNumbers[i]);
}
return 0;
}
Output :
46
87
81
74
90
Written By : Akshay Bhagade
Another common way to create arrays, is to specify the size of the
array, and add elements later:
#include <stdio.h>
int main() {
// Declare an array of four integers:
int myNumbers[4];
// Add elements to it
myNumbers[0] = 46;
myNumbers[1] = 87;
myNumbers[2] = 81;
myNumbers[3] = 74;
myNumbers[4] = 90;
printf("%dn", myNumbers[2]);
return 0;
}
Output :
81
Get Array Size or Length
#include <stdio.h>
int main() {
int myNumbers[] = {46, 87, 81, 74, 90};
printf("%d", sizeof(myNumbers));
return 0;
}
Output: 20 - It is because the sizeof operator returns the size of a type in
bytes.
- for calculating size of array divides the size of the array by the size of
one array element.
Written By : Akshay Bhagade
calculating size of array:
#include <stdio.h>
int main() {
int myNumbers[] = {46, 87, 81, 74, 90};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
printf("%d", length);
return 0;
}
Output :
5
Using for loop when we don't know the size of an array:
#include <stdio.h>
int main() {
int myNumbers[] = {46, 87, 81, 74, 90};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
int i;
for (i = 0; i < length; i++) {
printf("%dt", myNumbers[i]);
}
return 0;
}
Output :
46 87 81 74 90
Written By : Akshay Bhagade
Input Array From User:
Q. Program to take 5 values from the user and store them in an array
#include <stdio.h>
int main() {
int values[5];
printf("Enter 5 integers: ");
// taking input and storing it in an array
for(int i = 0; i < 5; i++) {
scanf("%d", &values[i]);
}
printf("Displaying integers: ");
// printing elements of an array
for(int i = 0; i < 5; i++) {
printf("n%d", values[i]);
}
return 0;
}
Output :
Enter 5 integers: 45
87
67
98
45
Displaying integers:
45
87
67
98
45
Written By : Akshay Bhagade
Questions:
1) Enter an array and take any input number from the user and check
whether the number exists in the array or not.
2) Enter an array and find the minimum number in that array.
3) Enter an array and find the maximum number in that array.
4) Program to find the sum and average of n numbers using arrays.
5) Sorting an array.
2D Arrays:
A multidimensional array is basically an array of arrays.
If you want to store data as a tabular form, like a table with rows and
columns, Then we use multidimensional arrays.
E.g.
int matrix[3][3] = {};
E.g.
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
Written By : Akshay Bhagade
Example:
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
printf("%d", matrix[0][2]);
return 0;
}
Output :
2
How To Change 2D Array Element:
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;
printf("%d", matrix[0][0]); // Now outputs 9 instead of 1
return 0;
}
Output :
9
Written By : Akshay Bhagade
Print 2D Array Element By Using Loop:
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++) {
for (j = 0; j < 3; j++) {
printf("Element at x[%i][%i]: ", i, j);
printf("%dn", matrix[i][j]);
}
}
return 0;
}
Output :
Element at x[0][0]: 1
Element at x[0][1]: 4
Element at x[0][2]: 2
Element at x[1][0]: 3
Element at x[1][1]: 6
Element at x[1][2]: 8
Taking Array Elements from User and print the array
#include <stdio.h>
int main() {
int arr[3][3],i,j;
// taking user input
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("Enter the Elements [%d][%d]: ",i,j);
Written By : Akshay Bhagade
scanf("%d",&arr[i][j]);
}
}
printf("nPrinting The Element......n");
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("%dt",arr[i][j]);
}
printf("n");
}
return 0;
}
Output :
Enter the Elements [0][0]: 34
Enter the Elements [0][1]: 67
Enter the Elements [0][2]: 34
Enter the Elements [1][0]: 09
Enter the Elements [1][1]: 86
Enter the Elements [1][2]: 12
Enter the Elements [2][0]: 45
Enter the Elements [2][1]: 67
Enter the Elements [2][2]: 34
Printing The Element......
34 67 34
9 86 12
45 67 34
Questions:
1) Enter an 2D array and take any input number from the user and check
whether the number exists in the array or not.
2) Addition Of Two Matrices
3) Multiplication of Two Matrix
4) Sum of Diagonal Elements in Square Matrix.
Written By : Akshay Bhagade
Chapter 6 - Strings
A String in C programming is a sequence of characters terminated
with a null character ‘0’. The C String is stored as an array of
characters. The difference between a character array and a C string
is that the string in C is terminated with a unique character ‘0’.
Note: %s is the format specifier to print a string in C.
Syntax:
char variableName[size];
For example:
char name[] = "c string";
When the compiler encounters a sequence of characters enclosed in
the double quotation marks, it appends a null character 0 at the
end by default.
There are two methods to do this:
1) Using Char Array -
without declaring the size of the array
char str[] = {'C', 'o', 'm', 'p', 'u', 'f', 'i', 'e', 'l', 'd', '0'};
by declaring the size of the array
char str[11] = {'C', 'o', 'm', 'p', 'u', 'f', 'i', 'e', 'l', 'd', '0'};
2) Using String Literal -
without declaring the size of the array
char str[]="Compufield";
by declaring the size of the array
char str[11]="Compufield";
Written By : Akshay Bhagade
Example :
#include <stdio.h>
int main() {
char str[11] = {'C', 'o', 'm', 'p', 'u', 'f', 'i', 'e', 'l', 'd', '0'};
char str1[11] = "Compufield";
printf("String by char array method: %sn", str);
printf("String by String Literal method: %sn", str1);
return 0;
}
Output :
String by char array method: Compufield
String by String Literal method: Compufield
Accessing The String:
As the string is array of characters, we can access the characters of the
string with their index number. The string index starts with 0.
%c is a format specifier to print a single character.
Example :
#include <stdio.h>
int main() {
char str[10]="Compufield";
printf("%c", str[5]);
return 0;
}
Output :
f
Written By : Akshay Bhagade
Modify The String:
To change the value of a specific character in a string, refer to the index
number, and use single quotes:
Example :
#include <stdio.h>
int main() {
char str[]="HelloWorld";
str[4] = 'i';
printf("%s", str);
return 0;
}
Output :
HelliWorld
Loops Through String:
We can also loop through the characters of a string, using a for loop:
Example :
#include <stdio.h>
int main() {
char str[10]="Compufield";
int length = sizeof(str) / sizeof(str[0]);
for (int i = 0; i < length; i++) {
printf("%cn", str[i]);
}
return 0;
}
Output :
Written By : Akshay Bhagade
Take Input String from User:
1) Using scanf()
Example :
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s", name);
return 0;
}
Output :
Enter name: Gaurav Therade
Name: Gaurav.
Note:
The scanf() function reads the sequence of characters until it encounters
whitespace (space, newline, tab, etc.).
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output :
Enter name: Gaurav Therade
Name: Gaurav Therade
Written By : Akshay Bhagade
String Functions in C:
There are many important string functions defined in "string.h" library.
No. Function Description
1) strlen(string_name) returns the length of the string name.
2) strcpy(destination,
source)
copies the contents of source string to
destination string.
3) strcat(first_string,
second_string)
concats or joins first string with second string.
The result of the string is stored in first string.
4) strcmp(first_string,
second_string)
compares the first string with second string. If
both strings are same, it returns 0.
5) strrev(string) returns reverse string.
6) strlwr(string) returns string characters in lowercase.
7) strupr(string) returns string characters in uppercase.
Example :
1) find the length of string
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Compufield";
char str2[20];
printf("Length of str1: %dn", strlen(str1));
return 0;
}
Output :
Length of str1: 10
Written By : Akshay Bhagade
Example :
2) copy string from another string
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "C programming";
char str2[20];
// copying str1 to str2
strcpy(str2, str1);
puts(str2); // C programming
return 0;
}
Output :
C programming
Example :
3) concatenate string
#include<stdio.h>
#include <string.h>
int main(){
char ch1[10]="Hellot";
char ch2[10]="World";
strcat(ch1,ch2);
printf("%s",ch1);
return 0;
}
Output :
Hello World
Example :
4) Compared Strings
#include <stdio.h>
#include <string.h>
int main() {
Written By : Akshay Bhagade
char str1[20], str2[20];
printf("Enter 1st string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter 2nd string: ");
fgets(str2, sizeof(str2), stdin);
if (strcmp(str1, str2) == 0) {
printf("Strings are equaln");
} else {
printf("Strings are not equaln");
}
return 0;
}
Output :
Enter 1st string: hello
Enter 2nd string: hello
Strings are equal
Example :
5) Reverse the Strings
#include<stdio.h>
#include <string.h>
int main(){
char str[20];
printf("Enter string: ");
gets(str);
printf("String is: %s",str);
printf("nReverse String is: %s",strrev(str));
return 0;
}
Output :
String is: dog
Reverse String is: god
Written By : Akshay Bhagade
Example :
6) Convert Strings into Lowercase & Uppercase
#include<stdio.h>
#include <string.h>
int main(){
char str[20]= "CompuField";
printf("String is: %s",str);
printf("nLower String is: %s",strlwr(str));
printf("nUpper String is: %s",strupr(str));
return 0;
}
Output :
String is: CompuField
Lower String is: compufield
Upper String is: COMPUFIELD
Questions :
1) reverse the string without using the rev function.
2) Check if the string is palindrome or not.
3) Write a program in C to count the total number of words in a string.
4) Write a program in C to count the total number of alphabets, digits and
special characters in a string.
5) Write a program in C to count the total number of vowels or
consonants in a string.
6) Write a C program to sort a string array in ascending order.
7) Write a program in C to find the frequency of characters.
Written By : Akshay Bhagade
Chapter 7 - Functions
A function is a block of code that performs a specific task when a
function is called. They provide a way to break down a program into
smaller, manageable units, which makes the code more readable,
reusable, and maintainable. They are of two types: Built-in and User
Defined.
types of Functions:
Built in Functions: are the functions which are declared in the C header
files such as scanf(), printf(), gets(), puts(), sqrt(), pow () etc.
User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the
complexity of a big program and optimises the code.
They are of two types of user-defined function;
1. Function with a return value
2. Function without a return value (void functions)
Written By : Akshay Bhagade
Function without Return value:
1) Print name using function
#include<stdio.h>
// Function Declaration
void printName();
int main ()
{
printf("Hello ");
printName(); // Function Call
return 0;
}
// Function Definition
void printName()
{
printf("Ruhi");
}
Output :
Hello Ruhi
2) Print name using function with parameter/Arguments.
#include <stdio.h>
// Function Declaration
void greet(char name[]);
int main()
{
greet("Ekayaa"); // Function Call
return 0;
}
// Function Definition
void greet(char name[])
{
printf("Hello, %s!", name);
}
Output :
Hello, Ekayaa!
Written By : Akshay Bhagade
3) Sum of two number
#include<stdio.h>
void sum(); // Function Declaration
int main() // main method
{
printf("ncalculate the sum of two numbers:");
sum(); // Function call in main method
return 0;
}
void sum() // Function Definition
{
int a,b;
printf("nEnter two numbers: ");
scanf("%d %d",&a,&b);
printf("The sum is: %d",a+b);
}
Output :
Enter two numbers: 23 67
The sum is: 90
Function with return value:
1) Sum of two number
#include <stdio.h>
// Function Declaration
int add(int a, int b);
int main()
{
int result = add(8, 9); //Function call
printf("The sum of a + b = %dn", result);
return 0;
}
// Function Definition
int add(int a, int b)
{
return a + b;
}
Output :
The sum of a + b = 17
Written By : Akshay Bhagade
Multiple Parameters
Inside the function,we can add as many parameters
#include <stdio.h>
void myFunction(char name[], int age) {
printf("Hello %s. You are %d years oldn", name, age);
}
int main() {
myFunction("Akaay", 3);
myFunction("Driti", 14);
myFunction("Gaurav", 30);
return 0;
}
Output :
Hello Akaay. You are 3 years old
Hello Driti. You are 14 years old
Hello Gaurav. You are 30 years old
You can also pass arrays to a function:
#include <stdio.h>
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
printf("%dn", myNumbers[i]);
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Written By : Akshay Bhagade
Questions :
1) Write a program in C to swap two numbers using a function.
2) Write a program in C to check if a given number is even or odd using
the function.
3) Write a program in C to find the sum of the series
4) program to calculate the average of five numbers.
5) Convert Celsius to Fahrenheit
6) print the factorial using a function.
Maths Function:
There is also a list of maths functions available, that allows you to
perform mathematical tasks on numbers.To use them, you must include
the math.h header file in your program:
1) To find the square root of a number, use the sqrt() function:
#include <stdio.h>
#include <math.h>
int main() {
printf("%f", sqrt(16));
return 0;
}
Output :
4.000000
2) The pow() function returns the value of x to the power of y (xy):
#include <stdio.h>
#include <math.h>
int main() {
printf("%f", pow(4, 3));
return 0;
}
Output :
64.000000
Written By : Akshay Bhagade
Recursion :
Recursion is the technique of making a function call itself. This
technique provides a way to break complicated problems down into
simple problems which are easier to solve.
Question:
1) print the number of 1 to 5 and also reverse order using recursion.
#include <stdio.h>
void printnum(int n) {
if (n == 6) {
return;
}
printf("%dt", n);
printnum(n + 1);
}
int main() {
int n = 1;
printnum(n);
return 0;
}
Output :
1 2 3 4 5
2) calculate sum of n natural numbers using recursion.
#include <stdio.h>
// Function prototype
void printsum(int i, int n, int sum);
int main() {
int num;
printf("Enter the number: ");
scanf("%d", &num);
printsum(1, num, 0);
return 0;
}
Written By : Akshay Bhagade
void printsum(int i, int n, int sum) {
if (i == n) {
sum += i;
printf("sum is: %dn", sum);
return;
}
sum += i;
printsum(i + 1, n, sum);
}
Output :
Enter the number: 5
sum is: 15
3) find the factorial by using recursion.
#include <stdio.h>
// Recursive function
int printfact(int n) {
if (n == 1 || n == 0) {
return 1;
}
int fact_1 = printfact(n - 1);
int fact_2 = n * printfact(n - 1);
return fact_2;
}
int main() {
int num;
printf("Enter the number: ");
scanf("%d", &num);
int result = printfact(num);
printf("Factorial of %d is %dn", num, result);
return 0;
}
Output :
Enter the number: 5
Factorial of 5 is 120
Written By : Akshay Bhagade
Chapter 8 - C Structures
A structure is a container to store multiple types of variables. The
variables stored in a structure are called member variables. Member
variables are related to each other, and they are combined to
provide complete information about an object.
The ,struct keyword is used to define the structure. Let's see the
syntax to define the structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
E.G.
struct employee
{ int id;
char name[20];
float salary;
};
Key Points of C Structure
● The structure is declared using the “struct” keyword.
● Structure allocates contiguous memory to all its member variables.
● You can only declare member variables in a structure.
● You cannot initialise the member variables during their declaration.
● To access the member variables, use the dot operator.
● Structure member variables are initialised in the same order as their
declaration.
Written By : Akshay Bhagade
Example :
#include <stdio.h>
struct book{
char title[50];
char author[30];
double price;
int pages;
};
int main(){
struct book book1 = {"An Era of Darkness", "Shashi Tharoor", 599.00,
360};
printf("Title: %s n", book1.title);
printf("Author: %s n", book1.author);
printf("Price: %.2fn", book1.price);
printf("Pages: %d n", book1.pages);
return 0;
}
Output :
Title: An Era of Darkness
Author: Shashi Tharoor
Price: 599.00
Pages: 360
Keyword typedef :
We use the typedef keyword to create an alias name for data types. It is
commonly used with structures to simplify the syntax of declaring
variables.
Example :
#include <stdio.h>
#include <string.h>
// struct with typedef person
typedef struct Person {
char name[50];
int citNo;
float salary;
} employee;
Written By : Akshay Bhagade
int main() {
// create struct Person variable with aliased name employee
employee p1;
// assign value to name of p1
strcpy(p1.name, "Gaurav Therade");
// assign values to other p1 variables
p1.citNo = 411001;
p1. salary = 25000;
// print struct variables
printf("Name: %sn", p1.name);
printf("Citizenship No.: %dn", p1.citNo);
printf("Salary: %.2f", p1.salary);
return 0;
}
Output :
Name: Gaurav Therade
Citizenship No.: 411001
Salary: 25000.00
Example :
Taking input from user how many person and take details of all person
and print the details by using loops
#include <stdio.h>
#include <string.h>
typedef struct Person {
char name[50];
int citNo;
float salary;
} employee;
int main() {
int numPersons;
Written By : Akshay Bhagade
// Input the number of persons
printf("Enter the number of persons: ");
scanf("%d", &numPersons);
// Array of employees based on the number of persons
employee emp[numPersons];
// Input details for each person
for (int i = 1; i <= numPersons; i++) {
printf("Enter details for person %d:n", i);
// Input name
printf("Name: ");
scanf(" %[^n]s", emp[i].name);
// Input city number
printf("City No.: ");
scanf("%d", &emp[i].citNo);
// Input salary
printf("Salary: ");
scanf("%f", &emp[i].salary);
}
// Print details for each person
printf("nDetails of all the Employees :n");
for (int i = 1; i <= numPersons; i++) {
printf("Person %d:n", i);
printf("Name: %sn", emp[i].name);
printf("Citizenship No.: %dn", emp[i].citNo);
printf("Salary: %.2fn", emp[i].salary);
}
return 0;
}
Written By : Akshay Bhagade
Union in C
structures and unions both serve the purpose of grouping data
members into a single unit, they have different use cases due to
their fundamental differences in memory allocation
structures and unions are similar in that they both allow you to
define custom data types.
Structures are typically used when you want to store and manipulate
different types of data together as a single entity. Each member of a
structure has its own memory space, and you can access them
independently.
Unions are used when you need to store different types of data in the
same memory location. Unlike structures, where each member has its
own memory space, in a union, all members share the same memory
space. This means that modifying one member of a union can affect the
values of other members.
When we Use Structure:
Use structures when you have a collection of related data elements
that you want to access independently and manipulate separately.
When we Use Union:
Use unions when you need to save memory and when you know
that only one member of the union will be accessed at any given time.
Unions are commonly used in situations like implementing variant types
or when dealing with hardware interfaces where memory conservation is
crucial.
Written By : Akshay Bhagade
Example:
#include <stdio.h>
union student {
int id;
float marks;
char grade;
};
int main() {
union student s;
s.id = 101;
printf("Student ID: %dn", s.id);
s.marks = 85.5;
printf("Student Marks: %fn", s.marks);
s.grade = 'A';
printf("Student Grade: %cn", s.grade);
return 0;
}
Output :
Student ID: 101
Student Marks: 85.500000
Student Grade: A
Difference between Struct & Union:
Written By : Akshay Bhagade
Features Struct Union
Memory Allocation Each member has their
own memory location
All members share the same memory
location
Size Sum of sizes of all
members
Size of the largest member
Usage Store related data Save memory by sharing memory location
Initialization Members can be initialized
individually
Only the first member can be initialized
Accessing Members Dot (.) operator Dot (.) or arrow (->) operator
Chapter 9 - Pointer
A Variable that stores the memory address of another variable.
Syntax:
int num = 3;
int *ptr = &num;
int num_1 = *ptr;
Note:
* is value of address operator
& is address of operator
num num_1 ptr
34 34 4673
4673 4674 4677
** different ways to declare pointers, pointers also be an int, float and
char.
Format Specifier for pointers:
“%p” or “%u” - unsigned int
Example:
1) Print the address of the operator.
#include<stdio.h>
int main(){
int num = 34;
int *ptr = &num;
printf("%pn",&num);
printf("%pn",ptr);
printf("%pn",&ptr);
return 0;
}
Written By : Akshay Bhagade
2) Print the Value of Operator.
#include<stdio.h>
int main(){
int num = 34;
int *ptr = &num;
printf("printing the values in diffrent waysn");
printf("%dn",num);
printf("%dn",*ptr);
printf("%dn",*(&num));
return 0;
}
3) Guess the Output of the following code.
#include<stdio.h>
int main(){
int a;
int *ptr;
ptr = &a;
*ptr = 0;
printf("a is: %dn",a);
printf("*ptr is: %dn",*ptr);
*ptr += 5;
printf("a is: %dn",a);
printf("*ptr is: %dn",*ptr);
(*ptr)++;
printf("a is: %dn",a);
printf("*ptr is: %dn",*ptr);
return 0;
}
Written By : Akshay Bhagade
Pointer to pointer:
A variable that stores the memory address of another pointer.
num pptr ptr
34 4677 4673
4673 4676 4677
Syntax:
float marks = 90.00;
float *ptr = &marks;
float **pptr = &ptr;
Example:
#include<stdio.h>
int main(){
float marks = 90.00;
float *ptr = &marks;
float **pptr = &ptr;
printf("%.2fn",**pptr);
return 0;
}
Pointers in Function Call:
1) Call by Value : We pass the value of the variable as an argument.
#include<stdio.h>
void square(int n);
int main(){
int number = 4;
square(number);
printf("number = %dn",number);
return 0;
}
void square(int n){
n = n * n;
printf("square = %dn",n);
}
Written By : Akshay Bhagade
2) Call By Reference :
We Pass Address of the variable as an argument.
#include<stdio.h>
void square_1(int *n);
int main(){
int number = 4;
square_1(&number);
printf("number = %dn",number);
return 0;
}
void square_1(int* n){
*n = (*n) * (*n);
printf("square = %dn",*n);
}
Questions :
1) Write a C program to swap two numbers using a pointer.
2) Write a C program to calculate and return sum, product and average
by using a function.
Written By : Akshay Bhagade
Chapter 10 - File I/O
What are files in C?
A file is used to store huge data. C provides multiple file management
functions like file creation, opening and reading files, Writing to the file,
and closing a file. The file is used to store relevant data and file handling
in C is used to manipulate the data.
Operation of Files :
1) Open a File
2) Close File
3) Create a File
4) Read From a File
5) Write in a File
Types of Files :
1) Text Files (textual data) - .txt, .c
2) binary Files (binary data) - .exe,.mp3,.jpg
File Pointer :
For Performing operations on the file in c a special pointer is used called
File pointer that can be declared as: FILE *fptr;
Opening & Closing a File :
#include <stdio.h>
int main(){
FILE *fptr;
fptr = fopen("filename", "mode");
// some work on file
fclose(fptr); //closing file
return 0;
}
Written By : Akshay Bhagade
File Opening Modes :
1) "r" - Open to read
2) "rb" - Open to read in binary
3) "w" - Open to write
4) "wb" - Open to write in binary
5) "a" - Open to append
Reading from a file :
char c;
fscanf(fptr,"%c",&c);
Example:
#include <stdio.h>
int main(){
FILE *fptr;
fptr = fopen("test.txt", "r");
char ch;
fscanf(fptr,"%c",&ch);
printf("%c",ch);
fscanf(fptr,"%c",&ch);
printf("%c",ch);
fscanf(fptr,"%c",&ch);
printf("%c",ch);
fscanf(fptr,"%c",&ch);
printf("%c",ch);
fscanf(fptr,"%c",&ch);
printf("%c",ch);
fclose(fptr);
return 0;
}
Writing to a file :
char ch = 'H';
fprintf(fptr,"%c",ch);
Written By : Akshay Bhagade
Example:
#include <stdio.h>
int main(){
FILE *fptr;
fptr = fopen("test.txt", "w");
fprintf(fptr,"%c", 'H');
fprintf(fptr,"%c", 'e');
fprintf(fptr,"%c", 'y');
fprintf(fptr,"%c", '!');
fclose(fptr);
return 0;
}
Writing to a file :
fgetc(fptr);
fputc('A',fptr);
Example:
1) Read from the file
#include <stdio.h>
int main(){
FILE *fptr;
fptr = fopen("test.txt", "r");
printf("%cn",fgetc(fptr));
printf("%cn",fgetc(fptr));
printf("%cn",fgetc(fptr));
printf("%cn",fgetc(fptr));
fclose(fptr);
return 0;
}
Written By : Akshay Bhagade
2) write into a file
#include <stdio.h>
int main(){
FILE *fptr;
fptr = fopen("test.txt", "w");
fputc('A',fptr);
fputc('K',fptr);
fputc('A',fptr);
fputc('A',fptr);
fputc('Y',fptr);
fclose(fptr);
return 0;
}
EOF (End Of File) : fgetc returns EOF to show that the file has ended
#include <stdio.h>
int main(){
FILE *fptr;
fptr = fopen("test.txt", "r");
char ch;
ch = fgetc(fptr);
while(ch != EOF){
printf("%c",ch);
ch = fgetc(fptr);
}
fclose(fptr);
return 0;
}
Questions :
1) Make a program to input student information from user & enter into file
2) wap to write all the odd numbers from 1 to 100 in a file
3) Write a multiplication table of the user entered number in the file.
4) take student number and subjects of each student & calculate their sum
and average store them into the file.
Written By : Akshay Bhagade
Chapter 11 - Dynamic Memory Allocation in c
Dynamic memory allocation is a way to allocate memory to a data structure
during the runtime.
Following function are available in C to perform Dynamic memory Allocation:
1) malloc()
2) Calloc()
3) free()
4) realloc()
malloc() function:
Malloc stands for memory allocation. It takes a number of bytes to be
allocated as an input and returns a pointer of type void.
Syntax:
#include<stdio.h>
#include<stdlib.h>
int main(){
int *ptr;
ptr = (int *)malloc(5* sizeof(int));
ptr[0] = 1;
ptr[1] = 2;
ptr[2] = 3;
ptr[3] = 4;
ptr[4] = 5;
for(int i =0;i<5;i++){
printf("n %d",ptr[i]);
}
return 0;
}
Written By : Akshay Bhagade
calloc() function:
Calloc stands for continuous allocation. It initialises each memory block
with a default value of 0.
Syntax:
#include<stdio.h>
#include<stdlib.h>
int main(){
int *ptr;
ptr = (int *)calloc(5, sizeof(int));
for(int i =0;i<5;i++){
printf("n %d",ptr[i]);
}
return 0;
}
Note: If the space is not sufficient in the device, memory allocation fails and
a NULL pointer is returned.
free() function:
We use the free() function to deallocate the memory or use it to free
memory that is allocated by using malloc & calloc.
Syntax:
#include<stdio.h>
#include<stdlib.h>
int main(){
int *ptr;
int n;
printf("enter the n: ");
scanf("%d",&n);
ptr = (int *)calloc(n, sizeof(int));
free(ptr);
Written By : Akshay Bhagade
ptr = (int *)calloc(2, sizeof(int));
for(int i =0;i<2;i++){
printf("n %d",ptr[i]);
}
return 0;
}
realloc() function:
Realloc is used to increase or decrease memory size using the same
pointer & size. E.g. ptr = realloc(ptr, newSize);
Syntax:
int *ptr;
ptr = (int *)calloc(5, sizeof(int));
ptr = realloc(ptr, 8);
Example: allocate memory for 5 numbers then increase it to 8 numbers.
#include<stdio.h>
#include<stdlib.h>
int main(){
int *ptr;
ptr = (int *)calloc(5, sizeof(int));
printf("Enter number 5: ");
for(int i = 1; i <= 5; i++){
scanf("%d",&ptr[i]);
}
ptr = realloc(ptr, 8);
printf("Enter number 8: ");
for(int i = 0; i < 8; i++){
scanf("%d",&ptr[i]);
}
//print
for(int i = 1; i <= 8; i++){
printf("number %d is %dn",i,ptr[i]);
}
return 0;
}
Written By : Akshay Bhagade
Questions :
1) WAP to allocate memory of size n, where n is entered by the user.
2) Create an array of size 5 & enter its values from the user.
3) Allocate memory to store the first 5 odd numbers, then reallocate it to
store the first 6 even numbers.
Written By : Akshay Bhagade

More Related Content

PPTX
comp 122 Chapter 2.pptx,language semantics
floraaluoch3
 
PPT
C program
AJAL A J
 
PPTX
C_Programming_Language_tutorial__Autosaved_.pptx
Likhil181
 
PPTX
Each n Every topic of C Programming.pptx
snnbarot
 
PPTX
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel
 
PPTX
C programming language
Abin Rimal
 
PDF
C programing Tutorial
Mahira Banu
 
PPS
C programming session 02
Dushmanta Nath
 
comp 122 Chapter 2.pptx,language semantics
floraaluoch3
 
C program
AJAL A J
 
C_Programming_Language_tutorial__Autosaved_.pptx
Likhil181
 
Each n Every topic of C Programming.pptx
snnbarot
 
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel
 
C programming language
Abin Rimal
 
C programing Tutorial
Mahira Banu
 
C programming session 02
Dushmanta Nath
 

Similar to learn basic to advance C Programming Notes (20)

PDF
java or oops class not in kerala polytechnic 4rth semester nots j
ishorishore
 
PDF
C-PPT.pdf
chaithracs3
 
PPTX
C and C++ programming basics for Beginners.pptx
renuvprajapati
 
PPTX
C Programming Unit-1
Vikram Nandini
 
PPT
Unit 4 Foc
JAYA
 
PPT
Introduction to C Programming
MOHAMAD NOH AHMAD
 
PPTX
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
RutviBaraiya
 
PPTX
C programming
DipjualGiri1
 
PDF
C intro
SHIKHA GAUTAM
 
PPTX
C programming
PralhadKhanal1
 
PDF
UNIT1 PPS of C language for first year first semester
Aariz2
 
PPTX
C++ lecture 01
HNDE Labuduwa Galle
 
PPTX
Introduction%20C.pptx
20EUEE018DEEPAKM
 
PPTX
presentation_data_types_and_operators_1513499834_241350.pptx
KrishanPalSingh39
 
PDF
C Programming Language Introduction and C Tokens.pdf
poongothai11
 
PPTX
Fundamentals of computers - C Programming
MSridhar18
 
PDF
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
anilcsbs
 
PDF
Week 02_Development Environment of C++.pdf
salmankhizar3
 
PPTX
presentation_c_basics_1589366177_381682.pptx
KrishanPalSingh39
 
java or oops class not in kerala polytechnic 4rth semester nots j
ishorishore
 
C-PPT.pdf
chaithracs3
 
C and C++ programming basics for Beginners.pptx
renuvprajapati
 
C Programming Unit-1
Vikram Nandini
 
Unit 4 Foc
JAYA
 
Introduction to C Programming
MOHAMAD NOH AHMAD
 
BCP_u2.pptxBCP_u2.pptxBCP_u2.pptxBCP_u2.pptx
RutviBaraiya
 
C programming
DipjualGiri1
 
C intro
SHIKHA GAUTAM
 
C programming
PralhadKhanal1
 
UNIT1 PPS of C language for first year first semester
Aariz2
 
C++ lecture 01
HNDE Labuduwa Galle
 
Introduction%20C.pptx
20EUEE018DEEPAKM
 
presentation_data_types_and_operators_1513499834_241350.pptx
KrishanPalSingh39
 
C Programming Language Introduction and C Tokens.pdf
poongothai11
 
Fundamentals of computers - C Programming
MSridhar18
 
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
anilcsbs
 
Week 02_Development Environment of C++.pdf
salmankhizar3
 
presentation_c_basics_1589366177_381682.pptx
KrishanPalSingh39
 
Ad

Recently uploaded (20)

DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PDF
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PDF
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
family health care settings home visit - unit 6 - chn 1 - gnm 1st year.pptx
Priyanshu Anand
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Exploring-Forces 5.pdf/8th science curiosity/by sandeep swamy notes/ppt
Sandeep Swamy
 
NOI Hackathon - Summer Edition - GreenThumber.pptx
MartinaBurlando1
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
Ad

learn basic to advance C Programming Notes

  • 1. C Programming Notes What is Programming ? Computer Programming is a medium for us to Communicate with Computers What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. The main reason for its popularity is because it is a fundamental language in the field of computer science. Why Learn C? ● It is one of the most popular programming languages in the world ● If you know C, you will have no problem learning other popular programming languages such as Java, Python, C++, C#, etc, as the syntax is similar ● C is very fast, compared to other programming languages, like Java and Python ● C is very versatile; it can be used in both applications and technologies Variables Variables are containers for storing data values, like numbers and characters. It’s also the name of a memory location. In C, there are different types of variables for example: ● int - stores integers (whole numbers), without decimals, such as 123 or -123 ● float - stores floating point numbers, with decimals, such as 19.99 or -19.99 Written By : Akshay Bhagade
  • 2. ● Double - stores floating point numbers, with decimals, such as 19.99 or -19.99 ● char - stores single characters, such as 'a' or 'B'. Characters are surrounded by single quotes E.g. int num = 34, float number = 45.7, char name = ’A’ The general rules for naming variables are: ● Names can contain letters, digits and underscores ● Names must begin with a letter or an underscore (_) ● Names are case-sensitive (myVar and myVar are different variables) ● Names cannot contain whitespaces or special characters like !, #, %, etc. ● Reserved words (such as int) cannot be used as names Basic Data Types The data type specifies the size and type of information the variable will store. Data Type Size Description Exam ple int 2 or 4 bytes Stores whole numbers, without decimals 1 float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7 decimal digits 1.99 double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits 1.99 char 1 byte Stores a single character/letter/number, or ASCII values 'A' Written By : Akshay Bhagade
  • 3. Format Specifiers Format specifiers are used together with the printf() function to tell the compiler what type of data the variable is storing. It is basically a placeholder for the variable value. Data Type Format Specifiers ● int %i or %d ● float %f ● double %lf or %f ● char %c Keywords These are reserved words,whose meaning is already known to the compiler there are 32 keywords available in C Auto double int struck Break long else switch Case return enum typedef Char register extern union Const short float unsigned Continue signed for void Default size of goto volatile Do static if while Written By : Akshay Bhagade
  • 4. OUR FIRST C PROGRAM #include <stdio.h> int main() { printf("Hello, I am Learning C Programming"); return 0; } BASIC STRUCTURE OF A C PROGRAMMING Line 1: #include <stdio.h> is a standard input output header file library that lets us work with input and output functions, such as printf() (used in line 4). Header files add functionality to C programs. Line 2: The int keyword indicates that the main function will return an integer value. By convention, returning 0 indicates that the program terminated successfully. main(). This is called a function. Any code inside its curly brackets {} will be executed. Line 3: printf() is a function used to output/print text to the screen. In our example, it will output "Hello, I am Learning C with Harry". Line 4: return 0 ends the main() function. Line 5: Do not forget to add the closing curly bracket } to actually end the main function. Note that: Every C statement ends with a semicolon ; COMMENTS Comments are used to clarify something about the program in plain language.it is a way for us to add notes to our program.there are two types of comments in C 1. Single line comment : //This is a comment 2. Multi line comment : /* This is a multi line comment * Comments in a C program are not executed and ignored Written By : Akshay Bhagade
  • 5. Receiving input from the user In order to take input from the user and assign it to a variable, we use scanf() function. Syntax for using scanf ; #include <stdio.h> int main() { int number; printf("Enter a number: "); scanf("%d", &number); printf("You entered: %dn", number); return 0; } Note: & is important & is the “address of” operator and it means that the supplied value should be copied to the address which is indicated by variable i. CHAPTER 1- PRACTICE SET Q1. Write a c program to calculate area of a rectangle (a) Using hard coded inputs (b) Using inputs supplied by the user Q2. Calculate the area of a circle and modify the same program to calculate the circumference of the circle. Q3. Write a program to convert celsius (Centigrade degree temperature to fahrenheit) Written By : Akshay Bhagade
  • 6. Chapter 2- INSTRUCTIONS AND OPERATORS Operators are used to perform operations on variables and values. Types of Operator: ● Arithmetic operators ● Assignment operators ● Comparison operators ● Logical operators ● Bitwise operators Arithmetic Operators Arithmetic operators are used to perform common mathematical operations. Written By : Akshay Bhagade Operator Name Description Example + Addition Adds together two values x + y - Subtraction Subtracts one value from another x - y * Multiplication Multiplies two values x * y / Division Divides one value by another x / y % Modulus Returns the division remainder x % y ++ Increment Increases the value of a variable by 1 ++x -- Decrement Decreases the value of a variable by 1 --x
  • 7. Assignment Operators Assignment operators are used to assign values to variables. Operator example Same as = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 Comparison Operators Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The return value of a comparison is either 1 or 0, which means true (1) or false (0). These values are known as Boolean values. Operator Name Example Description == Equal Equal to x == y Returns 1 if the values are equal != Not equal x != y Returns 1 if the values are not equal > Greater than x > y Returns 1 if the first value is greater than the second value Written By : Akshay Bhagade
  • 8. < Less than x < y Returns 1 if the first value is less than the second value >= Greater than or equal to x >= y Returns 1 if the first value is greater than, or equal to, the second value <= Less than or equal to x <= y Returns 1 if the first value is less than, or equal to, the second value Logical Operators You can also test for true or false values with logical operators. Operator Name Example Description && Logical and x < 5 && x < 10 Returns 1 if both statements are true || Logical or x < 5 || x < 4 Returns 1 if one of the statements is true ! Logical not !(x < 5 && x < 10) Reverse the result, returns 0 if the result is 1 Booleans Very often, in programming, you will need a data type that can only have one of two values, like: ● YES / NO ● ON / OFF ● TRUE / FALSE A boolean variable is declared with the bool keyword and can only take the values true or false: ● 1 (or any other number that is not 0) represents true ● 0 represents false Written By : Akshay Bhagade
  • 9. Chapter 3- Conditional Statements The conditional statements are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making statements in programming languages decide the direction of the flow of program execution. ● Conditional Operator (? :) ● If Statement ● If-else statement ● Ladder else-if statement ● Nested if-else statement ● Switch statement Conditional Operator/Ternary Operator (? :) Syntax: (condition) ? Execute when condition true : Execute when condition false; Example: 1) print the greater number between two numbers #include <stdio.h> int main() { int a,b; printf("enter a: "); scanf("%d",&a); printf("enter b: "); scanf("%d",&b); a>b ? printf("a is greater"): printf("b is greater"); return 0; } Written By : Akshay Bhagade
  • 10. Output : enter a: 13 enter b: 23 b is greater 2) Check the number is positive or negative #include <stdio.h> int main() { int number; printf("enter number: "); scanf("%d",&number); number > 0 ? printf("Number is Positive"): printf("Number is Negative"); return 0; } Output : enter number: 23 Number is Positive If Statement if a certain condition is true then a block of statements is executed otherwise not. Syntax : if(condition) { // Statements to execute if // condition is true } Written By : Akshay Bhagade
  • 11. Example: 1) #include <stdio.h> int main() { if (20 > 18) { printf("20 is greater than 18"); } return 0; } Output : 20 is greater than 18 2) #include <stdio.h> int main() { int x = 20; int y = 18; if (x > y) { printf("x is greater than y"); } } Output : x is greater than y If-Else Statement if a certain condition is true then a if block of statements is executed if condition false then else block will be executed. Syntax : if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false } Written By : Akshay Bhagade
  • 12. Example: 1) print the greater number between two numbers #include <stdio.h> int main() { int a,b; printf("enter a: "); scanf("%d",&a); printf("enter b: "); scanf("%d",&b); if(a > b){ printf("a is greater"); }else{ printf("b is greater"); } return 0; } Output : enter a: 23 enter b: 34 b is greater 2) Enter the percentage and check whether the student is pass or fail? #include <stdio.h> int main() { int percentage ; printf("enter total percentage: "); scanf("%d",&percentage); if(percentage >= 35){ printf("Student is Pass"); }else{ printf("Student is Fail"); } return 0; } Written By : Akshay Bhagade
  • 13. Output : enter total percentage: 35 Student is Pass More Questions :- 3) Enter the number and check whether the number is positive or negative. 4) Enter the number and check whether the number is even or odd. 5) Enter the year and check whether it is Leap year or Not. 6) Enter the purchase and sold amount and declare whether the profit or loss happened. 7) Enter the age to check if the person is eligible for voting or not. Ladder If-Else-if Statement The if else if statements are used when the user has to decide among multiple options. if a certain condition is true then the particular block of statements is executed If none of the conditions is true, then the final else statement will be executed. Syntax : if (condition1) { // Code to execute if condition1 is true } else if (condition2) { // Code to execute if condition1 is false and condition2 is true } else if (condition3) { // Code to execute if condition1 and condition2 are false, and condition3 is true } else { // Code to execute if all above conditions are false } Written By : Akshay Bhagade
  • 14. Example: 1) Take input from the user and print the number is positive or negative or zero. #include <stdio.h> int main() { int number; printf("enter number: "); scanf("%d",&number); if(number > 0){ printf("you enter positive number..."); } else if(number < 0){ printf("you enter negative number..."); } else{ printf("you enter the zero..."); } return 0; } Output : enter number: 0 you enter the zero… enter number: -8 you enter negative number... enter number: 12 you enter positive number... Written By : Akshay Bhagade
  • 15. 2) Write a program to find the maximum between three number #include <stdio.h> int main() { int a, b, c; // Get input from the user printf("Enter three numbers: n"); scanf("%d",&a); scanf("%d",&b); scanf("%d",&c); if(a > b && a > c ){ printf("%d is Greater...",a); } else if(b > a && b > c ){ printf("%d is Greater...",b); } else{ printf("%d is Greater...",c); } return 0; } Output : Enter three numbers: 45 23 56 56 is Greater... More Questions :- 3) Build the Calculator. 4) Write a c program to input marks of five subjects eng,hindi,mar,maths, phy, calculate percentage and print grade according to the following. - Grade Merit — > percentage in between 90-100. - Grade Distinction — > percentage in between 75-90. - Grade First Class— > percentage in between 60-75. - Grade Second Class— > percentage in between 45-60. - Grade Pass— > percentage in between 35-45. - Fail — > percentage less than 35. Written By : Akshay Bhagade
  • 16. Nested If-Else Statement A nested if-else statement is an if statement inside another if statement. The general syntax of nested if-else statement in C is as follows: Syntax : if (condition1) { /* code to be executed if condition1 is true */ if (condition2) { /* code to be executed if condition is true */ } else { /* code to be executed if condition is false */ } } else { /* code to be executed if condition1 is false */ } Example: 1) Check the given number is positive or negative or zero. If the number is positive then the check number is even or odd.. #include <stdio.h> int main() { int num = 7; if (num > 0) { printf("The number is positive.n"); if (num % 2 == 0) { printf("The number is even.n"); } else { printf("The number is odd.n"); } } else { if (num < 0) { printf("The number is negative.n"); } else { printf("The number is zero.n"); } } return 0; } Written By : Akshay Bhagade
  • 17. Output : The number is positive. The number is odd. Switch Statement Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Rules of the switch case statement Following are some of the rules that we need to follow while using the switch statement: 1. In a switch statement, the “case value” must be of “char” and “int” type. 2. There can be one or N number of cases. 3. The values in the case must be unique. 4. Each statement of the case can have a break statement. It is optional.If there is no break statement found in the case, all the cases will be executed present after the matched case. 5. The default Statement is also optional. Syntax : switch(expression){ case value1: //code to be executed; break; case value2: //code to be executed; break; ...... default: code to be executed if all cases are not matched; } Written By : Akshay Bhagade
  • 18. Example: 1) print the value of the given number using the switch statement. #include <stdio.h> int main() { int num = 2; switch (num) { case 1: printf("Value is 1n"); break; case 2: printf("Value is 2n"); break; case 3: printf("Value is 3n"); break; default: printf("Value is not 1, 2, or 3n"); break; } return 0; } Output : Value is 2 2) Write a c program to input the day number and print week day. #include <stdio.h> int main() { int day = 2; switch (day) { case 1: printf("Monday"); break; Written By : Akshay Bhagade
  • 19. case 2: printf("Tuesday"); break; case 3: printf("Wednesday"); break; case 4: printf("Thursday"); break; case 5: printf("Friday"); break; case 6: printf("Saturday"); break; case 7: printf("Sunday"); break; default: printf("Invalid Input"); break; } return 0; } Output : Tuesday 3) enter an alphabet and check whether it is vowel or consonant. 4) write a c program to input a month number and print no of days in that month. Written By : Akshay Bhagade
  • 20. Chapter 4-Loops in C Loops in programming are used to repeat a block of code until the specified condition is reached. A loop statement allows programmers to execute a statement or group of statements multiple times without repetition of code. ● For Loop ● While Loop ● Do While Loop ● Nested For Loop for Loop for loop in C programming is a repetition control structure that allows programmers to write a loop that will be executed a specific number of times. Syntax : #include <stdio.h> int main() { for (initialization; condition; increment/decrement){ // statements inside the body of loop } return 0; } Example : 1) print the 1 to 10 number. #include <stdio.h> int main() { int i; for (i = 1; i <= 10; i++) { printf("%d ", i); } return 0; } Written By : Akshay Bhagade
  • 21. Output : 1 2 3 4 5 6 7 8 9 10 More Questions :- 1) print the sum of n natural number 2) print the factorial. 3) write a c program to print all even numbers between 1 to 100. 4) write a program to print a multiplication table of any number. 5) print Fibonacci Series. While Loop Syntax : #include <stdio.h> int main() { // Initialization while (condition) { statement increment/decrement } return 0; } Example : 1) print the 1 to 10 number. #include <stdio.h> int main() { int i = 1; while (i <= 10) { printf("%d", i); i++; } return 0; } Output : 1 2 3 4 5 6 7 8 9 10 Written By : Akshay Bhagade
  • 22. More Questions :- 1) print Fibonacci Series. 2) All the above question of for loops Mid/Hard Level Questions :- 1) Take 10 numbers from the user and count how many there are positive, negative and zero numbers. 2) print the sum of digits.If number is 56 then answer is 11 (5+6=11) 3) write a c program to check if a given number is prime or not. 4) print the reverse number for e.g. number is 156 then output is 651 5) Check the entered number is palindrome or not. Do-while Loop do/while will always be executed at least once, even if the condition is false, because the code block is executed before the condition is checked. Syntax : #include <stdio.h> int main() { // Initialization do { statement increment/decrement } while (condition); return 0; } Example : #include <stdio.h> int main() { int i = 1; do { printf("%d n", i); i++; }while (i <= 10); return 0; } Written By : Akshay Bhagade
  • 23. Output : 1 2 3 4 5 6 7 8 9 10 Nested for Loop loop inside another loop. This is called a nested loop. The "inner loop" will be executed one time for each iteration of the "outer loop" Example : #include <stdio.h> int main() { int i, j; // Outer loop for (i = 1; i <= 2; i++) { printf("Outer: %dn", i); // Inner loop for (j = 1; j <= 3; j++) { printf(" Inner: %dn", j); } } return 0; } Output : Outer: 1 Inner: 1 Inner: 2 Inner: 3 Outer: 2 Inner: 1 Inner: 2 Inner: 3 Written By : Akshay Bhagade
  • 24. Star Pattern Questions :- 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Number left half pyramid * * * * * * * * * * * * * * * left half pyramid * * * * * * * * * * * * * * * Inverted left half pyramid * * * * * * * * * * * * * * * right half pyramid * * * * * * * * * * * * * * * inverted right half pyramid 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 floyd's triangle ***** * * * * * * ***** hollow rectangle; 1 0 1 1 0 1 0 1 0 1 1 0 1 0 1 triangle 1_0 ****** ****** ****** ****** ****** solid rhombus 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 Num pyramid Advance Pattern : * *** ***** ******* ********* ********* ******* ***** *** * diamond pattern * * ** ** *** *** **** **** ********** ********** **** **** *** *** ** ** * * butterfly Pattern Jump Statements :- - Break - Continue Written By : Akshay Bhagade
  • 25. Break :- The break statement can also be used to exit from a loop. Example : #include <stdio.h> int main() { int i; for (i = 0; i < 10; i++) { if (i == 4) { break; } printf("%d", i); } return 0; } Output : 0123 Continue:- The continue statement skips one iteration (in the loop) if a specified condition occurs, and continues with the next iteration in the loop. Example : #include <stdio.h> int main() { int i; for (i = 0; i < 10; i++) { if (i == 4) { continue; } printf("%d ", i); } return 0; } Output : 0 1 2 3 5 6 7 8 9 Written By : Akshay Bhagade
  • 26. Chapter 5 - Arrays Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. similar data items stored in contiguous memory locations. It can be used to store the collection of primitive data types such as int, char, float, etc., and also derived and user-defined data types such as pointers, structures, etc. Syntax: data_type array_name [size]; data_type array_name [size] = {value1, value2, ... valueN}; It is possible to initialize an array during declaration. For example, int mark[5] = {46, 87, 81, 74, 90}; You can also initialize an array like this. int mark[] = {46, 87, 81, 74, 90}; Example : #include <stdio.h> int main() { int myNumbers[] = {46, 87, 81, 74, 90}; printf("%d", myNumbers[0]); return 0; } Output : 46 Written By : Akshay Bhagade
  • 27. Change an Array Element To change the value of a specific element, refer to the index number: #include <stdio.h> int main() { int myNumbers[] = {46, 87, 81, 74, 90}; myNumbers[0] = 66; printf("%d", myNumbers[0]); return 0; } Output : 66 Array with For loop Also we caṇ print array elements with the for loop. #include <stdio.h> int main() { int myNumbers[] = {46, 87, 81, 74, 90}; int i; for(i = 0; i < 4; i++) { printf("%dn", myNumbers[i]); } return 0; } Output : 46 87 81 74 90 Written By : Akshay Bhagade
  • 28. Another common way to create arrays, is to specify the size of the array, and add elements later: #include <stdio.h> int main() { // Declare an array of four integers: int myNumbers[4]; // Add elements to it myNumbers[0] = 46; myNumbers[1] = 87; myNumbers[2] = 81; myNumbers[3] = 74; myNumbers[4] = 90; printf("%dn", myNumbers[2]); return 0; } Output : 81 Get Array Size or Length #include <stdio.h> int main() { int myNumbers[] = {46, 87, 81, 74, 90}; printf("%d", sizeof(myNumbers)); return 0; } Output: 20 - It is because the sizeof operator returns the size of a type in bytes. - for calculating size of array divides the size of the array by the size of one array element. Written By : Akshay Bhagade
  • 29. calculating size of array: #include <stdio.h> int main() { int myNumbers[] = {46, 87, 81, 74, 90}; int length = sizeof(myNumbers) / sizeof(myNumbers[0]); printf("%d", length); return 0; } Output : 5 Using for loop when we don't know the size of an array: #include <stdio.h> int main() { int myNumbers[] = {46, 87, 81, 74, 90}; int length = sizeof(myNumbers) / sizeof(myNumbers[0]); int i; for (i = 0; i < length; i++) { printf("%dt", myNumbers[i]); } return 0; } Output : 46 87 81 74 90 Written By : Akshay Bhagade
  • 30. Input Array From User: Q. Program to take 5 values from the user and store them in an array #include <stdio.h> int main() { int values[5]; printf("Enter 5 integers: "); // taking input and storing it in an array for(int i = 0; i < 5; i++) { scanf("%d", &values[i]); } printf("Displaying integers: "); // printing elements of an array for(int i = 0; i < 5; i++) { printf("n%d", values[i]); } return 0; } Output : Enter 5 integers: 45 87 67 98 45 Displaying integers: 45 87 67 98 45 Written By : Akshay Bhagade
  • 31. Questions: 1) Enter an array and take any input number from the user and check whether the number exists in the array or not. 2) Enter an array and find the minimum number in that array. 3) Enter an array and find the maximum number in that array. 4) Program to find the sum and average of n numbers using arrays. 5) Sorting an array. 2D Arrays: A multidimensional array is basically an array of arrays. If you want to store data as a tabular form, like a table with rows and columns, Then we use multidimensional arrays. E.g. int matrix[3][3] = {}; E.g. int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} }; Written By : Akshay Bhagade
  • 32. Example: #include <stdio.h> int main() { int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} }; printf("%d", matrix[0][2]); return 0; } Output : 2 How To Change 2D Array Element: #include <stdio.h> int main() { int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} }; matrix[0][0] = 9; printf("%d", matrix[0][0]); // Now outputs 9 instead of 1 return 0; } Output : 9 Written By : Akshay Bhagade
  • 33. Print 2D Array Element By Using Loop: #include <stdio.h> int main() { int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} }; int i, j; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++) { printf("Element at x[%i][%i]: ", i, j); printf("%dn", matrix[i][j]); } } return 0; } Output : Element at x[0][0]: 1 Element at x[0][1]: 4 Element at x[0][2]: 2 Element at x[1][0]: 3 Element at x[1][1]: 6 Element at x[1][2]: 8 Taking Array Elements from User and print the array #include <stdio.h> int main() { int arr[3][3],i,j; // taking user input for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf("Enter the Elements [%d][%d]: ",i,j); Written By : Akshay Bhagade
  • 34. scanf("%d",&arr[i][j]); } } printf("nPrinting The Element......n"); for(i=0;i<3;i++){ for(j=0;j<3;j++){ printf("%dt",arr[i][j]); } printf("n"); } return 0; } Output : Enter the Elements [0][0]: 34 Enter the Elements [0][1]: 67 Enter the Elements [0][2]: 34 Enter the Elements [1][0]: 09 Enter the Elements [1][1]: 86 Enter the Elements [1][2]: 12 Enter the Elements [2][0]: 45 Enter the Elements [2][1]: 67 Enter the Elements [2][2]: 34 Printing The Element...... 34 67 34 9 86 12 45 67 34 Questions: 1) Enter an 2D array and take any input number from the user and check whether the number exists in the array or not. 2) Addition Of Two Matrices 3) Multiplication of Two Matrix 4) Sum of Diagonal Elements in Square Matrix. Written By : Akshay Bhagade
  • 35. Chapter 6 - Strings A String in C programming is a sequence of characters terminated with a null character ‘0’. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character ‘0’. Note: %s is the format specifier to print a string in C. Syntax: char variableName[size]; For example: char name[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character 0 at the end by default. There are two methods to do this: 1) Using Char Array - without declaring the size of the array char str[] = {'C', 'o', 'm', 'p', 'u', 'f', 'i', 'e', 'l', 'd', '0'}; by declaring the size of the array char str[11] = {'C', 'o', 'm', 'p', 'u', 'f', 'i', 'e', 'l', 'd', '0'}; 2) Using String Literal - without declaring the size of the array char str[]="Compufield"; by declaring the size of the array char str[11]="Compufield"; Written By : Akshay Bhagade
  • 36. Example : #include <stdio.h> int main() { char str[11] = {'C', 'o', 'm', 'p', 'u', 'f', 'i', 'e', 'l', 'd', '0'}; char str1[11] = "Compufield"; printf("String by char array method: %sn", str); printf("String by String Literal method: %sn", str1); return 0; } Output : String by char array method: Compufield String by String Literal method: Compufield Accessing The String: As the string is array of characters, we can access the characters of the string with their index number. The string index starts with 0. %c is a format specifier to print a single character. Example : #include <stdio.h> int main() { char str[10]="Compufield"; printf("%c", str[5]); return 0; } Output : f Written By : Akshay Bhagade
  • 37. Modify The String: To change the value of a specific character in a string, refer to the index number, and use single quotes: Example : #include <stdio.h> int main() { char str[]="HelloWorld"; str[4] = 'i'; printf("%s", str); return 0; } Output : HelliWorld Loops Through String: We can also loop through the characters of a string, using a for loop: Example : #include <stdio.h> int main() { char str[10]="Compufield"; int length = sizeof(str) / sizeof(str[0]); for (int i = 0; i < length; i++) { printf("%cn", str[i]); } return 0; } Output : Written By : Akshay Bhagade
  • 38. Take Input String from User: 1) Using scanf() Example : #include <stdio.h> int main() { char name[20]; printf("Enter name: "); scanf("%s", name); printf("Your name is %s", name); return 0; } Output : Enter name: Gaurav Therade Name: Gaurav. Note: The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.). #include <stdio.h> int main() { char name[30]; printf("Enter name: "); fgets(name, sizeof(name), stdin); // read string printf("Name: "); puts(name); // display string return 0; } Output : Enter name: Gaurav Therade Name: Gaurav Therade Written By : Akshay Bhagade
  • 39. String Functions in C: There are many important string functions defined in "string.h" library. No. Function Description 1) strlen(string_name) returns the length of the string name. 2) strcpy(destination, source) copies the contents of source string to destination string. 3) strcat(first_string, second_string) concats or joins first string with second string. The result of the string is stored in first string. 4) strcmp(first_string, second_string) compares the first string with second string. If both strings are same, it returns 0. 5) strrev(string) returns reverse string. 6) strlwr(string) returns string characters in lowercase. 7) strupr(string) returns string characters in uppercase. Example : 1) find the length of string #include <stdio.h> #include <string.h> int main() { char str1[] = "Compufield"; char str2[20]; printf("Length of str1: %dn", strlen(str1)); return 0; } Output : Length of str1: 10 Written By : Akshay Bhagade
  • 40. Example : 2) copy string from another string #include <stdio.h> #include <string.h> int main() { char str1[20] = "C programming"; char str2[20]; // copying str1 to str2 strcpy(str2, str1); puts(str2); // C programming return 0; } Output : C programming Example : 3) concatenate string #include<stdio.h> #include <string.h> int main(){ char ch1[10]="Hellot"; char ch2[10]="World"; strcat(ch1,ch2); printf("%s",ch1); return 0; } Output : Hello World Example : 4) Compared Strings #include <stdio.h> #include <string.h> int main() { Written By : Akshay Bhagade
  • 41. char str1[20], str2[20]; printf("Enter 1st string: "); fgets(str1, sizeof(str1), stdin); printf("Enter 2nd string: "); fgets(str2, sizeof(str2), stdin); if (strcmp(str1, str2) == 0) { printf("Strings are equaln"); } else { printf("Strings are not equaln"); } return 0; } Output : Enter 1st string: hello Enter 2nd string: hello Strings are equal Example : 5) Reverse the Strings #include<stdio.h> #include <string.h> int main(){ char str[20]; printf("Enter string: "); gets(str); printf("String is: %s",str); printf("nReverse String is: %s",strrev(str)); return 0; } Output : String is: dog Reverse String is: god Written By : Akshay Bhagade
  • 42. Example : 6) Convert Strings into Lowercase & Uppercase #include<stdio.h> #include <string.h> int main(){ char str[20]= "CompuField"; printf("String is: %s",str); printf("nLower String is: %s",strlwr(str)); printf("nUpper String is: %s",strupr(str)); return 0; } Output : String is: CompuField Lower String is: compufield Upper String is: COMPUFIELD Questions : 1) reverse the string without using the rev function. 2) Check if the string is palindrome or not. 3) Write a program in C to count the total number of words in a string. 4) Write a program in C to count the total number of alphabets, digits and special characters in a string. 5) Write a program in C to count the total number of vowels or consonants in a string. 6) Write a C program to sort a string array in ascending order. 7) Write a program in C to find the frequency of characters. Written By : Akshay Bhagade
  • 43. Chapter 7 - Functions A function is a block of code that performs a specific task when a function is called. They provide a way to break down a program into smaller, manageable units, which makes the code more readable, reusable, and maintainable. They are of two types: Built-in and User Defined. types of Functions: Built in Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), sqrt(), pow () etc. User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times. It reduces the complexity of a big program and optimises the code. They are of two types of user-defined function; 1. Function with a return value 2. Function without a return value (void functions) Written By : Akshay Bhagade
  • 44. Function without Return value: 1) Print name using function #include<stdio.h> // Function Declaration void printName(); int main () { printf("Hello "); printName(); // Function Call return 0; } // Function Definition void printName() { printf("Ruhi"); } Output : Hello Ruhi 2) Print name using function with parameter/Arguments. #include <stdio.h> // Function Declaration void greet(char name[]); int main() { greet("Ekayaa"); // Function Call return 0; } // Function Definition void greet(char name[]) { printf("Hello, %s!", name); } Output : Hello, Ekayaa! Written By : Akshay Bhagade
  • 45. 3) Sum of two number #include<stdio.h> void sum(); // Function Declaration int main() // main method { printf("ncalculate the sum of two numbers:"); sum(); // Function call in main method return 0; } void sum() // Function Definition { int a,b; printf("nEnter two numbers: "); scanf("%d %d",&a,&b); printf("The sum is: %d",a+b); } Output : Enter two numbers: 23 67 The sum is: 90 Function with return value: 1) Sum of two number #include <stdio.h> // Function Declaration int add(int a, int b); int main() { int result = add(8, 9); //Function call printf("The sum of a + b = %dn", result); return 0; } // Function Definition int add(int a, int b) { return a + b; } Output : The sum of a + b = 17 Written By : Akshay Bhagade
  • 46. Multiple Parameters Inside the function,we can add as many parameters #include <stdio.h> void myFunction(char name[], int age) { printf("Hello %s. You are %d years oldn", name, age); } int main() { myFunction("Akaay", 3); myFunction("Driti", 14); myFunction("Gaurav", 30); return 0; } Output : Hello Akaay. You are 3 years old Hello Driti. You are 14 years old Hello Gaurav. You are 30 years old You can also pass arrays to a function: #include <stdio.h> void myFunction(int myNumbers[5]) { for (int i = 0; i < 5; i++) { printf("%dn", myNumbers[i]); } } int main() { int myNumbers[5] = {10, 20, 30, 40, 50}; myFunction(myNumbers); return 0; } Written By : Akshay Bhagade
  • 47. Questions : 1) Write a program in C to swap two numbers using a function. 2) Write a program in C to check if a given number is even or odd using the function. 3) Write a program in C to find the sum of the series 4) program to calculate the average of five numbers. 5) Convert Celsius to Fahrenheit 6) print the factorial using a function. Maths Function: There is also a list of maths functions available, that allows you to perform mathematical tasks on numbers.To use them, you must include the math.h header file in your program: 1) To find the square root of a number, use the sqrt() function: #include <stdio.h> #include <math.h> int main() { printf("%f", sqrt(16)); return 0; } Output : 4.000000 2) The pow() function returns the value of x to the power of y (xy): #include <stdio.h> #include <math.h> int main() { printf("%f", pow(4, 3)); return 0; } Output : 64.000000 Written By : Akshay Bhagade
  • 48. Recursion : Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve. Question: 1) print the number of 1 to 5 and also reverse order using recursion. #include <stdio.h> void printnum(int n) { if (n == 6) { return; } printf("%dt", n); printnum(n + 1); } int main() { int n = 1; printnum(n); return 0; } Output : 1 2 3 4 5 2) calculate sum of n natural numbers using recursion. #include <stdio.h> // Function prototype void printsum(int i, int n, int sum); int main() { int num; printf("Enter the number: "); scanf("%d", &num); printsum(1, num, 0); return 0; } Written By : Akshay Bhagade
  • 49. void printsum(int i, int n, int sum) { if (i == n) { sum += i; printf("sum is: %dn", sum); return; } sum += i; printsum(i + 1, n, sum); } Output : Enter the number: 5 sum is: 15 3) find the factorial by using recursion. #include <stdio.h> // Recursive function int printfact(int n) { if (n == 1 || n == 0) { return 1; } int fact_1 = printfact(n - 1); int fact_2 = n * printfact(n - 1); return fact_2; } int main() { int num; printf("Enter the number: "); scanf("%d", &num); int result = printfact(num); printf("Factorial of %d is %dn", num, result); return 0; } Output : Enter the number: 5 Factorial of 5 is 120 Written By : Akshay Bhagade
  • 50. Chapter 8 - C Structures A structure is a container to store multiple types of variables. The variables stored in a structure are called member variables. Member variables are related to each other, and they are combined to provide complete information about an object. The ,struct keyword is used to define the structure. Let's see the syntax to define the structure in c. struct structure_name { data_type member1; data_type member2; . . data_type memeberN; }; E.G. struct employee { int id; char name[20]; float salary; }; Key Points of C Structure ● The structure is declared using the “struct” keyword. ● Structure allocates contiguous memory to all its member variables. ● You can only declare member variables in a structure. ● You cannot initialise the member variables during their declaration. ● To access the member variables, use the dot operator. ● Structure member variables are initialised in the same order as their declaration. Written By : Akshay Bhagade
  • 51. Example : #include <stdio.h> struct book{ char title[50]; char author[30]; double price; int pages; }; int main(){ struct book book1 = {"An Era of Darkness", "Shashi Tharoor", 599.00, 360}; printf("Title: %s n", book1.title); printf("Author: %s n", book1.author); printf("Price: %.2fn", book1.price); printf("Pages: %d n", book1.pages); return 0; } Output : Title: An Era of Darkness Author: Shashi Tharoor Price: 599.00 Pages: 360 Keyword typedef : We use the typedef keyword to create an alias name for data types. It is commonly used with structures to simplify the syntax of declaring variables. Example : #include <stdio.h> #include <string.h> // struct with typedef person typedef struct Person { char name[50]; int citNo; float salary; } employee; Written By : Akshay Bhagade
  • 52. int main() { // create struct Person variable with aliased name employee employee p1; // assign value to name of p1 strcpy(p1.name, "Gaurav Therade"); // assign values to other p1 variables p1.citNo = 411001; p1. salary = 25000; // print struct variables printf("Name: %sn", p1.name); printf("Citizenship No.: %dn", p1.citNo); printf("Salary: %.2f", p1.salary); return 0; } Output : Name: Gaurav Therade Citizenship No.: 411001 Salary: 25000.00 Example : Taking input from user how many person and take details of all person and print the details by using loops #include <stdio.h> #include <string.h> typedef struct Person { char name[50]; int citNo; float salary; } employee; int main() { int numPersons; Written By : Akshay Bhagade
  • 53. // Input the number of persons printf("Enter the number of persons: "); scanf("%d", &numPersons); // Array of employees based on the number of persons employee emp[numPersons]; // Input details for each person for (int i = 1; i <= numPersons; i++) { printf("Enter details for person %d:n", i); // Input name printf("Name: "); scanf(" %[^n]s", emp[i].name); // Input city number printf("City No.: "); scanf("%d", &emp[i].citNo); // Input salary printf("Salary: "); scanf("%f", &emp[i].salary); } // Print details for each person printf("nDetails of all the Employees :n"); for (int i = 1; i <= numPersons; i++) { printf("Person %d:n", i); printf("Name: %sn", emp[i].name); printf("Citizenship No.: %dn", emp[i].citNo); printf("Salary: %.2fn", emp[i].salary); } return 0; } Written By : Akshay Bhagade
  • 54. Union in C structures and unions both serve the purpose of grouping data members into a single unit, they have different use cases due to their fundamental differences in memory allocation structures and unions are similar in that they both allow you to define custom data types. Structures are typically used when you want to store and manipulate different types of data together as a single entity. Each member of a structure has its own memory space, and you can access them independently. Unions are used when you need to store different types of data in the same memory location. Unlike structures, where each member has its own memory space, in a union, all members share the same memory space. This means that modifying one member of a union can affect the values of other members. When we Use Structure: Use structures when you have a collection of related data elements that you want to access independently and manipulate separately. When we Use Union: Use unions when you need to save memory and when you know that only one member of the union will be accessed at any given time. Unions are commonly used in situations like implementing variant types or when dealing with hardware interfaces where memory conservation is crucial. Written By : Akshay Bhagade
  • 55. Example: #include <stdio.h> union student { int id; float marks; char grade; }; int main() { union student s; s.id = 101; printf("Student ID: %dn", s.id); s.marks = 85.5; printf("Student Marks: %fn", s.marks); s.grade = 'A'; printf("Student Grade: %cn", s.grade); return 0; } Output : Student ID: 101 Student Marks: 85.500000 Student Grade: A Difference between Struct & Union: Written By : Akshay Bhagade Features Struct Union Memory Allocation Each member has their own memory location All members share the same memory location Size Sum of sizes of all members Size of the largest member Usage Store related data Save memory by sharing memory location Initialization Members can be initialized individually Only the first member can be initialized Accessing Members Dot (.) operator Dot (.) or arrow (->) operator
  • 56. Chapter 9 - Pointer A Variable that stores the memory address of another variable. Syntax: int num = 3; int *ptr = &num; int num_1 = *ptr; Note: * is value of address operator & is address of operator num num_1 ptr 34 34 4673 4673 4674 4677 ** different ways to declare pointers, pointers also be an int, float and char. Format Specifier for pointers: “%p” or “%u” - unsigned int Example: 1) Print the address of the operator. #include<stdio.h> int main(){ int num = 34; int *ptr = &num; printf("%pn",&num); printf("%pn",ptr); printf("%pn",&ptr); return 0; } Written By : Akshay Bhagade
  • 57. 2) Print the Value of Operator. #include<stdio.h> int main(){ int num = 34; int *ptr = &num; printf("printing the values in diffrent waysn"); printf("%dn",num); printf("%dn",*ptr); printf("%dn",*(&num)); return 0; } 3) Guess the Output of the following code. #include<stdio.h> int main(){ int a; int *ptr; ptr = &a; *ptr = 0; printf("a is: %dn",a); printf("*ptr is: %dn",*ptr); *ptr += 5; printf("a is: %dn",a); printf("*ptr is: %dn",*ptr); (*ptr)++; printf("a is: %dn",a); printf("*ptr is: %dn",*ptr); return 0; } Written By : Akshay Bhagade
  • 58. Pointer to pointer: A variable that stores the memory address of another pointer. num pptr ptr 34 4677 4673 4673 4676 4677 Syntax: float marks = 90.00; float *ptr = &marks; float **pptr = &ptr; Example: #include<stdio.h> int main(){ float marks = 90.00; float *ptr = &marks; float **pptr = &ptr; printf("%.2fn",**pptr); return 0; } Pointers in Function Call: 1) Call by Value : We pass the value of the variable as an argument. #include<stdio.h> void square(int n); int main(){ int number = 4; square(number); printf("number = %dn",number); return 0; } void square(int n){ n = n * n; printf("square = %dn",n); } Written By : Akshay Bhagade
  • 59. 2) Call By Reference : We Pass Address of the variable as an argument. #include<stdio.h> void square_1(int *n); int main(){ int number = 4; square_1(&number); printf("number = %dn",number); return 0; } void square_1(int* n){ *n = (*n) * (*n); printf("square = %dn",*n); } Questions : 1) Write a C program to swap two numbers using a pointer. 2) Write a C program to calculate and return sum, product and average by using a function. Written By : Akshay Bhagade
  • 60. Chapter 10 - File I/O What are files in C? A file is used to store huge data. C provides multiple file management functions like file creation, opening and reading files, Writing to the file, and closing a file. The file is used to store relevant data and file handling in C is used to manipulate the data. Operation of Files : 1) Open a File 2) Close File 3) Create a File 4) Read From a File 5) Write in a File Types of Files : 1) Text Files (textual data) - .txt, .c 2) binary Files (binary data) - .exe,.mp3,.jpg File Pointer : For Performing operations on the file in c a special pointer is used called File pointer that can be declared as: FILE *fptr; Opening & Closing a File : #include <stdio.h> int main(){ FILE *fptr; fptr = fopen("filename", "mode"); // some work on file fclose(fptr); //closing file return 0; } Written By : Akshay Bhagade
  • 61. File Opening Modes : 1) "r" - Open to read 2) "rb" - Open to read in binary 3) "w" - Open to write 4) "wb" - Open to write in binary 5) "a" - Open to append Reading from a file : char c; fscanf(fptr,"%c",&c); Example: #include <stdio.h> int main(){ FILE *fptr; fptr = fopen("test.txt", "r"); char ch; fscanf(fptr,"%c",&ch); printf("%c",ch); fscanf(fptr,"%c",&ch); printf("%c",ch); fscanf(fptr,"%c",&ch); printf("%c",ch); fscanf(fptr,"%c",&ch); printf("%c",ch); fscanf(fptr,"%c",&ch); printf("%c",ch); fclose(fptr); return 0; } Writing to a file : char ch = 'H'; fprintf(fptr,"%c",ch); Written By : Akshay Bhagade
  • 62. Example: #include <stdio.h> int main(){ FILE *fptr; fptr = fopen("test.txt", "w"); fprintf(fptr,"%c", 'H'); fprintf(fptr,"%c", 'e'); fprintf(fptr,"%c", 'y'); fprintf(fptr,"%c", '!'); fclose(fptr); return 0; } Writing to a file : fgetc(fptr); fputc('A',fptr); Example: 1) Read from the file #include <stdio.h> int main(){ FILE *fptr; fptr = fopen("test.txt", "r"); printf("%cn",fgetc(fptr)); printf("%cn",fgetc(fptr)); printf("%cn",fgetc(fptr)); printf("%cn",fgetc(fptr)); fclose(fptr); return 0; } Written By : Akshay Bhagade
  • 63. 2) write into a file #include <stdio.h> int main(){ FILE *fptr; fptr = fopen("test.txt", "w"); fputc('A',fptr); fputc('K',fptr); fputc('A',fptr); fputc('A',fptr); fputc('Y',fptr); fclose(fptr); return 0; } EOF (End Of File) : fgetc returns EOF to show that the file has ended #include <stdio.h> int main(){ FILE *fptr; fptr = fopen("test.txt", "r"); char ch; ch = fgetc(fptr); while(ch != EOF){ printf("%c",ch); ch = fgetc(fptr); } fclose(fptr); return 0; } Questions : 1) Make a program to input student information from user & enter into file 2) wap to write all the odd numbers from 1 to 100 in a file 3) Write a multiplication table of the user entered number in the file. 4) take student number and subjects of each student & calculate their sum and average store them into the file. Written By : Akshay Bhagade
  • 64. Chapter 11 - Dynamic Memory Allocation in c Dynamic memory allocation is a way to allocate memory to a data structure during the runtime. Following function are available in C to perform Dynamic memory Allocation: 1) malloc() 2) Calloc() 3) free() 4) realloc() malloc() function: Malloc stands for memory allocation. It takes a number of bytes to be allocated as an input and returns a pointer of type void. Syntax: #include<stdio.h> #include<stdlib.h> int main(){ int *ptr; ptr = (int *)malloc(5* sizeof(int)); ptr[0] = 1; ptr[1] = 2; ptr[2] = 3; ptr[3] = 4; ptr[4] = 5; for(int i =0;i<5;i++){ printf("n %d",ptr[i]); } return 0; } Written By : Akshay Bhagade
  • 65. calloc() function: Calloc stands for continuous allocation. It initialises each memory block with a default value of 0. Syntax: #include<stdio.h> #include<stdlib.h> int main(){ int *ptr; ptr = (int *)calloc(5, sizeof(int)); for(int i =0;i<5;i++){ printf("n %d",ptr[i]); } return 0; } Note: If the space is not sufficient in the device, memory allocation fails and a NULL pointer is returned. free() function: We use the free() function to deallocate the memory or use it to free memory that is allocated by using malloc & calloc. Syntax: #include<stdio.h> #include<stdlib.h> int main(){ int *ptr; int n; printf("enter the n: "); scanf("%d",&n); ptr = (int *)calloc(n, sizeof(int)); free(ptr); Written By : Akshay Bhagade
  • 66. ptr = (int *)calloc(2, sizeof(int)); for(int i =0;i<2;i++){ printf("n %d",ptr[i]); } return 0; } realloc() function: Realloc is used to increase or decrease memory size using the same pointer & size. E.g. ptr = realloc(ptr, newSize); Syntax: int *ptr; ptr = (int *)calloc(5, sizeof(int)); ptr = realloc(ptr, 8); Example: allocate memory for 5 numbers then increase it to 8 numbers. #include<stdio.h> #include<stdlib.h> int main(){ int *ptr; ptr = (int *)calloc(5, sizeof(int)); printf("Enter number 5: "); for(int i = 1; i <= 5; i++){ scanf("%d",&ptr[i]); } ptr = realloc(ptr, 8); printf("Enter number 8: "); for(int i = 0; i < 8; i++){ scanf("%d",&ptr[i]); } //print for(int i = 1; i <= 8; i++){ printf("number %d is %dn",i,ptr[i]); } return 0; } Written By : Akshay Bhagade
  • 67. Questions : 1) WAP to allocate memory of size n, where n is entered by the user. 2) Create an array of size 5 & enter its values from the user. 3) Allocate memory to store the first 5 odd numbers, then reallocate it to store the first 6 even numbers. Written By : Akshay Bhagade