C – Loops

C – Loops ”; Previous Next Loops are a programming construct that denote a block of one or more statements that are repeatedly executed a specified number of times, or till a certain condition is reached. Repetitive tasks are common in programming, and loops are essential to save time and minimize errors. In C programming, the keywords while, do–while and for are provided to implement loops. Looping constructs are an important part of any processing logic, as they help in performing the same process again and again. A C programmer should be well acquainted with implementing and controlling the looping construct. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Flowchart of C Loop Statement Given below is the general flowchart of a loop statement which is applicable to any programming language − The statements in a C program are always executed in a top-to-bottom manner. If we ask the compiler to go back to any of the earlier steps, it constitutes a loop. Example: Loops in C To understand the need of loops in a program, consider the following snippet − #include <stdio.h> int main (){ // local variable definition int a = 1; printf(“a: %dn”, a); a++; printf(“a: %dn”, a); a++; printf(“a: %dn”, a); a++; printf(“a: %dn”, a); a++; printf(“a: %dn”, a); return 0; } Output On running this code, you will get the following output − a: 1 a: 2 a: 3 a: 4 a: 5 The program prints the value of “a”, and increments its value. These two steps are repeated a number of times. If you need to print the value of “a” from 1 to 100, it is not desirable to manually repeat these steps in the code. Instead, we can ask the compiler to repeatedly execute these two steps of printing and incrementing till it reaches 100. Example: Using While Loop in C You can use for, while or do-while constructs to repeat a loop. The following program shows how you can print 100 values of “a” using the “while” loop in C − #include <stdio.h> int main () { // local variable definition int a = 1; while (a <= 100){ printf(“a: %dn”, a); a++; } return 0; } Output Run this code and check the output − a: 1 a: 2 a: 3 a: 4 ….. ….. a: 98 a: 99 a: 100 If a step redirects the program flow to any of the earlier steps, based on any condition, the loop is a conditional loop. The repetitions will stop as soon as the controlling condition turns false. If the redirection is done without any condition, it is an infinite loop, as the code block repeats forever. Parts of C Loops To constitute a loop, the following elements are necessary − Looping statement (while, do–while or for) Looping block Looping condition Loops are generally of two types − Counted Loops in C If the loop is designed to repeat for a certain number of times, it is a counted loop. In C, the for loop is an example of counted loop. Conditional Loops in C If the loop is designed to repeat till a condition is true, it is a conditional loop. The while and do–while constructs help you to form conditional loops. Looping Statements in C C programming provides the following types of loops to handle looping requirements − Sr.No. Loop Type & Description 1 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 3 do-while loop It is more like a while statement, except that it tests the condition at the end of the loop body. 4 nested loops You can use one or more loops inside any other while, for or do-while loop. Each of the above loop types have to be employed depending upon which one is right for the given situation. We shall learn about these loop types in detail in the subsequent chapters. Loop Control Statements in C Loop control statements change the execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. C supports the following control statements − Sr.No. Control Statement & Description 1 break statement Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. 2 continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 3 goto statement Transfers the control to the labeled statement. The break and continue statements have contrasting purposes. The goto statement acts as a jump statement if it causes the program to go to a later statement. If the goto statement redirects the program to an earlier statement, then it forms a loop. The Infinite Loop in C A loop becomes an infinite loop if a condition never becomes false. An infinite loop is a loop that repeats indefinitely because it has no terminating condition, or the termination condition is never met or the loop is instructed to start

C – Array of Strings

