🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

The Ultimate C Handbook (1).pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

PREFACE Welcome to the “Ultimate C Programming Handbook," your comprehensive guide to mastering C programming. This handbook is designed for beginners and anyone looking to strengthen their foundational knowledge of C, a versatile and user-friendly programmi...

PREFACE Welcome to the “Ultimate C Programming Handbook," your comprehensive guide to mastering C programming. This handbook is designed for beginners and anyone looking to strengthen their foundational knowledge of C, a versatile and user-friendly programming language. PURPOSE AND AUDIENCE 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 exploring C, this handbook will definitely be helpful. C’s simplicity and readability make it an ideal starting point for anyone interested in programming. STRUCTURE AND CONTENT The handbook is divided into clear, concise chapters, each focused on a specific aspect of C: Fundamental Concepts: Start with the basics and write your first program. Practical Examples: Illustrative examples and sample code demonstrate the application of concepts. Hands-On Exercises: End-of-chapter exercises reinforce learning and build confidence. WHY C? C is known for its efficiency and control, making it perfect for system-level programming. It is a low-level, compiled language that provides fine-grained control over hardware and memory, supporting applications in operating systems, embedded systems, game development, and high-performance computing. C's power and flexibility make it a valuable tool for both novice and experienced programmers looking to understand how computers work at a deeper level. ACKNOWLEDGEMENTS I extend my gratitude to the educators, programmers, and contributors who have shared their knowledge and insights, shaping the content of this handbook. Special thanks to all the students watching my content on YouTube and C community for maintaining a supportive and inspiring environment for learners worldwide. CONCLUSION Learning programming can be both exciting and challenging. The “Ultimate C Programming Handbook" aims to make your journey smooth and rewarding. Watch my video along with following this handbook for optimal learning. Let this guide be your stepping stone to success in the world of programming. 1 TABLE OF CONTENTS PREFACE........................................................................................................................................... 1 Purpose and Audience.................................................................................................................... 1 Structure and Content..................................................................................................................... 1 Why C?........................................................................................................................................... 1 Acknowledgements........................................................................................................................ 1 Conclusion..................................................................................................................................... 1 C Programming Handbook BY codewithharry....................................................................................... 6 What is programming?.................................................................................................................... 6 What is C?...................................................................................................................................... 6 Uses of C........................................................................................................................................ 6 Chapter 1: Variables, Constants & Keywords....................................................................................... 7 Variables........................................................................................................................................ 7 Rules for naming variables in C........................................................................................................ 7 Constants...................................................................................................................................... 7 Types of constants.......................................................................................................................... 7 Keywords....................................................................................................................................... 8 Our first c program.......................................................................................................................... 8 Basic structure of a c program......................................................................................................... 9 Comments..................................................................................................................................... 9 Compilation and execution.............................................................................................................. 9 Library functions........................................................................................................................... 10 Types of variables......................................................................................................................... 10 Receiving input from the user......................................................................................................... 10 Chapter 1- Practice Set..................................................................................................................... 11 Chapter 2: Instructions and operators............................................................................................... 12 Types of instructions..................................................................................................................... 12 Type declaration instructions......................................................................................................... 12 Arithmetic instructions.................................................................................................................. 12 Type conversion............................................................................................................................ 13 Operator precedence in c.............................................................................................................. 14 Operator precedence.................................................................................................................... 14 Operator associativity................................................................................................................... 14 Control Instructions...................................................................................................................... 15 Chapter 2 – Practice Set.................................................................................................................... 16 Chapter 3: Conditional Instructions................................................................................................... 17 2 Decision making instructions in c................................................................................................... 17 if-else statement........................................................................................................................... 17 Code example:............................................................................................................................. 17 Relational operators in c................................................................................................................ 18 Logical operators.......................................................................................................................... 18 Usage of logical operators:............................................................................................................ 18 else if clause................................................................................................................................ 18 Operator precedence.................................................................................................................... 19 Conditional operators................................................................................................................... 19 Switch case control instruction...................................................................................................... 20 Chapter 3 – Practice Set.................................................................................................................... 21 Chapter 4: Loop control instruction................................................................................................... 22 Why loops.................................................................................................................................... 22 Types of loops............................................................................................................................... 22 while loop..................................................................................................................................... 22 Increment and decrement operators.............................................................................................. 23 do–while loop............................................................................................................................... 23 for loop......................................................................................................................................... 23 A case of decrementing for loop..................................................................................................... 24 The break statement in c............................................................................................................... 24 The continue statement in c........................................................................................................... 25 Chapter 4 – Practice Set.................................................................................................................... 26 Project 1: Number guessing game..................................................................................................... 27 Chapter 5 – Functions and Recursion................................................................................................ 28 What is a function?....................................................................................................................... 28 Function prototype........................................................................................................................ 28 Function call................................................................................................................................. 28 Function definition........................................................................................................................ 29 Important points........................................................................................................................... 29 Types of functions......................................................................................................................... 29 Why use functions........................................................................................................................ 29 Passing values to function............................................................................................................. 29 Note:............................................................................................................................................ 30 Recursion..................................................................................................................................... 31 Important notes:........................................................................................................................... 32 Chapter 5 – Practice set.................................................................................................................... 33 Chapter 6- Pointers.......................................................................................................................... 34 3 The “address of” (&) operator........................................................................................................ 34 The ‘value at address’ operator (*).................................................................................................. 34 How to declare a pointer?.............................................................................................................. 34 A program to demonstrate pointers................................................................................................ 35 Output:........................................................................................................................................ 35 Pointer to a pointer........................................................................................................................ 35 Types of function call.................................................................................................................... 36 Call by value................................................................................................................................. 36 Call by reference........................................................................................................................... 36 Chapter 6 – Practice set.................................................................................................................... 38 Chapter 7 – Arrays............................................................................................................................ 39 Accessing elements...................................................................................................................... 39 Initialization of an array................................................................................................................. 39 Arrays in memory.......................................................................................................................... 40 Pointer arithmetic......................................................................................................................... 40 Accessing array using pointers....................................................................................................... 41 Passing array to functions............................................................................................................. 41 Multidimensional arrays................................................................................................................ 41 2-D arrays in memory.................................................................................................................... 41 Chapter 7 – Practice Set.................................................................................................................... 43 Chapter 8 – Strings........................................................................................................................... 44 Initializing strings.......................................................................................................................... 44 Strings in memoryd....................................................................................................................... 44 Printing strings.............................................................................................................................. 44 Taking string input from the user.................................................................................................... 44 gets() and puts()............................................................................................................................ 45 Declaring a string using pointers.................................................................................................... 45 Standard library functions for strings.............................................................................................. 45 strlen()......................................................................................................................................... 45 strcpy()......................................................................................................................................... 46 strcat()......................................................................................................................................... 46 strcmp()....................................................................................................................................... 46 Chapter 8 – Practice Set.................................................................................................................... 47 Chapter 9 – Structures...................................................................................................................... 48 Why use Structures?..................................................................................................................... 48 Array of structures........................................................................................................................ 48 Initializing structures..................................................................................................................... 49 4 Structures in memory.................................................................................................................... 49 Pointer to structures..................................................................................................................... 49 Arrow operator.............................................................................................................................. 49 Passing structure to a function...................................................................................................... 49 typedef keyword........................................................................................................................... 50 Chapter 9 – Practice set.................................................................................................................... 51 Chapter 10 – File I/O......................................................................................................................... 52 File pointer................................................................................................................................... 52 File opening modes in C................................................................................................................ 52 Types of files................................................................................................................................. 53 Reading a file................................................................................................................................ 53 Closing the file.............................................................................................................................. 53 Write to a file................................................................................................................................ 53 fgetc() and fputc()......................................................................................................................... 54 EOF : end of file............................................................................................................................. 54 Chapter 10 – Practice Set.................................................................................................................. 55 Project 2: Snake, Water, Gun............................................................................................................. 56 Chapter 11 – Dynamic Memory Allocation.......................................................................................... 57 Cynamic memory allocation.......................................................................................................... 57 Function for Dma in C.................................................................................................................... 57 malloc() function.......................................................................................................................... 57 calloc() function............................................................................................................................ 57 free() function............................................................................................................................... 58 realloc() function.......................................................................................................................... 58 Chapter 11 – Practice set.................................................................................................................. 59 \\ 5 C PROGRAMMING HANDBOOK BY CODEWITHHARRY WHAT IS PROGRAMMING? Computer programming is a medium for us to communicate with computers. Just like we use ‘Hindi’ or ‘English’ to communicate with each other, programming is a way for us to deliver our instructions to the computer. WHAT IS C? C is a programming language. C is one of the oldest and finest programming languages. C was developed by Dennis Ritchie at AT&T’s Bell labs, USA in 1972. USES OF C C language is used to program a wide variety of systems. Some of the uses of C are as follows: 1. Major parts of Windows, Linux and other operating systems are written in C. 2. C is used to write driver programs for devices like tablets, printers etc. 3. C language is used to program embedded systems where programs need to run faster in limited memory (Microwave, Cameras etc.) 4. C is used to develop games, an area where latency is very important, i.e., the computer must react quickly to user input. INSTALLATION We will use VS Code as our code editor to write our code and install MinGW gcc compiler to compile our C program. Compilation is the process of translating high-level source code written in programming languages like C into machine code, which is the low-level code that a computer's CPU can execute directly. Machine code consists of binary instructions specific to a computer's architecture. We can install VS Code and MinGW from their respective websites Just install it like a game! 6 CHAPTER 1: VARIABLES, CONSTANTS & KEYWORDS VARIABLES A variable is a container which stores a ‘value’. In kitchen, we have containers storing Rice, Dal, Sugar etc. Similar to that, variables in C stores value of a constant. Example: a = 3; // a is assigned "3" b = 4.7; // b is assigned "4.7" c = 'A'; // c is assigned 'A' RULES FOR NAMING VARIABLES IN C 1. First character must be an alphabet or underscore (_) 2. No commas, blanks are allowed. 3. No special symbol other than (_) allowed. 4. Variable names are case sensitive. We must create meaningful variable names in our programs. This enhances readability of our programs. CONSTANTS An entity whose value does not change is called as a constant. A variable is an entity whose value can be changed. TYPES OF CONSTANTS Primarily, there are three types of constants: 1. Integer Constant → 1,6,7,9 2. Real Constant → 322.1, 2.5 ,7.0 3. Character Constant → ‘a’, ‘$’, ‘@’ (must be enclosed within single quotes) 7 KEYWORDS These are reserved words, whose meaning is already known to the compiler. There are 32 keywords available in C. auto double int struct break long else switch case return enum typedef char register extern union const short float unsigned continue signed for void default sizeof goto volatile do static if while OUR FIRST C PROGRAM #include int main() { printf("Hello, I am learning C with Harry"); return 0; } 8 BASIC STRUCTURE OF A C PROGRAM All C programs must follow a basic structure. A C program starts with a main function and executes instructions present inside it. Each instruction is terminated with a semicolon (;). There are some rules which are applicable to all the C programs: 1. Every program’s execution starts from main() function. 2. All the statements are terminated with a semicolon. 3. Instructions are case–sensitive. 4. Instructions are executed in the same order in which they are written. 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: Single-line comments start with two forward slashes (//). Any information after the slashes // lying on the same line would be ignored (will not be executed). // This is a Single line comment. 2. Multi-line Comment: A multi-line comment starts with. Any information between will be ignored by the compiler. Note: Comments in a C program are not executed and are ignored. COMPILATION AND EXECUTION 9 A compiler is a computer program which converts a C program into machine language so that it can be easily understood by the computer. A C program is written in plain text. This plain text is combination of instructions in a particular sequence. The compiler performs some basic checks and finally converts the program into an executable. LIBRARY FUNCTIONS 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. #include int main() { int i = 10; printf("This is %d\n", i); // %d for integers // %f for real values (floating-point numbers) // %c for characters return 0; } TYPES OF VARIABLES 1. Integer variables → int a=3; 2. Real variables → int a=7; float a=7.7; 3. Character variables → char a= ‘b’; RECEIVING INPUT FROM THE USER In order to take input from the user and assign it to a variable, we use scanf() function Syntax: scanf("%d", &i); ‘&’ is the “address of” operator and it means that the supplied value should be copied to the address which is indicated by variable i. 10 CHAPTER 1- PRACTICE SET 1. Write a C program to calculate area of a rectangle: a. Using hard coded inputs. b. Using inputs supplied by the user. 2. Calculate the area of a circle and modify the same program to calculate the volume of a cylinder given its radius and height. 3. Write a program to convert Celsius (Centigrade degrees temperature to Fahrenheit). 4. Write a program to calculate simple interest for a set of values representing principal, number of years and rate of interest. 11 CHAPTER 2: INSTRUCTIONS AND OPERATORS A C program is a set of instructions. Just like a recipe - which contains instructions to prepare a particular dish. TYPES OF INSTRUCTIONS 1. Type declaration Instructions. 2. Arithmetic Instructions 3. Control Instructions. TYPE DECLARATION INSTRUCTIONS This is how you declare a variable in C int a; float b; char c; OTHER VARIATIONS: Some other variations of this declaration look like this: int a; // Declare an integer variable 'a' float b; // Declare a float variable 'b' int i = 10; // Declare and initialize 'i' with 10 int j = i; // Declare 'j' and initialize with 'i' int a = 2, b = 3, c = 4, d = 5; // Declare and initialize multiple variables int j1 = a + j - i; // Valid: use previously defined variables // Invalid: 'a' is used before declaration // float b = a + 3; // float a = 1.1; // Valid: Assigning the same value to multiple variables int a, b, c, d; a = b = c = d = 30; // a, b, c, d all equal to 30 ARITHMETIC INSTRUCTIONS Arithmetic instructions perform mathematical operations. Here are some of the commonly used operators in C language: 12 + (Addition) - (Subtraction) * (Multiplication) / (Division) % (Modulus) Note: 1. Operands can be int/float etc. + - * / are arithmetic operators. int b = 2, c = 3; int z; z = b*c; //legal int z; b*c = z; //illegal (not allowed) 2. % is the modular division operator o % → returns the remainder o % → cannot be applied on float o % → sign is same as of numerator (-5%2=-1) 3. No operator is assumed to pe present. int i = ab // invalid int i = a * b //valid 4. There is no operator to perform exponentiation in C however we can use pow (x,y) from (more later). TYPE CONVERSION An Arithmetic operation between int and int → int int and float → float float and float → float Example: o 5/2 becomes 2 as both the operands are int 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: In programming, type compatibility is crucial. For int a = 3.5;, the float 3.5 is 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 precision. 13 int a = 3.5; // In this case 3.5 (float) will be demoted to 3 (int) because a is not able to store floats. float a = 8; // a will store 8.0 | 8 -> 8.0 (promotion to float) Quick Quiz: int k = 3.0 /9; value of k? and why? Ans: 3.0/9 = 0.333. But since k is an int, it cannot store floats & value 0.33 is demoted to 0. OPERATOR PRECEDENCE IN C Have a look at the below statement: 3*x – 8*y is (3x)-(8y) or 3(x-8y)? In C language simple mathematical rules like BODMAS, no longer apply. The answer to the above questions is provided by operator precedence & associativity. OPERATOR PRECEDENCE The following table lists the operator priority in C Priority Operators 1st */% 2nd +- 3rd = Operators of higher priority are evaluated first in the absence of parenthesis. OPERATOR ASSOCIATIVITY When operators of equal priority are present in an expression, the tie is taken care of by associativity. 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 14 CONTROL INSTRUCTIONS Determines the flow of control in a program four types of control instructions in C are: 1. Sequence Control instructions. 2. Decision Control instructions 3. Loop Control instructions 4. Case Control instructions. 15 CHAPTER 2 – PRACTICE SET 1. Which of the following is invalid in C? a. int a=1; int b = a; b. int v = 3*3; c. char dt = ‘21 dec 2020’; 2. What data type will 3.0/8 – 2 return? 3. Write a program to check whether a number is divisible by 97 or not. 4. Explain step by step evaluation of 3*x/y – z+k, where x=2, y=3, z=3, k=1 5. 3.0 + 1 will be: a. Integer. b. Floating point number. c. Character. 16 CHAPTER 3: CONDITIONAL INSTRUCTIONS Sometimes we want to watch comedy videos on YouTube if the day is Sunday. Sometimes we order junk food if it is our friend’s birthday in the hostel. You might want to buy an umbrella if it’s raining, and you have the money. You order the meal if dal or your favourite bhindi is listed on the menu. All these are decisions which depends on a condition being met. In C language too, we must be able to execute instructions on a condition(s) being met. DECISION MAKING INSTRUCTIONS IN C if–else statement switch statement IF-ELSE STATEMENT The syntax of an if-else statement in C looks like: if (condition_to_be_checked) { // Statements if condition is true } else { // Statements if condition is false } CODE EXAMPLE: int a = 23; if (a > 18) { printf("you can drive \n"); } Note that else block is not necessary but optional. 17 RELATIONAL OPERATORS IN C Relational operators are used to evaluate conditions (true or false) inside the if statements. Some examples of relational operators are: ==, >=, >, Constants // code; // code -> Any valid C code. case c3: // code: default: // code; } 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 executed. Quick Quiz: Write a program to find grade of a student given his marks based on below: 90 – 100 => A 80 – 90 => B 70 – 80 => C 60 – 70 => D 50 – 60 => E F Some Important Notes: We can use switch-case statements even by writing cases in any order of our 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. 20 CHAPTER 3 – PRACTICE SET 1. What will be the output of this program int a = 10; if (a = 11) printf("I am 11"); else printf("I am not 11"); 2. Write a program to determine whether a student has passed or failed. To pass, a student requires a total of 40% and at least 33% in each subject. Assume there are three subjects and take the marks as input from the user. 3. Calculate income tax paid by an employee to the government as per the slabs mentioned below: Income Slab Tax 2.5 – 5.0L 5% 5.0L - 10.0L 20% Above 10.0L 30% Note that there is no tax below 2.5L. Take income amount as an input from the user. 4. Write a program to find whether a year entered by the user is a leap year or not. Take year as an input from the user. 5. Write a program to determine whether a character entered by the user is lowercase or not. 6. Write a program to find greatest of four numbers entered by the user. 21 CHAPTER 4: LOOP CONTROL INSTRUCTION WHY LOOPS Sometimes we want our programs to execute few sets of instructions over and over again. For example: Printing 1 to100, first 100 even numbers etc. Hence loops make it easy for a programmer to tell computer that a given set of instructions must be executed repeatedly. TYPES OF LOOPS Primarily there are three types of loops in C language: 1. while loop 2. do–while loop 3. for loop We will look into these one by one: WHILE LOOP while (condition is true) { // Code // The block keeps executing as long as the condition is true } Example: int i = 0; while (icode // here -> is known as the arrow operator. PASSING STRUCTURE TO A FUNCTION A structure can be passed to a function just like any other data type. void show(struct employee e); // function prototype 49 Quick Quiz: Complete this show function to display the content of employee. TYPEDEF KEYWORD We can use the ‘typedef’ keyword to create an alias name for data types in C. ‘typedef’ is more commonly used with structures. struct Complex { float real; float img; // struct complex c1,c2, for defining complex numbers }; typedef struct Complex { float real; float img; // ComplexNo c1,c2,for defining complex numbers } ComplexNo; EXAMPLE USAGE Using the typedef alias, you can declare complex number variables more succinctly: ComplexNo c1, c2; 50 CHAPTER 9 – PRACTICE SET 1. Create a two-dimensional vector using structures in C. 2. Write a function ‘sumVector’ which returns the sum of two vectors passed to it. The vectors must be two–dimensional. 3. Twenty integers are to be stored in memory. What will you prefer- Array or structure? 4. Write a program to illustrate the use of arrow operator → in C. 5. Write a program with a structure representing a complex number. 6. Create an array of 5 complex numbers created in Problem 5 and display them with the help of a display function. The values must be taken as an input from the user. 7. Write problem 5’s structure using ‘typedef’ keywords. 8. Create a structure representing a bank account of a customer. What fields did you use and why? 9. Write a structure capable of storing date. Write a function to compare those dates. 10. Solve problem 9 for time using ‘typedef’ keyword. 51 CHAPTER 10 – FILE I/O The random-access memory is volatile, and its content is lost once the program terminates. In order to persist the data forever we use files. A file is data stored in a storage device. A C program can talk to the file by reading content from it and writing content to it. FILE POINTER A “FILE” is a structure which needs to be created for opening the file. A file pointer is a pointer to this structure of the file. (FILE pointer is needed for communication between the file and the program). A FILE pointer can be created as follows: FILE *ptr; ptr = fopen("filename.ext"; "mode"); FILE OPENING MODES IN C C offers the programmers to select a mode for opening a file. Following modes are primarily used in C File I/O. "r" -> open for reading "rb" -> open for reading in binary "w" -> open for writing // If the file exists, the contents will be overwritten "wb" -> open for writing in binary "a" -> open for append // If the file does not exist, it will be created 52 TYPES OF FILES Primarily, there are two types of files: 1. Text files (.txt,.c) 2. Binary files (.jpg,.dat) READING A FILE A file can be opened for reading as follows: FILE *ptr; ptr = fopen("harry.txt", "r"); int num; Let us assume that "harry.txt" contains an integer we can read that integer using: fscanf(ptr, "%d", &num); // fscanf is file counterpart of scanf This will read an integer from file in Num variables. Quick Quiz: Modify the program above to check whether the file exists or not before opening the file. CLOSING THE FILE It is very important to close the file after read or write. This is achieved using fclose as follows: fclose(ptr); This will tell the compiler that we are done working with this file and the associated resources could be freed. WRITE TO A FILE We can write to a file in a very similar manner like we read the file FILE *fptr; fptr = fopen("harry.txt", "w"); int num = 432; fprintf(fptr, "%d", num); fclose(fptr); 53 FGETC() AND FPUTC() fgetc and fputc are used to read and write a character from / to a file. fgetc(ptr); // used to read a character from file fputc('c', ptr); // used to write character 'c' to the file EOF : END OF FILE fgetc returns EOF when all the characters from a file have been read. So, we can write a check like below to detect end of file: while(1) { ch = fgetc(ptr); // when all the content of a file has been read break the loop! if (ch == EOF) { break; } // code } 54 CHAPTER 10 – PRACTICE SET 1. Write a program to read three integers from a file. 2. Write a program to generate multiplication table of a given number in text format. Make sure that the file is readable and well formatted. 3. Write a program to read a text file character by character and write its content twice in separate file. 4. Take name and salary of two employees as input from the user and write them to a text file in the following format: i. Name1, 3300 ii. Name2, 7700 5. Write a program to modify a file containing an integer to double its value. 55 PROJECT 2: SNAKE, WATER, GUN Snake, water, gun or rock, paper, scissors is a game most of us have played during school time. (I sometimes play it even now). Write a C program capable of playing this game with you. Your program should be able to print the result after you choose snake/water or gun. 56 CHAPTER 11 – DYNAMIC MEMORY ALLOCATION C is a language with some fixed rules of programming. For example: Changing the size of an array is not allowed. DYNAMIC MEMORY ALLOCATION 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. 57 FREE() FUNCTION We can use free() function to deallocate the memory. The memory allocated using calloc/malloc is not deallocated automatically. Syntax: free(ptr); //memory of ptr is released. Quick Quiz: Write a program to demonstrate the usage of free() with malloc(). REALLOC() FUNCTION 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 CHAPTER 11 – PRACTICE SET 1. Write a program to dynamically create an array of size 6 capable of storing 6 integers. 2. Use the array in problem 1 to store 6 integers entered by the user. 3. Solve problem 1 using calloc(). 4. Create an array dynamically capable of storing 5 integers. Now use realloc so 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 make it store 15 number (from 7 x 1 to 7 x 15). 6. Attempt problem 4 using calloc(). 59

Use Quizgecko on...
Browser
Browser