0% found this document useful (0 votes)
224 views8 pages

The Ultimate C Handbook

The document is a comprehensive C Programming Handbook designed for beginners, covering fundamental concepts, variables, constants, control instructions, and practical examples. It explains the structure of a C program, the use of library functions, and provides hands-on exercises to reinforce learning. The handbook emphasizes C's efficiency and control, making it suitable for system-level programming and various applications.

Uploaded by

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

The Ultimate C Handbook

The document is a comprehensive C Programming Handbook designed for beginners, covering fundamental concepts, variables, constants, control instructions, and practical examples. It explains the structure of a C program, the use of library functions, and provides hands-on exercises to reinforce learning. The handbook emphasizes C's efficiency and control, making it suitable for system-level programming and various applications.

Uploaded by

Muskan Rastogi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Decision making instructions in c ...................................................................................................

17
TABLE OF CONTENTS C PROGRAMMING HANDBOOK BY CODEWITHHARRY CHAPTER 1: VARIABLES, CONSTANTS & KEYWORDS
if-else statement ........................................................................................................................... 17
PREFACE ........................................................................................................................................... 1
Code example: ............................................................................................................................. 17 WHAT IS PROGRAMMING? VARIABLES
Purpose and Audience .................................................................................................................... 1
Relational operators in c ................................................................................................................ 18
Structure and Content ..................................................................................................................... 1
Computer programming is a medium for us to communicate with computers. Just like A variable is a container which stores a ‘value’. In kitchen, we have containers storing
Logical operators .......................................................................................................................... 18 we use ‘Hindi’ or ‘English’ to communicate with each other, programming is a way for Rice, Dal, Sugar etc. Similar to that, variables in C stores value of a constant.
Why C?........................................................................................................................................... 1
Usage of logical operators: ............................................................................................................ 18 us to deliver our instructions to the computer.
Acknowledgements ........................................................................................................................ 1 Example:
else if clause ................................................................................................................................ 18
Conclusion ..................................................................................................................................... 1
Operator precedence .................................................................................................................... 19 WHAT IS C? a = 3; // a is assigned "3"
C Programming Handbook BY codewithharry ....................................................................................... 6 b = 4.7; // b is assigned "4.7"
Conditional operators ................................................................................................................... 19 C is a programming language.
What is programming? .................................................................................................................... 6 c = 'A'; // c is assigned 'A'
Switch case control instruction ...................................................................................................... 20
What is C? ...................................................................................................................................... 6 C is one of the oldest and finest programming languages.
Chapter 3 – Practice Set .................................................................................................................... 21
Uses of C ........................................................................................................................................ 6
Chapter 4: Loop control instruction ................................................................................................... 22 C was developed by Dennis Ritchie at AT&T’s Bell labs, USA in 1972. RULES FOR NAMING VARIABLES IN C
Chapter 1: Variables, Constants & Keywords ....................................................................................... 7
Why loops .................................................................................................................................... 22
Variables ........................................................................................................................................ 7 USES OF C 1. First character must be an alphabet or underscore (_)
Types of loops............................................................................................................................... 22
Rules for naming variables in C ........................................................................................................ 7 2. No commas, blanks are allowed.
while loop ..................................................................................................................................... 22 C language is used to program a wide variety of systems. Some of the uses of C are as
Constants ...................................................................................................................................... 7
3. No special symbol other than (_) allowed.
Increment and decrement operators .............................................................................................. 23 follows:
4. Variable names are case sensitive.
Types of constants .......................................................................................................................... 7
do–while loop ............................................................................................................................... 23 1. Major parts of Windows, Linux and other operating systems are written in C.
Keywords ....................................................................................................................................... 8
for loop......................................................................................................................................... 23 2. C is used to write driver programs for devices like tablets, printers etc.
Our first c program .......................................................................................................................... 8 We must create meaningful variable names in our programs. This enhances readability
A case of decrementing for loop ..................................................................................................... 24 3. C language is used to program embedded systems where programs need to run
Basic structure of a c program ......................................................................................................... 9 of our programs.
The break statement in c ............................................................................................................... 24 faster in limited memory (Microwave, Cameras etc.)
Comments ..................................................................................................................................... 9 4. C is used to develop games, an area where latency is very important, i.e., the
The continue statement in c........................................................................................................... 25 CONSTANTS
Compilation and execution .............................................................................................................. 9 computer must react quickly to user input.
Chapter 4 – Practice Set .................................................................................................................... 26
Library functions ........................................................................................................................... 10 An entity whose value does not change is called as a constant.
Project 1: Number guessing game ..................................................................................................... 27
Types of variables ......................................................................................................................... 10
INSTALLATION
Chapter 5 – Functions and Recursion ................................................................................................ 28 A variable is an entity whose value can be changed.
Receiving input from the user......................................................................................................... 10 We will use VS Code as our code editor to write our code and install MinGW gcc
What is a function? ....................................................................................................................... 28
Chapter 1- Practice Set ..................................................................................................................... 11 compiler to compile our C program. TYPES OF CONSTANTS
Function prototype........................................................................................................................ 28
Chapter 2: Instructions and operators ............................................................................................... 12 Primarily, there are three types of constants:
Function call................................................................................................................................. 28 Compilation is the process of translating high-level source code written in programming
Types of instructions ..................................................................................................................... 12 languages like C into machine code, which is the low-level code that a computer's CPU
Function definition ........................................................................................................................ 29 1. Integer Constant → 1,6,7,9
Type declaration instructions......................................................................................................... 12 can execute directly. Machine code consists of binary instructions specific to a
Important points ........................................................................................................................... 29
Arithmetic instructions .................................................................................................................. 12 computer's architecture. 2. Real Constant → 322.1, 2.5 ,7.0
Types of functions ......................................................................................................................... 29
Type conversion ............................................................................................................................ 13
Why use functions ........................................................................................................................ 29 We can install VS Code and MinGW from their respective websites 3. Character Constant → ‘a’, ‘$’, ‘@’ (must be enclosed within single quotes)
Operator precedence in c .............................................................................................................. 14
Passing values to function ............................................................................................................. 29
Operator precedence .................................................................................................................... 14
Note: ............................................................................................................................................ 30
Operator associativity ................................................................................................................... 14 Just install it like
Recursion ..................................................................................................................................... 31 a game!
Control Instructions ...................................................................................................................... 15
Important notes: ........................................................................................................................... 32
Chapter 2 – Practice Set .................................................................................................................... 16
Chapter 5 – Practice set .................................................................................................................... 33
Chapter 3: Conditional Instructions ................................................................................................... 17
Chapter 6- Pointers .......................................................................................................................... 34
2 3 6 7
The “address of” (&) operator ........................................................................................................ 34 Structures in memory .................................................................................................................... 49
PREFACE The ‘value at address’ operator (*) .................................................................................................. 34 Pointer to structures ..................................................................................................................... 49
Welcome to the “Ultimate C Programming Handbook," your comprehensive guide to mastering How to declare a pointer? .............................................................................................................. 34 Arrow operator .............................................................................................................................. 49
C programming. This handbook is designed for beginners and anyone looking to strengthen A program to demonstrate pointers ................................................................................................ 35 Passing structure to a function ...................................................................................................... 49
their foundational knowledge of C, a versatile and user-friendly programming language.
Output: ........................................................................................................................................ 35 typedef keyword ........................................................................................................................... 50
PURPOSE AND AUDIENCE Pointer to a pointer........................................................................................................................ 35 Chapter 9 – Practice set .................................................................................................................... 51
Types of function call .................................................................................................................... 36 Chapter 10 – File I/O ......................................................................................................................... 52
This handbook aims to make programming accessible and enjoyable for everyone. Whether
you're a student new to coding, a professional seeking to enhance your skills, or an enthusiast Call by value ................................................................................................................................. 36 File pointer ................................................................................................................................... 52
exploring C, this handbook will definitely be helpful. C’s simplicity and readability make it an Call by reference ........................................................................................................................... 36 File opening modes in C ................................................................................................................ 52
ideal starting point for anyone interested in programming. Chapter 6 – Practice set .................................................................................................................... 38 Types of files ................................................................................................................................. 53
Chapter 7 – Arrays ............................................................................................................................ 39 Reading a file ................................................................................................................................ 53
STRUCTURE AND CONTENT
Accessing elements ...................................................................................................................... 39 Closing the file .............................................................................................................................. 53
The handbook is divided into clear, concise chapters, each focused on a specific aspect of C:
Initialization of an array ................................................................................................................. 39 Write to a file ................................................................................................................................ 53
• Fundamental Concepts: Start with the basics and write your first program. Arrays in memory .......................................................................................................................... 40 fgetc() and fputc() ......................................................................................................................... 54
• Practical Examples: Illustrative examples and sample code demonstrate the Pointer arithmetic ......................................................................................................................... 40 EOF : end of file ............................................................................................................................. 54
application of concepts.
Accessing array using pointers ....................................................................................................... 41 Chapter 10 – Practice Set .................................................................................................................. 55
• Hands-On Exercises: End-of-chapter exercises reinforce learning and build confidence.
Passing array to functions ............................................................................................................. 41 Project 2: Snake, Water, Gun............................................................................................................. 56
WHY C? Multidimensional arrays ................................................................................................................ 41 Chapter 11 – Dynamic Memory Allocation .......................................................................................... 57
C is known for its efficiency and control, making it perfect for system-level programming. It is a 2-D arrays in memory .................................................................................................................... 41 Cynamic memory allocation .......................................................................................................... 57
low-level, compiled language that provides fine-grained control over hardware and memory, Chapter 7 – Practice Set .................................................................................................................... 43 Function for Dma in C.................................................................................................................... 57
supporting applications in operating systems, embedded systems, game development, and Chapter 8 – Strings ........................................................................................................................... 44 malloc() function .......................................................................................................................... 57
high-performance computing. C's power and flexibility make it a valuable tool for both novice
Initializing strings .......................................................................................................................... 44 calloc() function ............................................................................................................................ 57
and experienced programmers looking to understand how computers work at a deeper level.
Strings in memoryd ....................................................................................................................... 44 free() function ............................................................................................................................... 58
ACKNOWLEDGEMENTS Printing strings .............................................................................................................................. 44 realloc() function .......................................................................................................................... 58
I extend my gratitude to the educators, programmers, and contributors who have shared their Taking string input from the user .................................................................................................... 44 Chapter 11 – Practice set .................................................................................................................. 59
knowledge and insights, shaping the content of this handbook. Special thanks to all the gets() and puts() ............................................................................................................................ 45
students watching my content on YouTube and C community for maintaining a supportive and
Declaring a string using pointers .................................................................................................... 45
inspiring environment for learners worldwide.
Standard library functions for strings .............................................................................................. 45
CONCLUSION strlen() ......................................................................................................................................... 45
Learning programming can be both exciting and challenging. The “Ultimate C Programming strcpy() ......................................................................................................................................... 46
Handbook" aims to make your journey smooth and rewarding. Watch my video along with strcat() ......................................................................................................................................... 46
following this handbook for optimal learning. Let this guide be your stepping stone to success in strcmp() ....................................................................................................................................... 46
the world of programming.
Chapter 8 – Practice Set .................................................................................................................... 47
Chapter 9 – Structures ...................................................................................................................... 48
Why use Structures? ..................................................................................................................... 48 \\
Array of structures ........................................................................................................................ 48
Initializing structures ..................................................................................................................... 49
1 4 5
A compiler is a computer program which converts a C program into machine language CHAPTER 1- PRACTICE SET int a = 3.5; // In this case 3.5 (float) will be demoted to 3 (int) CONTROL INSTRUCTIONS
so that it can be easily understood by the computer. because a is not able to store floats.
1. Write a C program to calculate area of a rectangle: Determines the flow of control in a program four types of control instructions in C are:
A C program is written in plain text. a. Using hard coded inputs. float a = 8; // a will store 8.0 | 8 -> 8.0 (promotion to float)
1. Sequence Control instructions.
b. Using inputs supplied by the user.
This plain text is combination of instructions in a particular sequence. The compiler 2. Decision Control instructions
2. Calculate the area of a circle and modify the same program to calculate the
performs some basic checks and finally converts the program into an executable. 3. Loop Control instructions
volume of a cylinder given its radius and height. Quick Quiz: int k = 3.0 /9; value of k? and why?
4. Case Control instructions.
3. Write a program to convert Celsius (Centigrade degrees temperature to
Ans: 3.0/9 = 0.333. But since k is an int, it cannot store floats & value 0.33 is demoted to
Fahrenheit).
0.
LIBRARY FUNCTIONS 4. Write a program to calculate simple interest for a set of values representing
principal, number of years and rate of interest. OPERATOR PRECEDENCE IN C
C language has a lot of valuable library functions which is used to carry out certain
tasks. For instance printf() function is used to print values on the screen.
Have a look at the below statement:
#include <stdio.h>
3*x – 8*y is (3x)-(8y) or 3(x-8y)?
int main() {
int i = 10;
In C language simple mathematical rules like BODMAS, no longer apply.
printf("This is %d\n", i);
// %d for integers The answer to the above questions is provided by operator precedence & associativity.
// %f for real values (floating-point numbers)
// %c for characters
OPERATOR PRECEDENCE
return 0;
} The following table lists the operator priority in C
TYPES OF VARIABLES
Priority Operators
1. Integer variables → int a=3;
1st */%
2. Real variables → int a=7; float a=7.7;
3. Character variables → char a= ‘b’; 2nd +-
RECEIVING INPUT FROM THE USER 3rd =
In order to take input from the user and assign it to a variable, we use scanf() function Operators of higher priority are evaluated first in the absence of parenthesis.
Syntax: OPERATOR ASSOCIATIVITY
scanf("%d", &i); When operators of equal priority are present in an expression, the tie is taken care of by
‘&’ is the “address of” operator and it means that the supplied value should be copied associativity.
to the address which is indicated by variable i.
x*y/z → (x*y)/z
x/y*z → (x/y)*z
*, / follows left to right associativity
Pro Tip: Always use parenthesis in case of confusion
10 11 14 15
KEYWORDS BASIC STRUCTURE OF A C PROGRAM CHAPTER 2: INSTRUCTIONS AND OPERATORS • + (Addition)
• - (Subtraction)
These are reserved words, whose meaning is already known to the compiler. There are All C programs must follow a basic structure. A C program starts with a main function A C program is a set of instructions. Just like a recipe - which contains instructions to • * (Multiplication)
32 keywords available in C. and executes instructions present inside it. prepare a particular dish. • / (Division)
• % (Modulus)
auto double int struct Each instruction is terminated with a semicolon (;). TYPES OF INSTRUCTIONS
Note:
break long else switch There are some rules which are applicable to all the C programs: 1. Type declaration Instructions.
1. Operands can be int/float etc. + - * / are arithmetic operators.
2. Arithmetic Instructions
case return enum typedef 1. Every program’s execution starts from main() function.
3. Control Instructions. int b = 2, c = 3;
2. All the statements are terminated with a semicolon.
char register extern union int z; z = b*c; //legal
3. Instructions are case–sensitive.
TYPE DECLARATION INSTRUCTIONS int z; b*c = z; //illegal (not allowed)
const short float unsigned 4. Instructions are executed in the same order in which they are written.
This is how you declare a variable in C
continue signed for void COMMENTS
default sizeof goto volatile Comments are used to clarify something about the program in plain language. It is a int a; 2. % is the modular division operator
way for us to add notes to our program. There are two types of comments in C. o % → returns the remainder
do static if while float b;
o % → cannot be applied on float
1. Single line Comment: Single-line comments start with two forward slashes (//). char c; o % → sign is same as of numerator (-5%2=-1)
Any information after the slashes // lying on the same line would be ignored (will OTHER VARIATIONS: 3. No operator is assumed to pe present.
not be executed). int i = ab // invalid
OUR FIRST C PROGRAM Some other variations of this declaration look like this: int i = a * b //valid
#include <stdio.h> // This is a Single line comment. 4. There is no operator to perform exponentiation in C however we can use pow
int a; // Declare an integer variable 'a'
float b; // Declare a float variable 'b'
(x,y) from <math.h> (more later).
int main() {
2. Multi-line Comment: A multi-line comment starts with /* and ends with */. Any int i = 10; // Declare and initialize 'i' with 10
printf("Hello, I am learning C with Harry");
return 0; information between /* and */ will be ignored by the compiler. int j = i; // Declare 'j' and initialize with 'i' TYPE CONVERSION
} int a = 2, b = 3, c = 4, d = 5; // Declare and initialize multiple variables
/* An Arithmetic operation between
This is a multi-line comment int j1 = a + j - i; // Valid: use previously defined variables
*/ • int and int → int
Note: Comments in a C program are not executed and are ignored. // Invalid: 'a' is used before declaration • int and float → float
// float b = a + 3; • float and float → float
// float a = 1.1;
Example:
COMPILATION AND EXECUTION // Valid: Assigning the same value to multiple variables
int a, b, c, d; o 5/2 becomes 2 as both the operands are int
a = b = c = d = 30; // a, b, c, d all equal to 30 o 5.0/2 becomes 2.5 as one of the operands is float
o 2/5 becomes 0 as both the operands are int
NOTE:
ARITHMETIC INSTRUCTIONS
In programming, type compatibility is crucial. For int a = 3.5;, the float 3.5 is
Arithmetic instructions perform mathematical operations. demoted to 3, losing the fractional part because a is an integer. Conversely, for float
a = 8;, the integer 8 is promoted to 8.0, matching the float type of a and retaining
Here are some of the commonly used operators in C language:
precision.
8 9 12 13
RELATIONAL OPERATORS IN C CODE EXAMPLE CHAPTER 4: LOOP CONTROL INSTRUCTION INCREMENT AND DECREMENT OPERATORS
Relational operators are used to evaluate conditions (true or false) inside the if A typical if - else if - else ladder look like this: i++ → i is increased by 1
WHY LOOPS
statements. if{
Sometimes we want our programs to execute few sets of instructions over and over i -- → i is decreased by 1
// Statements
Some examples of relational operators are: again. For example: Printing 1 to100, first 100 even numbers etc.
} // Decrement i first and then print
else if{
==, >=, >, <, <=, != Hence loops make it easy for a programmer to tell computer that a given set of printf("--i = %d\n", --i);
// Statements
} instructions must be executed repeatedly.
Important note: ‘=’ is used for assignment // Print i first and then decrement
else{
whereas ‘==’ is used for equality check.
// Statements TYPES OF LOOPS printf("i-- = %d\n", i--);
The condition can be any valid expression. In C a non-zero value is considered to be } • +++ operator does not exist.
Primarily there are three types of loops in C language:
true. IMPORTANT NOTE • i+=2 is compound assignment which translates to i = i + 2
1. while loop • Similar to += operator we have other operators like -=, *=, /=, %=.
1. Using if-else if -else reduces indents.
LOGICAL OPERATORS 2. The last “else” is optional. 2. do–while loop
3. for loop DO–WHILE LOOP
&&, || and !, are three logical operators in C. These are read as “AND”, “OR” and “NOT” 3. Also there can be any number of “else if”.
4. Last else is executed only if all conditions fail. The syntax of do-while loop looks like this:
We will look into these one by one:
They are used to provide logic to our C programs.
OPERATOR PRECEDENCE WHILE LOOP
do {
USAGE OF LOGICAL OPERATORS: //code;
Priority Operator while (condition is true) { } while (condition);
1. && (AND) → is true when both the conditions are true
// Code The do–while loop works very similar to while loop.
a. “1 and 0” is evaluated as false. 1st !
// The block keeps executing as long as the condition is true
b. “0 and 0” is evaluated as false. } • ‘while’ checks the condition & then executes the code.
2nd *, /, %
c. “1 and 1” is evaluated as true. • ‘do-while’ executes the code & then checks the condition.
Example:
2. || (OR) → is true when at least one of the conditions is true. (1 or 0 → 1) (1 or 1 → 1) 3rd +, -
3. ! (NOT) → returns true if given false and false if given true int i = 0; In simpler terms we can say:
a. !(3==3) → evaluates to false 4th <>, <=, >= while (i<10) {
do-while loop = while loop which executes at least once.
b. !(3>30) → evaluates to true. 5th ==, != printf("the value of i is %d\n", i);
i++; Quick Quiz: Write a program to print first ‘n’ natural number using do-while loop.
As the number of conditions increases, the level of indentation increases. This reduces 6th && }
readability. Logical operators come to rescue in such cases. Note: If the condition never becomes false, the while loop keeps getting executed. Such Input: 4
7th ||
loop is known as an infinite loop.
ELSE IF CLAUSE
8th =
Quick Quiz: Write a program to print natural numbers from 10 to 20 when initial loop Output: 1
Instead of using multiple if statements, we can also use else if along with it thus forming
counter is initialized to 0. 2
an if-else if-else ladder. CONDITIONAL OPERATORS 3
A shorthand “if – else” can be written using the conditional or ternary operators The loop counter need not be int, it can be float as well. 4
condition ? expression-if-true : expression-if-false
FOR LOOP
// Here "?" and ":" are called Ternary Operators The syntax of a typical ‘for’ loop looks like this:
for (initialize; test; increment or decrement)
{
18 19 22 23
CHAPTER 2 – PRACTICE SET CHAPTER 3: CONDITIONAL INSTRUCTIONS SWITCH CASE CONTROL INSTRUCTION CHAPTER 3 – PRACTICE SET
1. Which of the following is invalid in C? Sometimes we want to watch comedy videos on YouTube if the day is Sunday. switch-case is used when we have to make a choice between number of alternatives for 1. What will be the output of this program
a. int a=1; int b = a; a given variable.
Sometimes we order junk food if it is our friend’s birthday in the hostel. int a = 10;
b. int v = 3*3;
switch (integer expression) if (a = 11)
c. char dt = ‘21 dec 2020’; You might want to buy an umbrella if it’s raining, and you have the money. printf("I am 11");
{
2. What data type will 3.0/8 – 2 return? else
3. Write a program to check whether a number is divisible by 97 or not. You order the meal if dal or your favourite bhindi is listed on the menu. printf("I am not 11");
case c1:
4. Explain step by step evaluation of 3*x/y – z+k, where x=2, y=3, z=3, k=1 // code; 2. Write a program to determine whether a student has passed or failed. To pass, a
All these are decisions which depends on a condition being met.
5. 3.0 + 1 will be: student requires a total of 40% and at least 33% in each subject. Assume there
a. Integer. In C language too, we must be able to execute instructions on a condition(s) being met. case c2: // c1, c2 & c3 -> Constants
are three subjects and take the marks as input from the user.
// code; // code -> Any valid C code.
b. Floating point number. 3. Calculate income tax paid by an employee to the government as per the slabs
c. Character. DECISION MAKING INSTRUCTIONS IN C case c3: mentioned below:
// code:
• if–else statement Income Slab Tax
• switch statement default:
// code; 2.5 – 5.0L 5%
IF-ELSE STATEMENT }
5.0L - 10.0L 20%
The syntax of an if-else statement in C looks like: The value of integer-expression is matched against c1, c2, c3… If it matches any of
these cases, that case along with all subsequent “case” and “default” statements are Above 10.0L 30%
if (condition_to_be_checked) { executed.
Note that there is no tax below 2.5L. Take income amount as an input from the user.
// Statements if condition is true
Quick Quiz: Write a program to find grade of a student given his marks based on below:
} else { 4. Write a program to find whether a year entered by the user is a leap year or not.
// Statements if condition is false 90 – 100 => A Take year as an input from the user.
} 80 – 90 => B 5. Write a program to determine whether a character entered by the user is
70 – 80 => C lowercase or not.
60 – 70 => D 6. Write a program to find greatest of four numbers entered by the user.
CODE EXAMPLE: 50 – 60 => E
int a = 23; <50 => F
if (a > 18)
{ Some Important Notes:
printf("you can drive \n");
} • We can use switch-case statements even by writing cases in any order of our
Note that else block is not necessary but optional. choice (not necessarily ascending).
• char values are allowed as they can be easily evaluated to an integer.
• A switch can occur within another but in practice this is rarely done.
16 17 20 21
CHAPTER 4 – PRACTICE SET PROJECT 1: NUMBER GUESSING GAME A function prototype in programming is a declaration of a function that specifies its Quick Quiz: Use the library function to calculate the area of a square with side a.
name, return type, and parameters (if any) but does not include the function body.
1. Write a program to print multiplication table of a given number n. We will write a program that generates a random number and asks the player to guess
2. Write a program to print multiplication table of 10 in reversed order. it. If the player’s guess is higher than the actual number, the program displays “Lower The above prototype means that sum is a function which takes values ‘a’ (of type int)
3. A do while loop is executed: number please”. Similarly, if the user’s guess is too low, the program prints “Higher and ‘b’ (of type int) and returns a value of type int.
a. At least once. number please”.
Function definition of sum can be:
b. At least twice.
When the user guesses the correct number, the program displays the number of
c. At most once. int sum (int a, int b) { // a and b are parameters
guesses the player used to arrive at the number.
4. What can be done using one type of loop can also be done using the other two int c;
types of loops – true or false? Hint: Use loop & use a random number generator. c = a+b;
5. Write a program to sum first ten natural numbers using while loop.
return c;
6. Write a program to implement program 5 using ‘for’ and ‘do-while’ loop.
}
7. Write a program to calculate the sum of the numbers occurring in the
// Now we can call sum (2,3); from main to get 5 in return. Here 2 & 3 are
multiplication table of 8. (consider 8 x 1 to 8 x 10).
arguments.
8. Write a program to calculate the factorial of a given number using a for loop.
9. Repeat 8 using while loop. int d = sum (2,3); // d becomes 5
RECURSION
10. Write a program to check whether a given number is prime or not using loops. NOTE:
11. Implement 10 using other types of loops. A function defined in C can call itself. This is called recursion. A function calling itself is
1. Parameters are the values or variable placeholders in the function definition. also called ‘recursive’ function.
Example a & b.
2. Arguments are the actual values passed to the function to make a call. Example Example:
2 & 3. A very good example of recursion is factorial.
3. A function can return only one value at a time.
4. If the passed variable is changed inside the function, the function call doesn’t Factorial(n) = 1 x 2 x 3 … x n
change the value in the calling function.
Factorial(n) = 1 x 2 x3 … (n-1) x n
int change(int a) {
Factorial(n) = Factorial (n-1) x n
a = 77; // Misnomer
return 0;
Since we can write factorial of a number in terms of itself, we can program it using
}
recursion.
‘change’ is a function which pretends to change ‘a’ to 77. Now if we call it from main
like this int factorial(int x) {
int f;
int b=22;
change(b); // The value of b remains 22 if (x == 0 || x == 1) {
printf("b is %d", b); // Prints "b is 22" return 1; // a program to calculate factorial using recursion
This happens because a copy of ‘b’ is passed to the change function } else {
f = x * factorial(x - 1);
return f;
}
}
26 27 30 31
//code; CHAPTER 5 – FUNCTIONS AND RECURSION FUNCTION DEFINITION
}
for (i=0; i<1000; i++){ Sometimes our program gets bigger in size and it's not possible for a programmer to This part contains the exact set of instructions executed during the function call.
printf("%d\n",i); track which piece of code is doing what.
• Initialize → Setting a loop counter to an initial value. if (i==5){ When a function is called from main(), the main function pauses and temporarily
• Test → Checking a condition. break; Function is a way to break our code into chunks so that it is possible for a programmer suspends. During this time, control transfers to the called function. Once the function
• Increment → Updating the loop counter. } to reuse them. finishes executing, main() resumes.
}
Example: WHAT IS A FUNCTION? Quick Quiz: Write a program with three functions
OUTPUT
A function is a block of code which performs a particular task. 1. Good morning function which prints “good morning”.
for (i=0; i<3; i++){
0 2. Good afternoon function which prints “good afternoon”.
printf("%d\n", i); A function can be reused by the programmer in a given program any number of times.
1 3. Good night function which prints “good night”.
printf("\n"); 2
}
Syntax: main() should call all of these in order 1→2→3
3
// Output: 4 #include <stdio.h>
// 0 5 IMPORTANT POINTS
// 1 The output of the above program will be below (and not 0 to 100) • Execution of a C program starts from main().
// 2 // Function prototype • A C program can have more than one function.
Quick Quiz: Write a program to print first ‘n’ natural numbers using for loop THE CONTINUE STATEMENT IN C void display(); • Every function gets called directly or indirectly from main().
The ‘continue’ statement is used to immediately move to the next iteration of the loop.
A CASE OF DECREMENTING FOR LOOP int main() { TYPES OF FUNCTIONS
The control is taken to the next iteration thus skipping everything below “continue” int a; // Variable declaration
for (i=5; i ; i--) display(); // Function call There are two functions in C. Let's talk about them.
inside the loop for that iteration.
printf("%d\n",i); return 0; // Return statement
This for loop will keep on running until i become 0. 1. Library functions → Commonly required functions grouped together in a library
Example: }
file on disk.
The loop runs in following steps: #include <stdio.h>
// Function definition 2. User defined function → These are the functions declared and defined by the
int main() { void display() { user.
1. ‘i’ is initialized to 5.
int skip = 5; printf("hi i am display\n"); // Printing the message
2. The condition “i” (0 or none) is tested. int i = 0;
} WHY USE FUNCTIONS
3. The code is executed. while (i < 10) {
if (i == skip) {
4. ‘i’ is decremented. i++;
FUNCTION PROTOTYPE 1. To avoid rewriting the same logic again and again.
5. Condition ‘i’ is checked & code is executed if it’s not 0. continue; // skips the rest of the loop body for i == 5 2. To keep track of what we are doing in a program
} A function prototype informs the compiler about a function that will be defined later in
6. And so on until ‘i’ is non 0. 3. To test and check logic independently.
printf("%d\n", i); the program.
i++;
Quick Quiz: Write a program to print ‘n’ natural numbers in reverse order. } PASSING VALUES TO FUNCTION
The void keyword indicates that the function does not return any value.
return 0;
} We can pass values to a function and can get a value in return from a function.
THE BREAK STATEMENT IN C
Notes: FUNCTION CALL
The ‘break’ statement is used to exit the loop irrespective of whether the condition is Have a look at the code snippet below:
1. Sometimes, the name of the variable might not indicate the behaviour of the A function call instructs the compiler to execute the function's body when the call is
true or false.
program. made.
Whenever a “break” is encountered inside the loop, the control is sent outside the loop 2. ‘break’ statement completely exits the loop. Note that program execution starts from the main function and follows the sequence of int sum (int a, int b)
1. ‘continue’ statement skips the particular iteration of the loop. instructions written.
Let us see this with the help of an example:
24 25 28 29
CHAPTER 6 – PRACTICE SET CHAPTER 7 – ARRAYS
CHAPTER 6- POINTERS int *in_ptr; //pointer to integer 1. Write a program to print the address of a variable. Use this address to get the An array is a collection of similar elements. Array allows a single variable to store
char *ch_ptr; //pointer to character
value of the variable. multiple values.
A pointer is a variable which stores the address of another variable. float *fl_ptr; //pointer to float
2. Write a program having a variable ‘i’. Print the address of ‘i’. Pass this variable to
Although it’s a good practice to use meaningful variable names, we should be very SYNTAX:
a function and print its address. Are these addresses same? Why?
careful while reading and working on programs from fellow programmers.
3. Write a program to change the value of a variable to ten times of its current int marks[90]; // integer array
value. char name[20]; // character array or string
A PROGRAM TO DEMONSTRATE POINTERS
4. Write a function and pass the value by reference. float percentile[90]; // float array
#include <stdio.h> 5. Write a program using a function which calculates the sum and average of two The values can now be assigned to make array like this:
numbers. Use pointers and print the values of sum and average in main().
int main (){ marks[0] = 33;
int i = 8; 6. Write a program to print the value of a variable i by using “pointer to pointer” type
marks[1] = 12;
int *j; of variable.
Note: It is very important to note that the array index starts with 0.
j = &i; 7. Try problem 3 using call by value and verify that it does not change the value of
printf("add i= %u\n",&i); the said variable.
printf("add i= %u\n",j);
printf("add j= %u\n",&j);
printf("value i= %d\n",i);
THE “ADDRESS OF” (&) OPERATOR printf("value i= %d\n",*(&i));
printf("value i= %d\n",*j);
The address of operator is used to obtain the address of a given variable.
return 0;
If you refer to the diagrams above, }
&i → 87994
OUTPUT:
&j → 87998
add i= 87994
Format specifier for printing pointer address is ‘%p’. add i= 87994
add j= 87998 ACCESSING ELEMENTS
THE ‘VALUE AT ADDRESS’ OPERATOR (*)
value i= 8 Elements of an array can be accessed using:
The value at address or * operator is used to obtain the value present at a given memory value i= 8
address. It is denoted by *. value i= 8 scanf("%d", &marks[0]); // input first value
printf("%d", marks[0]); // output first value of the array
*(&i) =72 This program sums it all. If you understand it, you have got the idea of pointers.
Quick Quiz: Write a program to accept marks of five students in an array and print them
*(&j) = 87994 POINTER TO A POINTER on the screen.
HOW TO DECLARE A POINTER? Just like ‘j’ is pointing to ‘i’ or storing the address of ‘i’, we can have another variable k INITIALIZATION OF AN ARRAY
which can further store the address of ‘j’. What will be the type of ‘k’?
A pointer is declared using the following syntax. There are many other ways in which an array can be initialized.
int **k;
• int *j => declare a variable j of type int-pointer k = &j; int cgpa[3] = {9, 8, 8}; // arrays can be initialized while declaration
float marks[] = {33, 40};
• j=&i => store address of i in j.
Just like pointer of type integer, we also have pointers to char, float etc.
34 35 38 39
DRY RUN OF RECURSIVE FACTORIAL PROGRAM CHAPTER 5 – PRACTICE SET EXAMPLE
void swap (int *x, int *y)
1. Write a program using function to find average of three numbers. {
2. Write a function to convert Celsius temperature into Fahrenheit. int temp;
3. Write a function to calculate force of attraction on a body of mass ‘m’ exerted by temp = *x;
earth. Consider g = 9.8m/s2. *x = *y;
*y = temp;
4. Write a program using recursion to calculate nth element of Fibonacci series.
}
5. What will the following line produce in a C program:
This function is capable of swapping the values passed to it. If a = 3 and b = 4 before a
int a = 4;
printf("%d %d %d \n", a, ++a, a++); call to swap(a, b), then a = 4 and b = 3 after calling swap.
6. Write a recursive function to calculate the sum of first ‘n’ natural numbers.
int main(){
7. Write a program using function to print the following pattern (first n lines) int a = 3;
int b = 4; // a is 3 and b is 4
*
We can even go further one level and create a variable ‘l’ of type int*** to store the swap(&a, &b);
*** address of ‘k’. We mostly use int* and int** sometimes in real world programs. return 0; //now a is 4 and b is 3
}
***** TYPES OF FUNCTION CALL
Based on the way we pass arguments to the function, function calls are of two types.
1. Call by value → Sending the values of arguments.
2. Call by reference → Sending the address of arguments.
IMPORTANT NOTES:
CALL BY VALUE
1. Recursion is often a direct way to implement certain algorithms, but not
always the most direct for every algorithm. Recursion is particularly suited for Here the values of the arguments are passed to the function. Consider this example:
problems that can be divided into smaller, similar subproblems (like factorial
int c = sum (3,4); //assume x=3 and y=4
computation or tree traversal), but for some algorithms, iterative approaches
might be more straightforward or efficient. If sum is defined as sum (int a, int b), the values 3 and 4 are copied to a and b. Now even
2. The condition in a recursive function that stops further recursion is called if we change a and b, nothing happens to the variables x and y.
the base case. This correction clarifies that the base case is crucial as it This is call by value.
prevents infinite recursion and ensures the function terminates correctly.
3. Sometimes, due to an oversight by the programmer, a recursive function can In C we usually make a call by value.
continue to run indefinitely without reaching a base case, potentially
causing a stack overflow or memory error. This statement highlights the risk of CALL BY REFERENCE
infinite recursion and its consequences, emphasizing the importance of properly Here the address of the variables is passed to the function as arguments.
defining base cases in recursive functions.
Now since the addresses are passed to the function, the function can now modify the
value of a variable in calling function using * and & operators.
32 33 36 37
CHAPTER 7 – PRACTICE SET STRCPY() CHAPTER 8 – PRACTICE SET
1. Create an array of 10 numbers. Verify using pointer arithmetic that (ptr+2) points This function is used to copy the content of second string into first string passed to it. 1. Which of the following is used to appropriately read a multi-word string.
to the third element where ptr is a pointer pointing to the first element of the 1. gets()
char source[] = "harry";
array. 2. puts()
char target[30];
2. If S[3] is a 1-D array of integers then *(S+3) refers to the third element: strcpy (target,source); //target now contains "harry" 3. printf()
(i) True. 4. scanf()
target string should have enough capacity to store the source string.
(ii) False. 2. Write a program to take string as an input from the user using %c and %s confirm
Quick Quiz: Create a 2-d array by taking input from the user. Write a display function to (iii) Depends. STRCAT() that the strings are equal.
print the content of this 2-d array on the screen. 3. Write a program to create an array of 10 integers and store multiplication table of 3. Write your own version of strlen function from <string.h>
5 in it. This function is used to concatenate two strings. 4. Write a function slice() to slice a string. It should change the original string such
4. Repeat problem 3 for a general input provided by the user using scanf. that it is now the sliced string. Take ‘m’ and ‘n’ as the start and ending position
char s1[12] = "hello";
5. Write a program containing a function which reverses the array passed to it. char s2[] = "harry"; for slice.
6. Write a program containing functions which counts the number of positive strcat(s1,s2); // s1 now contains "helloharry" <no space in between> 5. Write your own version of strcpy function from <string.h>
integers in an array. 6. Write a program to encrypt a string by adding 1 to the ascii value of its
7. Create an array of size 3 x 10 containing multiplication tables of the numbers 2,7 characters.
STRCMP()
and 9 respectively. 7. Write a program to decrypt the string encrypted using encrypt function in
8. Repeat problem 7 for a custom input given by the user. This function is used to compare two strings. It returns 0 if the strings are equal, a problem 6.
9. Create a three–dimensional array and print the address of its elements in negative value if the first string's mismatching character's ASCII value is less than the 8. Write a program to count the occurrence of a given character in a string.
increasing order. second string's corresponding mismatching character, and a positive value otherwise. 9. Write a program to check whether a given character is present in a string or not.
strcmp("far", "joke"); // Negative value
strcmp("joke", "far"); // Positive value
42 43 46 47
ARRAYS IN MEMORY ACCESSING ARRAY USING POINTERS CHAPTER 8 – STRINGS scanf automatically adds a null character when the enter key is pressed.
Consider this array: Consider this array: A string is a 1-D character array terminated by a null character (‘\0’) Note:
int arr[3] = {1, 2, 3} // 1 integer = 4 bytes A null character is used to denote the termination of a string. Characters are stored in 1. The string should be short enough to fit into the array.
contiguous memory locations. 2. scanf cannot be used to input multi-word strings with spaces.
This will reserve 4 x 3 = 12 bytes in memory (4 bytes for each integer).
INITIALIZING STRINGS GETS() AND PUTS()
Since string is an array of characters, it can be initialized as follows: gets() is a function which can be used to receive a multi-word string.
If ptr points to index 0, ptr++ will point to index 1 & so on…
char s[] = {'H', 'A', 'R', 'R', 'Y', '\0'}; char st[30];
This way we can have an integer pointer pointing to first element of the array like this: gets(st); // The entered string is stored in st!
There is another shortcut for initializing string in C language:
multiple gets() calls will be needed for multiple strings.
POINTER ARITHMETIC int *ptr = &arr[0]; // or simple arr char s[] = "HARRY"; // In this case C adds a null character automatically.
ptr++; Likewise, puts can be used to output a string.
A pointer can be incremented to point to the next memory location of that type.
*ptr // will have 9 as its value STRINGS IN MEMORY
puts(st); // Prints the string & places the cursor on the next line
Consider this example: PASSING ARRAY TO FUNCTIONS A string is stored just like an array in the memory as shown below.
DECLARING A STRING USING POINTERS
int i = 32; Array can be passed to the functions like this:
int *a = &i; // a = 87994 We can declare strings using pointers.
a++; // address of i or value of a = 87998 printArray(arr, n); // function call
void printArray(int *i, int n); // function prototype char *ptr = "harry";
char a = 'A'; // or This tells the compiler to store the string in memory and assigned address is stored in a
char *b = &a; // a= 87994 void printArray(int i[], int n); char pointer.
b++; // now a = 87995
MULTIDIMENSIONAL ARRAYS
Note:
float i = 1.7;
float *a = &i; // now a = 87994 An array can be of 2 dimension/ 3 dimension/ n dimensions.
1. Once a string is defined using char st [] = “harry”, it cannot be reinitialized to
a++; // now a = 87998
A 2 dimensions array can be defined like this: something else.
Following operations can be performed on a pointer: 2. A string defined using pointers can be reinitialized.
int arr[3][2] = {{1, 4}
1. Addition of a number to a pointer. ptr = "Rohan";
{7, 9} Quick Quiz: Create a string using double quotes and print its content using a loop.
2. Subtraction of a number from a pointer. {11, 22}};
3. Subtraction of one pointer from another. We can access the elements of this array as arr[0][0] , arr[0][1] & so on … PRINTING STRINGS STANDARD LIBRARY FUNCTIONS FOR STRINGS
4. Comparison of two pointer variables.
A string can be printed character by character using printf and %c.
C provides a set of standard library functions for string manipulation.
Quick Quiz: Try these operations on another variable by creating pointers in a separate
But there is another convenient way to print strings in C.
program. Demonstrate all the four operations. 2-D ARRAYS IN MEMORY Some of the most commonly used string functions are:
char st[] = "HARRY";
A 2d array like a 1d array is stored in contiguous memory blocks like this: STRLEN()
printf("%s", st); // print the entire string.
TAKING STRING INPUT FROM THE USER This function is used to count the number of characters in the string excluding the null
(‘\0’) characters.
We can use %s with scanf to take string input from the user:
int length = strlen(st);
char st[50];
scanf ("%s", st); These functions are declared under <string.h> header file.
40 41 44 45
Quick Quiz: Complete this show function to display the content of employee. CHAPTER 9 – PRACTICE SET FGETC() AND FPUTC() CHAPTER 10 – PRACTICE SET
TYPEDEF KEYWORD 1. Create a two-dimensional vector using structures in C. fgetc and fputc are used to read and write a character from / to a file. 1. Write a program to read three integers from a file.
2. Write a function ‘sumVector’ which returns the sum of two vectors passed to it. 2. Write a program to generate multiplication table of a given number in text
We can use the ‘typedef’ keyword to create an alias name for data types in C. fgetc(ptr); // used to read a character from file
The vectors must be two–dimensional. format. Make sure that the file is readable and well formatted.
fputc('c', ptr); // used to write character 'c' to the file
‘typedef’ is more commonly used with structures. 3. Twenty integers are to be stored in memory. What will you prefer- Array or 3. Write a program to read a text file character by character and write its content
structure? EOF : END OF FILE twice in separate file.
struct Complex 4. Write a program to illustrate the use of arrow operator → in C. 4. Take name and salary of two employees as input from the user and write them to
{ fgetc returns EOF when all the characters from a file have been read. So, we can write a
5. Write a program with a structure representing a complex number. a text file in the following format:
float real; check like below to detect end of file:
6. Create an array of 5 complex numbers created in Problem 5 and display them i. Name1, 3300
float img; // struct complex c1,c2, for defining complex numbers with the help of a display function. The values must be taken as an input from ii. Name2, 7700
while(1)
};
the user. { 5. Write a program to modify a file containing an integer to double its value.
7. Write problem 5’s structure using ‘typedef’ keywords. ch = fgetc(ptr); // when all the content of a file has been read break
typedef struct Complex
8. Create a structure representing a bank account of a customer. What fields did the loop!
{
float real;
you use and why? if (ch == EOF)
float img; // ComplexNo c1,c2,for defining complex numbers 9. Write a structure capable of storing date. Write a function to compare those {
} ComplexNo; dates. break;
10. Solve problem 9 for time using ‘typedef’ keyword. }
// code
}
EXAMPLE USAGE
Using the typedef alias, you can declare complex number variables more succinctly:
ComplexNo c1, c2;
50 51 54 55
CHAPTER 9 – STRUCTURES INITIALIZING STRUCTURES CHAPTER 10 – FILE I/O TYPES OF FILES
Array and strings → Similar data (int, float, char). Structures can also be initialized as follows: The random-access memory is volatile, and its content is lost once the program Primarily, there are two types of files:
terminates. In order to persist the data forever we use files.
Structures can hold → Dissimilar data. struct employee harry = {100, 71.22, "harry"}; 1. Text files (.txt, .c)
struct employee shubh = {0}; //All elements set to 0 A file is data stored in a storage device. 2. Binary files (.jpg, .dat)
A C structure can be created as follows:
STRUCTURES IN MEMORY A C program can talk to the file by reading content from it and writing content to it. READING A FILE
struct employee
{
Structures are stored in contiguous memory locations. For the structure ‘e1’ of type A file can be opened for reading as follows:
int code; // This declares a new user defined data type!
float salary; struct employee, memory layout looks like this:
char name[10]; FILE *ptr;
}; // semicolon is important
ptr = fopen("harry.txt", "r");
We can use this user defined data type as follows: int num;
struct employee e1; // creating a structure variable Let us assume that "harry.txt" contains an integer we can read that integer using:
strcpy(e1.name, "harry");
e1.code = 100; fscanf(ptr, "%d", &num); // fscanf is file counterpart of scanf
e1.salary = 71.22; This will read an integer from file in Num variables.
So, a structure in C is a collection of variables of different types under a single name.
In an array of structures, these employee instances are stored adjacent to each other. FILE POINTER Quick Quiz: Modify the program above to check whether the file exists or not before
Quick Quiz: Write a program to store the details of 3 employees from user defined data. opening the file.
A “FILE” is a structure which needs to be created for opening the file.
Use the structure declared above. POINTER TO STRUCTURES
A file pointer is a pointer to this structure of the file. CLOSING THE FILE
WHY USE STRUCTURES? A pointer to structures can be created as follows:
(FILE pointer is needed for communication between the file and the program).
It is very important to close the file after read or write. This is achieved using fclose as
We can create the data types in the employee structure separately but when the struct employee *ptr; A FILE pointer can be created as follows: follows:
number of properties in a structure increases, it becomes difficult for us to create data ptr = &e1;
variables without structures. In a nutshell: // now we can print structure elements using: FILE *ptr; fclose(ptr);
printf("%d", (*ptr).code); ptr = fopen("filename.ext"; "mode"); This will tell the compiler that we are done working with this file and the associated
a. Structures keep the data organized.
resources could be freed.
b. Structures make data management easy for the programmer. ARROW OPERATOR FILE OPENING MODES IN C
Instead of writing (*ptr).code, we can use arrow operator to access structure properties C offers the programmers to select a mode for opening a file. WRITE TO A FILE
ARRAY OF STRUCTURES as follows:
Following modes are primarily used in C File I/O. We can write to a file in a very similar manner like we read the file
Just like an array of integers, an array of floats and an array of characters, we can create
(*ptr).code
an array of structures. "r" -> open for reading FILE *fptr;
//or
"rb" -> open for reading in binary fptr = fopen("harry.txt", "w");
struct employee facebook[100]; // an array of structures ptr->code "w" -> open for writing // If the file exists, the contents will be int num = 432;
// we can access the data using: // here -> is known as the arrow operator. overwritten
facebook[0].code = 100; fprintf(fptr, "%d", num);
"wb" -> open for writing in binary
facebook[1].code = 101; PASSING STRUCTURE TO A FUNCTION fclose(fptr);
"a" -> open for append // If the file does not exist, it will be created
// And so on
A structure can be passed to a function just like any other data type.
void show(struct employee e); // function prototype
48 49 52 53
FREE() FUNCTION CHAPTER 11 – PRACTICE SET
We can use free() function to deallocate the memory. The memory allocated using 1. Write a program to dynamically create an array of size 6 capable of storing 6
calloc/malloc is not deallocated automatically. integers.
2. Use the array in problem 1 to store 6 integers entered by the user.
Syntax:
3. Solve problem 1 using calloc().
free(ptr); //memory of ptr is released. 4. Create an array dynamically capable of storing 5 integers. Now use realloc so
Quick Quiz: Write a program to demonstrate the usage of free() with malloc(). that it can now store 10 integers.
5. Create an array of multiplication table of 7 upto 10 (7 x 10 = 70). Use realloc to
REALLOC() FUNCTION make it store 15 number (from 7 x 1 to 7 x 15).
6. Attempt problem 4 using calloc().
Sometimes the dynamically allocated memory is insufficient or more than required.
realloc is used to allocate memory of new size using the previous pointer and size.
Syntax:
ptr = realloc (ptr, newsize);
ptr = realloc (ptr, 3*sizeof(int));
58 59
PROJECT 2: SNAKE, WATER, GUN CHAPTER 11 – DYNAMIC MEMORY ALLOCATION
Snake, water, gun or rock, paper, scissors is a game most of us have played during C is a language with some fixed rules of programming. For example: Changing the size
school time. (I sometimes play it even now). of an array is not allowed.
Write a C program capable of playing this game with you. DYNAMIC MEMORY ALLOCATION
Your program should be able to print the result after you choose snake/water or gun. Dynamic memory allocation is a way to allocate memory to a data structure during the
runtime. We can use DMA function available in C to allocate and free memory during
runtime.
FUNCTION FOR DMA IN C
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 number of bytes to be allocated as an
input and returns a pointer of type void.
Syntax:
ptr = (int*)malloc(30* sizeof (int))
The expression returns a null pointer if the memory cannot be allocated.
Quick Quiz: Write a program to create a dynamic array of 5 floats using malloc().
CALLOC() FUNCTION
calloc stands for continuous allocation. It initializes each memory block with a default
value of 0.
Syntax:
ptr = (float*)calloc(30, sizeof (float));
//allocates contiguous space in memory for 30 blocks (floats)
It the space is not sufficient, memory allocation fails, and a NULL pointer is returned.
Quick Quiz: Write a program to create an array of size n using calloc where n is an
integer entered by the user.
56 57

You might also like