Array of Strings in C ”; Previous Next In C programming language, a string is an array of character sequences terminated by NULL, it is a one-dimensional array of characters. And, the array of strings is an array of strings (character array). What is an Array of Strings in C? Thus, an array of strings can be defined as – An array of strings is a two-dimensional array of character-type arrays where each character array (string) is null-terminated. To declare a string, we use the statement − char string[] = {”H”, ”e”, ”l”, ”l”, ”o”, ””}; Or char string = “Hello”; Declare and Initialize an Array of Strings To declare an array of strings, you need to declare a two-dimensional array of character types, where the first subscript is the total number of strings and the second subscript is the maximum size of each string. To initialize an array of strings, you need to provide the multiple strings inside the double quotes separated by the commas. Syntax To construct an array of strings, the following syntax is used − char strings [no_of_strings] [max_size_of_each_string]; Example Let us declare and initialize an array of strings to store the names of 10 computer languages, each with the maximum length of 15 characters. char langs [10][15] = { “PYTHON”, “JAVASCRIPT”, “PHP”, “NODE JS”, “HTML”, “KOTLIN”, “C++”, “REACT JS”, “RUST”, “VBSCRIPT” }; Printing An Array of Strings A string can be printed using the printf() function with %s format specifier. To print each string of an array of strings, you can use the for loop till the number of strings. Example In the following example, we are declaring, initializing, and printing an array of string − #include <stdio.h> int main (){ char langs [10][15] = { “PYTHON”, “JAVASCRIPT”, “PHP”, “NODE JS”, “HTML”, “KOTLIN”, “C++”, “REACT JS”, “RUST”, “VBSCRIPT” }; for (int i = 0; i < 10; i++){ printf(“%sn”, langs[i]); } return 0; } Output When you run this code, it will produce the following output − PYTHON JAVASCRIPT PHP NODE JS HTML KOTLIN C++ REACT JS RUST VBSCRIPT Note: The size of each string is not equal to the row size in the declaration of the array. The “” symbol signals the termination of the string and the remaining cells in the row are empty. Thus, a substantial part of the memory allocated to the array is unused and thus wasted. How an Array of Strings is Stored in Memory? We know that each char type occupies 1 byte in the memory. Hence, this array will be allocated a block of 150 bytes. Although this block is contagious memory locations, each group of 15 bytes constitutes a row. Assuming that the array is located at the memory address 1000, the logical layout of this array can be shown as in the following figure − An Array of Strings with Pointers To use the memory more efficiently, we can use the pointers. Instead of a 2D char array, we declare a 1D array of “char *” type. char *langs[10] = { “PYTHON”, “JAVASCRIPT”, “PHP”, “NODE JS”, “HTML”, “KOTLIN”, “C++”, “REACT JS”, “RUST”, “VBSCRIPT” }; In the 2D array of characters, the strings occupied 150 bytes. As against this, in an array of pointers, the strings occupy far less number of bytes, as each string is randomly allocated memory as shown below − Note: Here, lang[ ] is an array of pointers of individual strings. Example We can use a for loop as follows to print the array of strings − #include <stdio.h> int main(){ char *langs[10] = { “PYTHON”, “JAVASCRIPT”, “PHP”, “NODE JS”, “HTML”, “KOTLIN”, “C++”, “REACT JS”, “RUST”, “VBSCRIPT” }; for (int i = 0; i < 10; i++) printf(“%sn”, langs[i]); return 0; } Output When you run this code, it will produce the following output − PYTHON JAVASCRIPT PHP NODE JS HTML KOTLIN C++ REACT JS RUST VBSCRIPT Here, langs is a pointer to an array of 10 strings. Therefore, if langs[0] points to the address 5000, then “langs + 1” will point to the address 5004 which stores the pointer to the second string. Hence, we can also use the following variation of the loop to print the array of strings − for(int i = 0; i < 10; i++){ printf(“%sn”, *(langs + i)); } When strings are stored in array, there are a lot use cases. Let study some of the use cases. Find the String with the Largest Length In the following example, we store the length of first string and its position (which is “0”) in the variables “l” and “p” respectively. Inside the for loop, we update these variables whenever a string of larger length is found. Example Take a look at the following example − #include <stdio.h> #include <string.h> int main (){ char langs [10][15] = { “PYTHON”, “JAVASCRIPT”, “PHP”, “NODE JS”, “HTML”, “KOTLIN”, “C++”, “REACT JS”, “RUST”, “VBSCRIPT” }; int l = strlen(langs[0]); int p = 0; for (int i = 0; i < 10; i++){ if (strlen(langs[i]) >= l){ l = strlen(langs[i]); p = i; } } printf(“Language with the longest name: %s Length: %d”, langs[p], l); return 0; } Output When you run this code, it will produce the following output − Language with longest name: JAVASCRIPT Length: 10 Sort a String Array in Ascending Order We need to use the strcmp() function to compare two strings. If the value of comparison of strings is greater than 0, it means the first argument string appears

C – Near, Far and Huge Pointers

Near, Far, and Huge Pointers in C ”; Previous Next Concepts like near pointers, far pointers, and huge pointers were used in the C programming language to handle segmented memory models. However, these concepts are no longer relevant in modern computing environments with improved CPU architecture. The idea of near, far, and huge pointers was implemented in 16-bit Intel architectures, in the days of the MS DOS operating system. Near Pointer The “near” keyword in C is used to declare a pointer that can only access memory within the current data segment. A near pointer on a 16-bit machine is a pointer that can store only 16-bit addresses. A near pointer can only access data of a small size of about 64 kb in a given period, which is its main disadvantage. The size of a near pointer is 2 bytes. Syntax of Near Pointer <data type> near <pointer definition> <data type> near <function definition> The following statement declares a near pointer for the variable “ptr” − char near *ptr; Example of Near Pointer Take a look at the following example − #include <stdio.h> int main(){ // declaring a near pointer int near *ptr; // size of the near pointer printf(“Size of Near Pointer: %d bytes”, sizeof(ptr)); return 0; } Output It will produce the following output − Size of Near Pointer: 2 bytes Far Pointer A far pointer is a 32-bit pointer that can access information that is outside the computer memory in a given segment. To use this pointer, one must allocate the “sector register” to store data addresses in the segment and also another sector register must be stored within the most recent sector. A far pointer stores both the offset and segment addresses to which the pointer is differencing. When the pointer is incremented or decremented, only the offset part is changing. The size of the far pointer is 4 bytes. Syntax of Far Pointer <data type> far <pointer definition> <data type> far <function definition> The following statements declares a far pointer for the variable “ptr” − char far *s; Example of Far Pointer Take a look at the following example − #include <stdio.h> int main(){ int number=50; int far *p; p = &number; printf(“Size of far pointer: %d bytes”, sizeof(number)); return 0; } Output It will produce the following output − Size of far pointer: 4 bytes Huge Pointer A huge pointer has the same size of 32-bit as that of a far pointer. A huge pointer can also access bits that are located outside the sector. A far pointer is fixed and hence that part of the sector in which they are located cannot be modified in any way; however huge pointers can be modified. In a huge pointer, both the offset and segment address is changed. That is why we can jump from one segment to another using a huge pointer. As they compare the absolute addresses, you can perform the relational operation on it. The size of a huge pointer is 4 bytes. Syntax of Huge Pointer Below is the syntax to declare a huge pointer − data_type huge* pointer_name; Example of Huge Pointer Take a look at the following example − #include <stdio.h> int main(){ int huge* ptr; printf(“Size of the Huge Pointer: %d bytes”, sizeof(ptr)); return 0; } Output It will produce the following output − Size of Huge Pointer: 4 bytes Pointers to Remember Remember the following points while working with near, far, and huge pointers − A near pointer can only store till the first 64kB addresses, while a far pointer can store the address of any memory location in the RAM. A huge pointer can move between multiple memory segments. A near pointer can only store addresses in a single register. On the other hand, a far pointer uses two registers to store segment and offset addresses. The size of a near pointer is 2 bytes, while the size of far and huge pointers is 4 bytes. Two far pointer values can point to the same location, while in the case of huge pointers, it is not possible. The near, far, and huge pointers were used to manage memory access based on segment registers in segmented memory architectures. Modern systems use flat memory models where memory is addressed as a single contiguous space. Modern C compilers provide better memory management techniques that don”t rely on segmentation concepts. Print Page Previous Next Advertisements ”;

C – Nested loop

Nested Loops in C ”; Previous Next In the programming context, the term “nesting” refers to enclosing a particular programming element inside another similar element. For example, nested loops, nested structures, nested conditional statements, etc. Nested Loops When a looping construct in C is employed inside the body of another loop, we call it a nested loop (or, loops within a loop). Where, the loop that encloses the other loop is called the outer loop. The one that is enclosed is called the inner loop. General Syntax of Nested Loops The general form of a nested loop is as follows − Outer loop { Inner loop { … … } … } C provides three keywords for loops formation − while, do-while, and for. Nesting can be done on any of these three types of loops. That means you can put a while loop inside a for loop, a for loop inside a do-while loop, or any other combination. The general behaviour of nested loops is that, for each iteration of the outer loop, the inner loop completes all the iterations. Nested For Loops Nested for loops are very common. If both the outer and inner loops are expected to perform three iterations each, the total number of iterations of the innermost statement will be “3 * 3 = 9”. Example: Nested for Loop Take a look at the following example − #include <stdio.h> int main(){ int i, j; // outer loop for(i = 1; i <= 3; i++){ // inner loop for(j = 1; j <= 3; j++){ printf(“i: %d j: %dn”, i, j); } printf(“End of Inner Loop n”); } printf(“End of Outer Loop”); return 0; } Output When you run this code, it will produce the following output − i: 1 j: 1 i: 1 j: 2 i: 1 j: 3 End of Inner Loop i: 2 j: 1 i: 2 j: 2 i: 2 j: 3 End of Inner Loop i: 3 j: 1 i: 3 j: 2 i: 3 j: 3 End of Inner Loop End of Outer loop Explanation of Nested Loop Now let”s analyze how the above program works. As the outer loop is encountered, “i” which is the looping variable for the outer loop is initialized to 1. Since the test condition (a <= 3) is true, the program enters the outer loop body. The program reaches the inner loop, and “j” which is the variable that controls the inner loop is initialized to 1. Since the test condition of the inner loop (j <= 3) is true, the program enters the inner loop. The values of “a” and “b” are printed. The program reaches the end of the inner loop. Its variable “j” is incremented. The control jumps to step 4 until the condition (j <= 3) is true. As the test condition becomes false (because “j” becomes 4), the control comes out of the inner loop. The end of the outer loop is encountered. The variable “i” that controls the outer variable is incremented and the control jumps to step 3. Since it is the start of the inner loop, “j” is again set to 1. The inner loop completes its iteration and ends again. Steps 4 to 8 will be repeated until the test condition of the outer loop (i <= 3) becomes false. At the end of the outer loop, “i” and “j” have become 4 and 4 respectively. The result shows that, for each value of the outer looping variable, the inner looping variable takes all the values. The total lines printed are “3 * 3 = 9”. Nesting a While Loop Inside a For Loop Any type of loop can be nested inside any other type. Let us rewrite the above example by putting a while loop inside the outer for loop. Example: Nested Loops (while Loop Inside for Loop) Take a look at the following example − #include <stdio.h> int main(){ int i, j; // outer for loop for (i = 1; i <= 3; i++){ // inner while loop j = 1; while (j <= 3){ printf(“i: %d j: %dn”, i, j); j++; } printf(“End of Inner While Loop n”); } printf(“End of Outer For loop”); return 0; } Output i: 1 j: 1 i: 1 j: 2 i: 1 j: 3 End of Inner While Loop i: 2 j: 1 i: 2 j: 2 i: 2 j: 3 End of Inner While Loop i: 3 j: 1 i: 3 j: 2 i: 3 j: 3 End of inner while Loop End of outer for loop Programmers use nested loops in a lot of applications. Let us take a look at some more examples of nested loops. C Nested Loops Examples Example: Printing Tables The following program prints the tables of 1 to 10 with the help of two nested for loops. #include <stdio.h> int main(){ int i, j; printf(“Program to Print the Tables of 1 to 10 n”); // outer loop for(i = 1; i <= 10; i++){ // inner loop for(j = 1; j <= 10; j++){ printf(“%4d”, i*j); } printf(“n”); } return 0; } Output Run the code and check its output − Program to Print the Tables of 1 to 10 1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30 4 8 12 16 20 24 28 32 36 40 5 10 15 20 25 30 35 40 45 50 6 12 18 24 30 36

C – Pointer Arithmetics

Pointer Arithmetics in C ”; Previous Next A pointer variable in C stores the address of another variable. The address is always an integer. So, can we perform arithmetic operations such as addition and subtraction on the pointers? In this chapter, we will explain which arithmetic operators use pointers in C as operands, and which operations are not defined to be performed with pointers. C pointers arithmetic operations are different from the general arithmetic operations. The following are some of the important pointer arithmetic operations in C: Increment and Decrement of a Pointer Addition and Subtraction of Integer to Pointer Subtraction of Pointers Comparison of Pointers Let us discuss all these pointer arithmetic operations in detail with the help of examples. Increment and Decrement of a Pointer We know that “++” and “–” are used as the increment and decrement operators in C. They are unary operators, used in prefix or postfix manner with numeric variable operands, and they increment or decrement the value of the variable by one. Assume that an integer variable “x” is created at address 1000 in the memory, with 10 as its value. Then, “x++” makes the value of “x” as 11. int x = 10; // created at address 1000 x++; // x becomes 11 What happens if we declare “y” as pointer to “x” and increment “y” by 1 (with “y++”)? Assume that the address of “y” itself is 2000. int x = 10; // created at address 1000 // “y” is created at address 2000 // it holds 1000 (address of “x”) int *y = &x ; y++; // y becomes 1004 Since the variable “y” stores 1000 (the address of “x”), we expect it to become 1001 because of the “++” operator, but it increments by 4, which is the size of “int” variable. The is why because, if the address of “x” is 1000, then it occupies 4 bytes: 1000, 1001, 1002 and 1003. Hence, the next integer can be put only in 1004 and not before it. Hence “y” (the pointer to “x”) becomes 1004 when incremented. Example of Incrementing a Pointer The following example shows how you can increment a pointer − #include <stdio.h> int main(){ int x = 10; int *y = &x; printf(“Value of y before increment: %dn”, y); y++; printf(“Value of y after increment: %d”, y); } Output Run the code and check its output − Value of y before increment: 6422036 Value of y after increment: 6422040 You can see that the value has increased by 4. Similarly, the “–” operator decrements the value by the size of the data type. Example of Decrementing a Pointer Let us change the types of “x” and “y” to “double” and “float” and see the effect of decrement operator. #include <stdio.h> int main(){ double x = 10; double *y = &x; printf(“value of y before decrement: %ldn”, y); y–; printf(“value of y after decrement: %ld”, y); } Output Value of y before decrement: 6422032 Value of y after decrement: 6422024 When an array is declared, the elements are stored in adjacent memory locations. In case of “int” array, each array subscript is placed apart by 4 bytes, as the following figure shows − Hence, if a variable stores the address of 0th element of the array, then the “increment” takes it to the 1st element. Example of Traversing an Array by Incrementing Pointer The following example shows how you can traverse an array by incrementing a pointer successively − #include <stdio.h> int main(){ int a[]= {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; int len = sizeof(a)/sizeof(int); int *x = a; int i = 0; for(i = 0; i < len; i++){ printf(“Address of subscript %d = %d Value = %dn”, i, x, *x); x++; } return 0; } Output Run the code and check its output − Address of subscript 0 = 6421984 Value = 10 Address of subscript 1 = 6421988 Value = 20 Address of subscript 2 = 6421992 Value = 30 Address of subscript 3 = 6421996 Value = 40 Address of subscript 4 = 6422000 Value = 50 Address of subscript 5 = 6422004 Value = 60 Address of subscript 6 = 6422008 Value = 70 Address of subscript 7 = 6422012 Value = 80 Address of subscript 8 = 6422016 Value = 90 Address of subscript 9 = 6422020 Value = 100 Addition and Subtraction of Integer to Pointer An integer value can be added and subtracted to a pointer. When an integer is added to a pointer, the pointer points to the next memory address. Similarly, when an integer is subtracted from a pointer, the pointer points to the previous memory location. Addition and subtraction of an integer to a pointer does not add and subtract that value to the pointer, multiplication with the size of the data type is added or subtracted to the pointer. For example, there is an integer pointer variable ptr and it is pointing to an address 123400, if you add 1 to the ptr (ptr+1), it will point to the address 123404 (size of an integer is 4). Let”s evaluate it, ptr = 123400 ptr = ptr + 1 ptr = ptr + sizeof(int)*1 ptr = 123400 + 4 ptr = 123404 Example of Adding Value to a Pointer In the following example, we are declaring an array and pointer to an array. Initializing the pointer with the first element of the array and then adding an integer value (2) to the

C – Dangling Pointers

Dangling Pointers in C ”; Previous Next Dangling Pointers in C Dangling pointers in C is used to describe the behavior of a pointer when its target (the variable it is pointing to) has been deallocated or is no longer accessible. In other words, a dangling pointer in C is a pointer that doesn”t point to a valid variable of the appropriate type. Why Do We Get Dangling Pointers in C? Working with a dangling pointer can lead to unpredicted behavior in a C program and sometimes it may result in the program crashing. The situation of dangling pointers can occur due to the following reasons − De-allocation of memory Accessing an out-of-bounds memory location When a variable goes out of scope Let”s analyze each of these three situations with the help of examples. De-allocation of Memory A pointer holds the address of a variable. If the target variable is deallocated or freed, then its pointer becomes a dangling pointer. Trying to access a pointer whose target variable has been deallocated results in garbage situations. Let us use malloc() to create an integer variable and store its address in an integer pointer. int *x = (int *) malloc(sizeof(int)); *x = 100; Here, the pointer is referring to a valid location in the memory. Let us release the memory pointed by “x” using the free() function. free(x); Now, “x” stores an address that is no longer valid. Hence, if we try to dereference it, the compiler shows a certain garbage value. Example The following example shows how we end up getting dangling pointers in a C program − #include <stdio.h> int main(){ int *x = (int *) malloc(sizeof(int)); *x = 100; printf(“x: %dn”, *x); free (x); printf(“x: %dn”, *x); } Output Run the code and check its output − x: 100 x: 11665744 Accessing an Out-of-Bounds Memory Location We know that a function can return a pointer. If it returns a pointer to any local variable inside the function, it results in a dangling pointer in the outer scope, as the location it points to is no longer valid. Example Take a look at the following code − #include <stdio.h> int * function(); int main(){ int *x = function(); printf(“x: %d”, *x); return 0; } int * function(){ int a =100; return &a; } Output When compiled, the following warning is displayed at the “return &a” statement in the function − warning: function returns address of local variable [-Wreturn-local-addr] If you run the program despite the warning, you get the following error − Segmentation fault (core dumped) When you get this error, it means that the program is trying to access a memory location that is out of bounds. When a Variable Goes Out of Scope The same reason applies when a variable declared in an inner block is accessed outside it. In the following example, we have a variable inside a block and its address is stored in a pointer variable. However, outside the block, the pointer becomes a dangling pointer as its target is out of bounds. Example The following program shows how we get a dangling pointer when its base variable goes out of scope − #include <stdio.h> int main(){ int *ptr;{ int a = 10; ptr = &a; } // ”a” is now out of scope // ptr is a dangling pointer now printf(“%d”, ptr); return 0; } Output It will display a garbage value − 6422036 How to Fix Dangling Pointers? C doesn’t have the feature of automatic garbage collection, so we need to carefully manage the dynamically allocated memory. To fix the issue of dangling pointers or to avoid them altogether, you need to apply proper memory management and try to avoid situations where you may end up getting dangling pointers. Here are some general guidelines that you can follow to avoid dangling pointers − Always ensure that pointers are set to NULL after the memory is deallocated. It will clearly signify that the pointer is no longer pointing to a valid memory location. Avoid accessing a variable or a memory location that has gone out of scope. Do not return pointers to local variables because such local variables will go out of scope when the function returns. By following these guidelines, you can reduce the chances of getting dangling pointers in your code. Print Page Previous Next Advertisements ”;

C – Chain of Pointers

Chain of Pointers in C ”; Previous Next What is Chain of Pointers in C? A chain of pointers in C is a series of pointers that point to each other. A pointer variable can store the address of another variable which can be of any type, including another pointer, in which case it is called a pointer to pointer. A chain of pointers is when there are multiple levels of pointers. Theoretically, there is no limit to how many levels the chaining can be done, as shown in the following diagram − Declaration of Chain of Pointers This can be represented by the following code − int a = 10; int *x = &a; int **y = &x; int ***z = &y; In the above example, “x” is a pointer to an “int” type, as the notation “int *” indicates. To store the address of “x” in “y”, it should be a pointer to a pointer to int, i.e., “int **”. Similarly, “z” is a “pointer to a pointer to a pointer” to int, hence the asterisk appears thrice in its declaration, i.e., “int ***”. How Does the Dereferencing Work? We know that “*x” returns the value at the address stored in “x”, i.e., the value of “a”. Going by the same logic, “*y” should return its value (refer to the above diagram) which is 1000, which in turn is the address of “a”. Hence, the double dereferencing of “y” (i.e., “**y”) should give you the value of “a”. Further, a triple referencing of “z” as “***z” should give the value of “a”. Example The following example shows how “double dereferencing” and “triple dereferencing” work − #include <stdio.h> int main(){ int a = 10; int *x = &a; int **y = &x; int ***z = &y; printf(“a: %dn”, a); printf(“a: %dn”, *x); // dereferencing x; printf(“a: %dn”, **y); // double dereferencing y; printf(“a: %dn”, ***z); // triple dereferencing z; return 0; } Output Notice that all the three cases of dereferencing print the value of “a” − a: 10 a: 10 a: 10 a: 10 A Chain of Float Pointers We can follow the same logic to create a chain of float pointers and apply dereferencing of multiple levels to obtain the value of a float variable. Example The following example shows how you can work with a chain of float pointers − #include <stdio.h> int main(){ float a = 10.25; float *x = &a; float **y = &x; float ***z = &y; printf(“a: %fn”, a); printf(“a: %fn”, *x); printf(“a: %fn”, **y); printf(“a: %fn”, ***z); return 0; } Output Run the code and check its output − a: 10.250000 a: 10.250000 a: 10.250000 a: 10.250000 Updating the Original Variable by Dereferencing We can also update the value of the original variable by dereferencing. Take a look at the following statement − *x = 11.25; It will change the value of “a” accordingly. Similarly, it can be updated with the pointer at subsequent levels. Example The following program shows how you can update the original variable using different levels of dereferencing − #include <stdio.h> int main(){ float a = 10.25;; float *x = &a; float **y = &x; float ***z = &y; printf(“a: %fn”, a); // update with first pointer *x = 11.25; printf(“a: %fn”, *x); // update with second pointer **y = 12.25; printf(“a: %fn”, **y); // update with third pointer ***z = 13.25; printf(“a: %fn”, ***z); return 0; } Output Run the code and check its output − a:10.250000 a:11.250000 a:12.250000 a:13.250000 A Chain of Character Pointers A string is represented as an array of “char” type or a pointer to “char” type − char *a = “Hello”; Hence, we can create a chain of char pointers. Note: The only difference is, here the original variable itself is a pointer, so the upper-level pointers have one asterisk more, as compared to the earlier examples. Example The following example shows how a chain of character pointers works − #include <stdio.h> int main(){ char *a = “Hello”; char **x = &a; char ***y = &x; char ****z = &y; printf(“a: %sn”, a); printf(“a: %sn”, *x); printf(“a: %sn”, **y); printf(“a: %sn”, ***z); return 0; } Output When you run this code, it will produce the following output − a: Hello a: Hello a: Hello a: Hello Chaining of pointers is useful for creating linked lists and other data structures. Print Page Previous Next Advertisements ”;

C – Compilation Process

Compilation Process in C ”; Previous Next C is a compiled language. Compiled languages provide faster execution performance as compared to interpreted languages. Different compiler products may be used to compile a C program. They are GCC, Clang, MSVC, etc. In this chapter, we will explain what goes in the background when you compile a C program using GCC compiler. Compiling a C Program A sequence of binary instructions consisting of 1 and 0 bits is called as machine code. High-level programming languages such as C, C++, Java, etc. consist of keywords that are closer to human languages such as English. Hence, a program written in C (or any other high-level language) needs to be converted to its equivalent machine code. This process is called compilation. Note that the machine code is specific to the hardware architecture and the operating system. In other words, the machine code of a certain C program compiled on a computer with Windows OS will not be compatible with another computer using Linux OS. Hence, we must use the compiler suitable for the target OS. C Compilation Process Steps In this tutorial, we will be using the gcc (which stands for GNU Compiler Collection). The GNU project is a free-software project by Richard Stallman that allows developers to have access to powerful tools for free. The gcc compiler supports various programming languages, including C. In order to use it, we should install its version compatible with the target computer. The compilation process has four different steps − Preprocessing Compiling Assembling Linking The following diagram illustrates the compilation process. Example To understand this process, let us consider the following source code in C languge (main.c) − #include <stdio.h> int main(){ /* my first program in C */ printf(“Hello World! n”); return 0; } Output Run the code and check its output − Hello World! The “.c” is a file extension that usually means the file is written in C. The first line is the preprocessor directive #include that tells the compiler to include the stdio.h header file. The text inside /* and */ are comments and these are useful for documentation purpose. The entry point of the program is the main() function. It means the program will start by executing the statements that are inside this function’s block. Here, in the given program code, there are only two statements: one that will print the sentence “Hello World” on the terminal, and another statement that tells the program to “return 0” if it exited or ended correctly. So, once we compiled it, if we run this program we will only see the phrase “Hello World” appearing. What Goes Inside the C Compilation Process? In order for our “main.c” code to be executable, we need to enter the command “gcc main.c”, and the compiling process will go through all of the four steps it contains. Step 1: Preprocessing The preprocessor performs the following actions − It removes all the comments in the source file(s). It includes the code of the header file(s), which is a file with extension .h which contains C function declarations and macro definitions. It replaces all of the macros (fragments of code which have been given a name) by their values. The output of this step will be stored in a file with a “.i” extension, so here it will be in “main.i“. In order to stop the compilation right after this step, we can use the option “-E” with the gcc command on the source file, and press Enter. gcc -E main.c Step 2: Compiling The compiler generates the IR code (Intermediate Representation) from the preprocessed file, so this will produce a “.s” file. That being said, other compilers might produce assembly code at this step of compilation. We can stop after this step with the “-S” option on the gcc command, and press Enter. gcc -S main.c This is what the main.s file should look like − .file “helloworld.c” .text .def __main; .scl 2; .type 32; .endef .section .rdata,”dr” .LC0: .ascii “Hello, World! “ .text .globl main .def main; .scl 2; .type 32; .endef .seh_proc main main: pushq %rbp .seh_pushreg %rbp movq %rsp, %rbp .seh_setframe %rbp, 0 subq $32, %rsp .seh_stackalloc 32 .seh_endprologue call __main leaq .LC0(%rip), %rcx call puts movl $0, %eax addq $32, %rsp popq %rbp ret .seh_endproc .ident “GCC: (x86_64-posix-seh-rev0, Built by MinGW-W64 project) 8.1.0″ .def puts; .scl 2; .type 32; .endef Step 3: Assembling The assembler takes the IR code and transforms it into object code, that is code in machine language (i.e. binary). This will produce a file ending in “.o”. We can stop the compilation process after this step by using the option “-c” with the gcc command, and pressing Enter. Note that the “main.o” file is not a text file, hence its contents won”t be readable when you open this file with a text editor. Step 4: Linking The linker creates the final executable, in binary. It links object codes of all the source files together. The linker knows where to look for the function definitions in the static libraries or the dynamic libraries. Static libraries are the result of the linker making a copy of all the used library functions to the executable file. The code in dynamic libraries is not copied entirely, only the name of the library is placed in the binary file. By default, after this fourth and last step, that is when you type the whole “gcc main.c” command without any options, the compiler will create an executable program called main.out (or main.exe in case of Windows) that we can run from the command

C – Hello World

C – Hello World ”; Previous Next Every learner aspiring to become a professional software developer starts with writing a Hello World program in the programming language he/she is learning. In this chapter, we shall learn how to write a Hello World program in C language. Hello World in C Language Before writing the Hello World program, make sure that you have the C programming environment set up in your computer. This includes the GCC compiler, a text editor, and preferably an IDE for C programming such as CodeBlocks. Example The first step is to write the source code for the Hello World program. Open a text editor on your computer. On Windows, open Notepad or Notepad++, enter the following code and save it as “hello.c”. #include <stdio.h> int main(){ /* my first program in C */ printf(“Hello World! n”); return 0; } Output Run the code and check its output − Hello World! The Step-by-Step Execution of a C Program Let us understand how the above program works in a step-by-step manner. Step 1 The first statement in the above code is the #include statement that imports the stdio.h file in the current C program. This is called a preprocessor directive. This header file contains the definitions of several library functions used for stand IO operations. Since we shall be calling the printf() function which is defined in the stdio.h library, we need to include it in the first step. Step 2 Every C program must contain a main() function. The main() function in this program prints the “Hello World” message on the console terminal. Inside the main() function, we have inserted a comment statement that is ultimately ignored by the compiler; it is for the documentation purpose. The next statement calls the printf() function. In C, every statement must terminate with a semicolon symbol (;), failing which the compiler reports an error. The printf() function, imported from the stdio.h library file, echoes the Hello World string to the standard output stream. In case of Windows, the standard output stream is the Command prompt terminal and in case of Linux it is the Linux terminal. In C, every function needs to have a return value. If the function doesn’t return anything, its value is void. In the example above, the main() function has int as its return value. Since the main() function doesn’t need to return anything, it is defined to return an integer “0”. The “return 0” statement also indicates that the program has been successfully compiled and run. Step 3 Next, we need to compile and build the executable from the source code (“hello.c”). If you are using Windows, open the command prompt in the folder in which “hello.c” has been saved. The following command compiles the source code − gcc -c hello.c -o hello.o The -c option specifies the source code file to be compiled. This will result in an object file with the name hello.o if the C program doesn’t have any errors. If it contains errors, they will be displayed. For example, if we forget to put the semicolon at the end of the printf() statement, the compilation result will show the following error − helloworld.c: In function ”main”: helloworld.c:6:30: error: expected ”;” before ”return” printf(“Hello, World! n”) ^ ; helloworld.c:8:4: return 0; To build an executable from the compiled object file, use the following command − gcc -o hello.exe hello.o The hello.exe is now ready to be run from the command prompt that displays the Hello World message in the terminal. C:Usersuser>hello Hello World! On Ubuntu Linux, the object file is first given executable permission before running it by prefixing “./” to it. $ chmod a+x a.o $ ./a.o You can also use an IDE such as CodeBlocks to enter the code, edit, debug and run the Hello World program more conveniently. Using CodeBlocks IDE for C Programming CodeBlocks is one the most popular IDEs for C/C++ development. Install it if you have not already done and open it. Create a new file from the File menu, enter the following code and save it as “hello.c”. Example #include <stdio.h> int main(){ /* my first program in C */ printf(“Hello World! n”); return 0; } Output Run the code and check its output − Hello World! Choose Build and Run option from the Build menu as shown below − You can also use the F9 shortcut for the same. If the program is error-free, the Build Log tab shows the following messages − gcc.exe -c C:Usersmlathhello.c -o C:Usersmlathhello.o gcc.exe -o C:Usersmlathhello.exe C:Usersmlathhello.o Process terminated with status 0 (0 minute(s), 0 second(s)) 0 error(s), 0 warning(s) (0 minute(s), 0 second(s)) Checking for existence: C:Usersmlath hello.exe Executing: ””C:Program FilesCodeBlocks/cb_console_runner.exe” “C:Usersmlathhello.exe”” (in ”C:UsersmlathDocuments”) In a separate command prompt window, the output will be displayed − Hello World! Process returned 0 (0x0) execution time : 0.236 s Press any key to continue. If the code contains errors, the build log tab echoes them. For instance, if we miss the trailing semicolon in the printf() statement, the log will be as below − You can use any other IDE to run the C program. You will need to follow the documentation of the respective IDE for the purpose. Running the Hello World successfully also confirms that the C programming environment is working properly on your computer. Print Page Previous Next Advertisements ”;

C – Program Structure

C – Program Structure ”; Previous Next A typical program in C language has certain mandatory sections and a few optional sections, depending on the program”s logic, complexity, and readability. Normally a C program starts with one or more preprocessor directives (#include statements) and must have a main() function that serves as the entry point of the program. In addition, there may be global declarations of variables and functions, macros, other user-defined functions, etc. The Preprocessor Section The C compiler comes with several library files, having “.h” as an extension. A “.h” file (called a “header file”) consists of one or more predefined functions (also called “library functions”) to be used in the C program. The library functions must be loaded in any C program. The “#include” statement is used to include a header file. It is a “preprocessor directive”. For example, printf() and scanf() functions are needed to perform console I/O operations. They are defined in the stdio.h file. Hence, you invariably find #include <stdio.h> statement at the top of any C program. Other important and frequently used header files include string.h, math.h, stdlib.h, etc. There are other preprocessor directives such as #define which is used to define constants and macros and #ifdef for conditional definitions. The following statement defines a constant PI − #define PI 3.14159 Example Once a constant is defined, it can be used in the rest of the C program. #include <stdio.h> #define PI 3.14159 int main(){ int radius = 5; float area = PI*radius*radius; printf(“Area: %f”, area); return 0; } Output On executing this code, you will get the following output − Area: 78.539749 You can also define a macro with the “#define” directive. It is similar to a function in C. We can pass one or more arguments to the macro name and perform the actions in the code segment. The following code defines AREA macro using the #define statement − Example #include <stdio.h> #define PI 3.14159 #define AREA(r) (PI*r*r) int main(){ int radius = 5; float area = AREA(radius); printf(“Area: %f”, area); return 0; } Output Area: 78.539749 Macros are generally faster in execution than the functions. The main() Function A C program is a collection of one or more functions. There are two types of functions in a C program: library functions and user-defined functions. There must be at least one user-defined function in a C program, whose name must be main(). The main() function serves as the entry point of the program. When the program is run, the compiler looks for the main() function. The main() function contains one or more statements. By default, each statement must end with a semicolon. The statement may include variable declarations, decision control or loop constructs or call to a library or another user-defined function. In C, a function must have a data type. The data type of return value must match with the data type of the function. By default, a function in C is of int type. Hence, if a function doesn’t have a return statement, its type is int, and you may omit it in the function definition, but the compiler issues a warning − warning: return type defaults to ”int” Example A typical example of main() function is as follows − #include <stdio.h> int main() { /* my first program in C */ printf(“Hello, World! n”); return 0; } Output On executing this code, you will get the following output − Hello, World! The Global Declaration Section This section consists of declaration of variables to be used across all the functions in a program. Forward declarations of user-defined functions defined later in the program as well as user-defined data types are also present in the global section. Example of global variable declaration − int total = 0; float average = 0.0; Example of forward declaration of a function − float area(float height, float width); Subroutines in a C Program There may be more than one user-defined functions in a C program. Programming best practices require that the programming logic be broken down to independent and reusable functions in a structured manner. Depending on the requirements, a C program may have one or more user-defined functions, which may be called from the main() function or any other user-defined function as well. Comments in a C Program Apart from the programming elements of a C program such as variables, structures, loops, functions, etc., the code may have a certain text inside “/* .. */” recognized as comments. Such comments are ignored by the compiler. Inserting comments in the code often proves to be helpful in documenting the program, and in understanding as well as debugging the programming logic and errors. If the /* symbol doesn’t have a matching */ symbol, the compiler reports an error: “Unterminated comment”. A text between /* and */ is called as C-style comment, and is used to insert multi-line comments. /* Program to display Hello World Author: Tutorialspoint Built with codeBlocks */ A single line comment starts with a double forward-slash (//) and ends with a new line. It may appear after a valid C statement also. int age = 20; // variable to store age However, a valid statement can’t be given in a line that starts with “//”. Hence, the following statement is erroneous: // Variable to store age. int age=20; Structure of the C Program The following code shows the different sections in a C program − /*Headers*/ #include <stdio.h> #include <math.h> /*forward declaration*/ float area_of_square(float); /*main function*/ int main() { /* my first program in