Multi-dimensional Arrays in C ”; Previous Next The array is declared with one value of size in square brackets, it is called one dimensional array. In a one dimensional array, each element is identified by its index or subscript. In C, you can declare with more indices to simulate a two, three or multidimensional array. Multidimensional Arrays in C Multi-dimensional arrays can be termed as nested arrays. In such a case, each element in the outer array is an array itself. Such type of nesting can be upto any level. If each element in the outer array is another one-dimensional array, it forms a two-dimensional array. In turn, the inner array is an array of another set of one dimensional array, it is a three-dimensional array, and so on. Declaration of Multidimensional Arrays Depending on the nesting level, the multi-dimensional array is declared as follows − type name[size1][size2]…[sizeN]; For example, the following declaration creates a three dimensional integer array − int threedim[3][3][3]; A multidimensional array can have any number of dimensions. In this tutorial, we will learn about the two commonly used types of multidimensional arrays: Two-dimensional Array Three-dimensional Array Two-dimensional Array in C A two-dimensional array in an array of one-dimensional arrays. Each element of a two-dimensional array is an array itself. It is like a table or a matrix. The elements can be considered to be logically arranged in rows and columns. Hence, the location of any element is characterised by its row number and column number. Both row and column index start from 0. Declaration and Initialization of Two-dimensional Array The following statement declares and initializes a two-dimensional array − int arr[3][5] = {1,2,3,4,5, 10,20,30,40,50, 5,10,15,20,25}; The arr array has three rows and five columns. In C, a two dimensional array is a row−major array. The first square bracket always represents the dimension size of rows, and the second is the number of columns. Obviously, the array has 3 X 5 = 15 elements. The array is initialized with 15 comma−separated values put inside the curly brackets. Elements are read into the array in a row−wise manner, which means the first 5 elements are stored in first row, and so on. Hence, the first dimension is optional in the array declaration. int arr[ ][5] = {1,2,3,4,5, 10,20,30,40,50, 5,10,15,20,25}; To increase the readability, elements of each row can be optionally put in curly brackets as follows − int arr[ ][5] = { {1,2,3,4,5}, {10,20,30,40,50}, {5,10,15,20,25} }; The numbers are logically arranged in a tabular manner as follows − 1 2 3 4 5 10 20 30 40 50 5 10 15 20 25 The cell with row index 1 and column index 2 has 30 in it. Example of Printing Elements of Two-dimensional Array The program below displays the row and column indices of each element in a 2D array − #include <stdio.h> int main () { /* an array with 5 rows and 2 columns*/ int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; int i, j; /* output each array element”s value */ for ( i = 0; i < 5; i++ ) { for ( j = 0; j < 2; j++ ) { printf(“a[%d][%d] = %dn”, i,j, a[i][j] ); } } return 0; } Output a[0][0] = 0 a[0][1] = 0 a[1][0] = 1 a[1][1] = 2 a[2][0] = 2 a[2][1] = 4 a[3][0] = 3 a[3][1] = 6 a[4][0] = 4 a[4][1] = 8 In case of a two or multi-dimensional array, the compiler assigns a memory block of the size which is the product of dimensions multiplied by the size of the data type. In this case, the size is 3 X 5 X 4 = 60 bytes, 4 being the size of int data type. Even though all the elements are stored in consecutive memory locations, we can print the elements in row and column format with the use of nested loops. Example of Printing Two-dimensional Array as Matrix in Row and Columns The following program prints a two-dimensional array in row and columns. #include <stdio.h> int main() { int arr[3][5] = {1,2,3,4,5, 10,20,30,40,50, 5,10,15,20,25}; int i, j; for (i=0; i<3; i++){ for (j=0; j<5; j++){ printf(“%4d”, arr[i][j]); } printf(“n”); } return 0; } Output 1 2 3 4 5 10 20 30 40 50 5 10 15 20 25 Three-dimensional Array in C A three-dimensional array is an array of two-dimensional arrays, where each element is a two-dimensional array. A 3D array needs three subscripts to define depth, row, and column. Imagine the students appearing for an exam are seated in five halls, each hall having twenty rows of desks, and each row has 5 tables. Such an arrangement is represented by a three dimensional array such as − Students[hall][row][column] To locate each student, you need to have three indices, hall number, row and column of his table in the hall. Example of Three-dimensional Array The following program stores numbers in a 3 X 3 X 3 array − #include<stdio.h> int main(){ int i, j, k; int arr[3][3][3]= { { {11, 12, 13}, {14, 15, 16}, {17, 18, 19} }, { {21, 22, 23}, {24, 25, 26}, {27, 28, 29} }, { {31, 32, 33}, {34, 35, 36}, {37, 38, 39} }, }; printf(“Printing 3D Array Elementsn”); for(i=0;i<3;i++) { for(j=0;j<3;j++){ for(k=0;k<3;k++){ printf(“%4d”,arr[i][j][k]); } printf(“n”); } printf(“n”); } return 0; } Output Printing 3D Array Elements 11 12 13 14 15 16 17
Category: cprogramming
C – Pragmas
#pragma Directive in C ”; Previous Next What is #pragma Directive in C? The preprocessor directive #pragma is used to provide additional information to the compiler in C/C++ language. This is used by the compiler to provide some special features. Note that pragmas are compiler dependent. Not all the pragma directives are supported by all the compilers. Syntax Here is the syntax of using a #pragma directive in C/C++ language − #pragma token_name Types of Pragma Directives in C The table of some of #pragma directives in C/C++ language is given as follows, Directive Description #pragma startup Before the execution of main(), the function specified in pragma is needed to run. #pragma exit Before the end of program, the function specified in pragma is needed to run. #pragma warn Used to hide the warning messages. #pragma GCC dependency Checks the dates of current and other file. If other file is recent, it shows a warning message. #pragma GCC system_header It treats the code of current file as if it came from system header. #pragma GCC poison Used to block an identifier from the program. #pragma once Compiler loads the header file only once. #pragma startup and exit These pragma directives are executed before and after the main() function. Not all the compilers support these directives. Example The following code demonstrates how you can use the pragma startup and exit directives − #include <stdio.h> int display(); #pragma startup display #pragma exit display int main(){ printf(“nI am in main function”); return 0; } int display() { printf(“nI am in display function”); return 0; } Output When you run this code, it will produce the following output − I am in main function #pragma warn The #pragma warn directive is used to hide or display the warning messages which are displayed during compilation. The warn pragma is used as per the following syntax − #pragma warn +xxx (To show the warning) #pragma warn -xxx (To hide the warning) #pragma warn .xxx (To toggle between hide and show) The three character codes to be used are rvl (return value), par (parameter used or not), and rch (if the code is unreachable). If any character code is prefixed by “+”, it indicates to show the warning; prefixed by “–” means indication to the compiler to hide warnings, and prefix by dot (.) is an instruction to the compiler to toggle between hide and display warnings. Example The following example shows how you can use the warn pragma in a C program − #include <stdio.h> #pragma warn -rvl /* return value */ #pragma warn +par /* parameter never used */ #pragma warn –rch /* unreachable code */ int square(int x){ printf(“Hello World”); } int main(){ square(10); return 0; } Output When you run this code, it will produce the following output − Hello World #pragma GCC poison The GCC compiler removes an identifier completely from the program. If we want to block an identifier, then we can use the #pragma GCC poison directive. Its syntax is as follows − #pragma GCC poison identifier Example In this example, we will use the GCC poison pragma to block the printf() function − #include <stdio.h> #pragma GCC poison printf int main(){ int a = 10; if (a == 10) { printf(“Hello World”); } else printf(“TutorialsPoint”); return 0; } Output When you try to compile this code, it will show the following error − error: attempt to use poisoned “printf” #pragma GCC dependency This pragma allows you to check the relative dates of the current file and another file. If the other file is more recent than the current file, a warning is issued. Example Take a look at the following example − #include <stdio.h> #pragma GCC dependency “depends.c” int main(){ printf(“Hello, World!”); return 0; } Output The above source code is depending on depends.c. If its compilation timestamp is more recent, then the following warning is issued − warning: current file is older than depends.c #pragma GCC system_header As a convention, system header files are placed angular brackets in front of the #include directive, whereas the non-system header files are in quotation marks. If you want the compiler to treat the latter as the system header, use this pragma. Syntax #pragma GCC system_header library.h We define a “library.h” header file in the current directory. #ifndef LIBRARY_H #define LIBRARY_H #pragma GCC system_header void myFunction(); #endif Example To ask the compiler to treat “library.h” as a system header, use the #pragma GCC system_header. #include <stdio.h> #include “library.h” int main(){ myFunction(); // Using a function from the library.h printf(“Hello, World!n”); return 0; } #pragma once The #pragma once directive causes the header file to be included only once, even if the programmer includes it multiple times. Save the “myheader.h” file as − myheader.h #pragma once void myFunction(); Example In another code (main.c), call myFunction() as follows − #include <stdio.h> #include “myheader.h” int main(){ myFunction(); printf(“Hello, World!n”); return 0; } Print Page Previous Next Advertisements ”;
C – Input & Output
Input and Output Functions in C ”; Previous Next Reading input from the user and showing it on the console (output) are the common tasks every C program needs. C language provides libraries (header files) that contain various functions for input and output. In this tutorial, we will learn different types of formatted and unformatted input and output functions. The Standard Files in C The C language treats all the devices as files. So, devices such as the “display” are addressed in the same way as “files”. The following three files are automatically opened when a program executes to provide access to the keyboard and screen. Standard File File Device Standard input stdin Keyboard Standard output stdout Screen Standard error stderr Your screen To access a file, C uses a predefined FILE struct type to refer to the file for reading and writing purpose. Read this chapter to understand how to read values from the screen and how to print the result on the screen. Types of Input and Output Functions We have the following categories of IO function in C − Unformatted character IO functions: getchar() and putchar() Unformatted string IO functions: gets() and puts() Formatted IO functions: scanf() and printf() The unformatted I/O functions read and write data as a stream of bytes without any format, whereas formatted I/O functions use predefined formats like “%d”, “%c” or “%s” to read and write data from a stream. Unformatted Character Input & Output Functions: getchar() and putchar() These two functions accept a single character as input from the keyboard, and display a single character on the output terminal, respectively. The getchar() function it reads a single key stroke without the Enter key. int getchar(void) There are no parameters required. The function returns an integer corresponding to the ASCII value of the character key input by the user. Example 1 The following program reads a single key into a char variable − #include <stdio.h> int main() { char ch; printf(“Enter a character: “); ch = getchar(); puts(“You entered: “); putchar(ch); return 0; } Output Run the code and check its output − Enter a character: W You entered: W Example 2 The following program shows how you can read a series of characters till the user presses the Enter key − #include <stdio.h> int main() { char ch; char word[10]; int i = 0; printf(“Enter characters. End with pressing enter: “); while(1) { ch = getchar(); word[i] = ch; if (ch == ”n”) break; i++; } printf(“nYou entered the word: %s”, word); return 0; } Output Run the code and check its output − Enter characters. End with pressing enter: Hello You entered the word: Hello You can also use the unformatted putchar() function to print a single character. The C library function “int putchar(int char)” writes a character (an unsigned char) specified by the argument char to stdout. int putchar(int c) A single parameter to this function is the character to be written. You can also pass its ASCII equivalent integer. This function returns the character written as an unsigned char cast to an int or EOF on error. Example 3 The following example shows how you can use the putchar() function − #include <stdio.h> int main() { char ch; for(ch = ”A” ; ch <= ”Z” ; ch++) { putchar(ch); } return(0); } Output When you run this code, it will produce the following output − ABCDEFGHIJKLMNOPQRSTUVWXYZ Formatted String Input & Output Functions: gets(), fgets(), puts(), and fputs() The char *gets(char *str) function reads a line from stdin into the buffer pointed to by str until either a terminating newline or EOF (End of File) is encountered. char *gets (char *str) This function has a single argument. It is the pointer to an array of chars where the C string is stored. The function returns “str” on success and NULL on error or when EOF occurs while no characters have been read. Example Take a look at the following example − #include <stdio.h> int main() { char name[20]; printf(“Enter your name: “); gets(name); printf(“You entered the name: %s”, name); return 0; } Output Enter your name: Ravikant Soni You entered the name: Ravikant Soni scanf(“%s”) reads characters until it encounters a whitespace (space, tab, newline, etc.) or EOF. So, if you try to input a string with multiple words (separated by a whitespace), then it accepts characters before the first whitespace as the input to string. fgets() Function In newer versions of C, gets() has been deprecated as it is potentially a dangerous function because it doesn’t perform bound checks and may result in buffer overflow. Instead, it is advised to use fgets() function − fgets(char arr[], size, stream); fgets() can be used to accept input from any input stream such as stdin (keyboard) or FILE (file stream). Example 1 The following program shows how you can use fgets() to accept multi-word input from the user − #include <stdio.h> int main () { char name[20]; printf(“Enter a name: n”); fgets(name, sizeof(name), stdin); printf(“You entered: n”); printf(“%s”, name); return 0; } Output Run the code and check its output − Enter a name: Rakesh Sharma You entered: Rakesh Sharma The function “int puts (const char *str)” writes the string ”s” and
C – Recursion
Recursion in C ”; Previous Next Recursion is the process by which a function calls itself. C language allows writing of such functions which call itself to solve complicated problems by breaking them down into simple and easy problems. These functions are known as recursive functions. What is a Recursive Function in C? A recursive function in C is a function that calls itself. A recursive function is used when a certain problem is defined in terms of itself. Although it involves iteration, using iterative approach to solve such problems can be tedious. Recursive approach provides a very concise solution to seemingly complex problems. Syntax This is how a general recursive function looks like − void recursive_function(){ recursion(); // function calls itself } int main(){ recursive_function(); } While using recursion, programmers need to be careful to define an exit condition from the function, otherwise it will go into an infinite loop. Why Recursion is Used in C? Recursion is used to perform complex tasks such as tree and graph structure traversals. Popular recursive programming solutions include factorial, binary search, tree traversal, tower of Hanoi, eight queens problem in chess, etc. A recursive program becomes concise, it is not easily comprehendible. Even if the size of the code may reduce, it needs more resources of the processor, as it involves multiple IO calls to the function. Factorial Using Recursion Recursive functions are very useful to solve many mathematical problems such as calculating the factorial of a number, generating Fibonacci series, etc. The most popular example of recursion is calculation of factorial. Mathematically, a factorial is defined as − n! = n X (n-1)! It can be seen that we use factorial itself to define factorial. Hence this is a fit case to write a recursive function. Let us expand the above definition for calculating the factorial value of 5. 5! = 5 X 4! 5 X 4 X 3! 5 X 4 X 3 X 2! 5 X 4 X 3 X 2 X 1! 5 X 4 X 3 X 2 X 1 = 120 While we can perform this calculation using a loop, its recursive function involves successively calling it by decrementing the number till it reaches 1. Example: Non-Recursive Factorial Function The following program shows how you can use a non-recursive function to calculate the factorial of a number − #include <stdio.h> #include <math.h> // function declaration int factorial(int); int main(){ int a = 5; int f = factorial(a); printf(“a: %d n”, a); printf(“Factorial of a: %d”, f); } int factorial(int x){ int i; int f = 1; for (i = 5; i >= 1; i–){ f *= i; } return f; } Output When you run this code, it will produce the following output − a: 5 Factorial of a: 120 Example: Recursive Factorial Function Let us now write a recursive function for calculating the factorial of a given number. The following example calculates the factorial of a given number using a recursive function − #include <stdio.h> #include <math.h> /* function declaration */ int factorial(int i){ if(i <= 1){ return 1; } return i * factorial(i – 1); } int main(){ int a = 5; int f = factorial(a); printf(“a: %d n”, a); printf(“Factorial of a: %d”, f); return 0; } Output Run the code and check its output − a: 5 Factorial of a: 120 When the main() function calls the factorial() function by passing the variable “a”, its value is stored in “i”. The factorial() function successively calls itself. In each call, the value of “i” is multiplied by its earlier value after reducing it by 1, till it reaches 1. As it reaches 1, the product of all the values between the initial value of the argument and 1 is returned to the main() function. Binary Search Using Recursion Let us have a look at another example to understand how recursion works. The problem at hand is to check whether a given number is present in an array. While we can perform a sequential search for a certain number in the list using a for loop and comparing each number, the sequential search is not efficient, especially if the list is too long. The binary search algorithm checks if the index “start” is greater than the index “end”. Based on the value present at the variable “mid”, the function is called again to search for the element. We have a list of numbers arranged in ascending order. Then we find the midpoint of the list and restrict the checking to either left or right of the midpoint, depending on whether the desired number is less than or greater than the number at the midpoint. Example: Recursive Binary Search The following code implements the recursive binary searching technique − #include <stdio.h> int bSearch(int array[], int start, int end, int element){ if (end >= start){ int mid = start + (end – start ) / 2; if (array[mid] == element) return mid; if (array[mid] > element) return bSearch(array, start, mid-1, element); return bSearch(array, mid+1, end, element); } return -1; } int main(void){ int array[] = {5, 12, 23, 45, 49, 67, 71, 77, 82}; int n = 9; int element = 67; int index = bSearch(array, 0, n-1, element); if(index == -1 ){ printf(“Element not found in the array “); } else{ printf(“Element found at index: %d”, index); } return 0; } Output Run the code and check its output − Element found at index: 5 Fibonacci Series Using Recursion In Fibonacci series, a number is the sum
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 – sizeof Operator
C – The sizeof Operator ”; Previous Next The sizeof operator is a compile−time unary operator. It is used to compute the size of its operand, which may be a data type or a variable. It returns the size in number of bytes. It can be applied to any data type, float type, or pointer type variables. sizeof(type or var); When sizeof() is used with a data type, it simply returns the amount of memory allocated to that data type. The outputs can be different on different machines, for example, a 32-bit system can show a different output as compared to a 64-bit system. Example 1: Using the sizeof Operator in C Take a look at the following example. It highlights how you can use the sizeof operator in a C program − #include <stdio.h> int main(){ int a = 16; printf(“Size of variable a: %d n”,sizeof(a)); printf(“Size of int data type: %d n”,sizeof(int)); printf(“Size of char data type: %d n”,sizeof(char)); printf(“Size of float data type: %d n”,sizeof(float)); printf(“Size of double data type: %d n”,sizeof(double)); return 0; } Output On running this code, you will get the following output − Size of variable a: 4 Size of int data type: 4 Size of char data type: 1 Size of float data type: 4 Size of double data type: 8 Example 2: Using sizeof with Struct In this example, we declare a struct type and find the size of the struct type variable. #include <stdio.h> struct employee { char name[10]; int age; double percent; }; int main(){ struct employee e1 = {“Raghav”, 25, 78.90}; printf(“Size of employee variable: %dn”,sizeof(e1)); return 0; } Output Run the code and check its output − Size of employee variable: 24 Example 3: Using sizeof with Array In the following code, we have declared an array of 10 int values. Applying the sizeof operator on the array variable returns 40. This is because the size of an int is 4 bytes. #include <stdio.h> int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; printf(“Size of arr: %dn”, sizeof(arr)); } Output Run the code and check its output − Size of arr: 40 Example 4: Using sizeof to Find the Length of an Array In C, we don’t have a function that returns the number of elements in a numeric array (we can get the number of characters in a string using the strlen() function). For this purpose, we can use the sizeof() operator. We first find the size of the array and then divide it by the size of its data type. #include <stdio.h> int main(){ int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int y = sizeof(arr)/sizeof(int); printf(“No of elements in arr: %dn”, y); } Output When you run this code, it will produce the following output − No of elements in arr: 10 Example 5: Using sizeof in Dynamic Memory Allocation The sizeof operator is used to compute the memory block to be dynamically allocated with the malloc() and calloc() functions. The malloc() function is used with the following syntax − type *ptr = (type *) malloc(sizeof(type)*number); The following statement allocates a block of 10 integers and stores its address in the pointer − int *ptr = (int *)malloc(sizeof(int)*10); When the sizeof() is used with an expression, it returns the size of the expression. Here is an example. #include <stdio.h> int main(){ char a = ”S”; double b = 4.65; printf(“Size of variable a: %dn”,sizeof(a)); printf(“Size of an expression: %dn”,sizeof(a+b)); int s = (int)(a+b); printf(“Size of explicitly converted expression: %dn”,sizeof(s)); return 0; } Output Run the code and check its output − Size of variable a: 1 Size of an expression: 8 Size of explicitly converted expression: 4 Example 6: The Size of a Pointer in C The sizeof() operator returns the same value irrespective of the type. This includes the pointer of a built−in type, a derived type, or a double pointer. #include <stdio.h> int main(){ printf(“Size of int data type: %d n”, sizeof(int *)); printf(“Size of char data type: %d n”, sizeof(char *)); printf(“Size of float data type: %d n”, sizeof(float *)); printf(“Size of double data type: %d n”, sizeof(double *)); printf(“Size of double pointer type: %d n”, sizeof(int **)); } Output Run the code and check its output − Size of int data type: 8 Size of char data type: 8 Size of float data type: 8 Size of double data type: 8 Size of double pointer type: 8 c_operators.htm Print Page Previous Next Advertisements ”;
C – Strings
Strings in C ”; Previous Next Strings in C A string in C is a one-dimensional array of char type, with the last character in the array being a “null character” represented by ””. Thus, a string in C can be defined as a null-terminated sequence of char type values. Creating a String in C Let us create a string “Hello”. It comprises five char values. In C, the literal representation of a char type uses single quote symbols − such as ”H”. These five alphabets put inside single quotes, followed by a null character represented by ”” are assigned to an array of char types. The size of the array is five characters plus the null character − six. Example char greeting[6] = {”H”, ”e”, ”l”, ”l”, ”o”, ””}; Initializing String Without Specifying Size C lets you initialize an array without declaring the size, in which case the compiler automatically determines the array size. Example char greeting[] = {”H”, ”e”, ”l”, ”l”, ”o”, ””}; The array created in the memory can be schematically shown as follows − If the string is not terminated by “”, it results in unpredictable behavior. Note: The length of the string doesn’t include the null character. The library function strlen() returns the length of this string as 5. Loop Through a String You can loop through a string (character array) to access and manipulate each character of the string using the for loop or any other loop statements. Example In the following example, we are printing the characters of the string. #include <stdio.h> #include <string.h> int main (){ char greeting[] = {”H”, ”e”, ”l”, ”l”, ”o”, ””}; for (int i = 0; i < 5; i++) { printf(“%c”, greeting[i]); } return 0; } Output It will produce the following output − Hello Printing a String (Using %s Format Specifier) C provides a format specifier “%s” which is used to print a string when you”re using functions like printf() or fprintf() functions. Example The “%s” specifier tells the function to iterate through the array, until it encounters the null terminator () and printing each character. This effectively prints the entire string represented by the character array without having to use a loop. #include <stdio.h> int main (){ char greeting[] = {”H”, ”e”, ”l”, ”l”, ”o”, ””}; printf(“Greeting message: %sn”, greeting ); return 0; } Output It will produce the following output − Greeting message: Hello You can declare an oversized array and assign less number of characters, to which the C compiler has no issues. However, if the size is less than the characters in the initialization, you may get garbage values in the output. char greeting[3] = {”H”, ”e”, ”l”, ”l”, ”o”, ””}; printf(“%s”, greeting); Constructing a String using Double Quotes Instead of constructing a char array of individual char values in single quotation marks, and using “” as the last element, C lets you construct a string by enclosing the characters within double quotation marks. This method of initializing a string is more convenient, as the compiler automatically adds “” as the last character. Example #include <stdio.h> int main() { // Creating string char greeting[] = “Hello World”; // Printing string printf(“%sn”, greeting); return 0; } Output It will produce the following output − Hello World String Input Using scanf() Declaring a null-terminated string causes difficulty if you want to ask the user to input a string. You can accept one character at a time to store in each subscript of an array, with the help of a for loop − Syntax for(i = 0; i < 6; i++){ scanf(“%c”, &greeting[i]); } greeting[i] = ””; Example In the following example, you can input a string using scanf() function, after inputting the specific characters (5 in the following example), we are assigning null (””) to terminate the string. printf(“Starting typing… “); for (i = 0; i < 5; i++) { scanf(“%c”, &greeting[i]); } // Assign NULL manually greeting[i] = ””; // Printing the string printf(“Value of greeting: %sn”, greeting); Output Run the code and check its output − Starting typing… Hello Value of greeting: Hello Example It is not possible to input “” (the null string) because it is a non-printable character. To overcome this, the “%s” format specifier is used in the scanf() statement − #include <stdio.h> #include <string.h> int main (){ char greeting[10]; printf(“Enter a string:n”); scanf(“%s”, greeting); printf(“You entered: n”); printf(“%s”, greeting); return 0; } Output Run the code and check its output − Enter a string: Hello You entered: Hello Note: If the size of the array is less than the length of the input string, then it may result in situations such as garbage, data corruption, etc. String Input with Whitespace scanf(“%s”) reads characters until it encounters a whitespace (space, tab, newline, etc.) or EOF. So, if you try to input a string with multiple words (separated by whitespaces), then the C program would accept characters before the first whitespace as the input to the string. Example Take a look at the following example − #include <stdio.h> #include <string.h> int main (){ char greeting[20]; printf(“Enter a string:n”); scanf(“%s”, greeting); printf(“You entered: n”); printf(“%s”, greeting); return 0; } Output Run the code and check its output − Enter a string: Hello World! You entered: Hello String Input Using gets() and fgets() Functions To accept a string input with
C – nested if statements
C – Nested If Statements ”; Previous Next It is always legal in C programming to nest if-else statements, which means you can use one if or else-if statement inside another if or else-if statement(s). 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. If an if statement in C is employed inside another if statement, then we call it as a nested if statement in C. Syntax The syntax of nested if statements is as follows − if (expr1){ if (expr2){ block to be executed when expr1 and expr2 are true } else{ block to be executed when expr1 is true but expr2 is false } } The following flowchart represents the nesting of if statements − You can compound the Boolean expressions with && or || to get the same effect. However, for more complex algorithms, where there are different combinations of multiple Boolean expressions, it becomes difficult to form the compound conditions. Instead, it is recommended to use nested structures. Another if statement can appear inside a top-level if block, or its else block, or inside both. Example 1 Let us take an example, where the program needs to determine if a given number is less than 100, between 100 to 200, or above 200. We can express this logic with the following compound Boolean expression − #include <stdio.h> int main (){ // local variable definition int a = 274; printf(“Value of a is : %dn”, a); if (a < 100){ printf(“Value of a is less than 100n”); } if (a >= 100 && a < 200){ printf(“Value of a is between 100 and 200n” ); } if (a >= 200){ printf(“Value of a is more than 200n” ); } } Output Run the code and check its output. Here, we have intialized the value of “a” as 274. Change this value and run the code again. If the supplied value is less than 100, then you will get a different output. Similarly, the output will change again if the supplied number is in between 100 and 200. Value of a is : 274 Value of a is more than 200 Example 2 Now let”s use nested conditions for the same problem. It will make the solution more understandable when we use nested conditions. First, check if “a >= 100”. Inside the true part of the if statement, check if it is <200 to decide if the number lies between 100-200, or it is >200. If the first condition (a >= 100) is false, it indicates that the number is less than 100. #include <stdio.h> int main (){ // local variable definition // check with different values 120, 250 and 74 int a = 120; printf(“value of a is : %dn”, a ); // check the boolean condition if(a >= 100){ // this will check if a is between 100-200 if(a < 200){ // if the condition is true, then print the following printf(“Value of a is between 100 and 200n” ); } else{ printf(“Value of a is more than 200n”); } } else{ // executed if a < 100 printf(“Value of a is less than 100n”); } return 0; } Output Run the code and check its output. You will get different outputs for different input values of “a” − Value of a is : 120 Value of a is between 100 and 200 Example 3 The following program uses nested if statements to determine if a number is divisible by 2 and 3, divisible by 2 but not 3, divisible by 3 but not 2, and not divisible by both 2 and 3. #include <stdio.h> int main(){ int a = 15; printf(“a: %dn”, a); if (a % 2 == 0) { if (a % 3 == 0){ printf(“Divisible by 2 and 3”); } else { printf(“Divisible by 2 but not 3”); } } else { if (a % 3 == 0){ printf(“Divisible by 3 but not 2”); } else{ printf(“Not divisible by 2, not divisible by 3″); } } return 0; } Output Run the code and check its output − a: 15 Divisible by 3 but not 2 For different values of “a”, you will get different outputs. Example 4 Given below is a C program to check if a given year is a leap year or not. Whether the year is a leap year or not is determined by the following rules − Is the year divisible by 4? If yes, is it a century year (divisible by 100)? If yes, is it divisible by 400? If yes, it is a leap year, otherwise not. If it is divisible by 4 and not a century year, it is a leap year. If it is not divisible by 4, it is not a leap year. Here is the C code − #include <stdio.h> int main(){ // Test the program with the values 1900, 2023, 2000, 2012 int year = 1900; printf(“year: %dn”, year); // is divisible by 4? if (year % 4 == 0){ // is divisible by 100? if (year % 100 == 0){ // is divisible by 400? if(year % 400 == 0){ printf(“%d is a Leap Yearn”, year); } else{ printf(“%d is not a Leap Yearn”, year); } } else{ printf(“%d is not a Leap Yearn”, year); } } else{ printf(“%d is a Leap Yearn”, year); } } Output Run the code and check its output − year: 1900 1900
C – Pointers to Structures
Pointers to Structures in C ”; Previous Next If you have defined a derived data type using the keyword struct, then you can declare a variable of this type. Hence, you can also declare a pointer variable to store its address. A pointer to struct is thus a variable that refers to a struct variable. Syntax: Defining and Declaring a Structure This is how you will define a new derived data type using the “struct” keyword − struct type { type var1; type var2; type var3; … … }; You can then declare a variable of this derived data type as following − struct type var; You can then declare a pointer variable and store the address of var. To declare a variable as a pointer, it must be prefixed by “*“; and to obtain the address of a variable, we use the “&” operator. struct type *ptr = &var; Accessing the Elements of a Structure To access the elements of a structure with pointer, we use a special operator called the indirection operator (→) . Here, we define a user-defined struct type called book. We declare a book variable and a pointer. struct book{ char title[10]; double price; int pages; }; struct book b1 = {“Learn C”, 675.50, 325}, struct book *strptr; To store the address, use the & operator. strptr = &b1; Using the Indirection Operator In C programming, we use the indirection operator (“→“) with struct pointers. It is also called the “struct dereference operator”. It helps to access the elements of a struct variable to which the pointer references to. To access an individual element in a struct, the indirection operator is used as follows − strptr -> title; strptr -> price; strptr -> pages; The struct pointer uses the indirection operator or the dereference operator to fetch the values of the struct elements of a struct variable. The dot operator (“.“) is used to fetch the values with reference to the struct variable. Hence, b1.title is the same as strpr -> title b1.price is the same as strptr -> price b1.pages is the same as strptr -> pages Example: Pointers to Structures The following program shows the usage of pointers to structures. In this example, “strptr” is a pointer to the variable “struct book b1”. Hence, “strrptr → title” returns the title, similar to “b1.title” does. #include <stdio.h> #include <string.h> struct book{ char title[10]; double price; int pages; }; int main(){ struct book b1 = {“Learn C”, 675.50, 325}; struct book *strptr; strptr = &b1; printf(“Title: %sn”, strptr -> title); printf(“Price: %lfn”, strptr -> price); printf(“No of Pages: %dn”, strptr -> pages); return 0; } Output Title: Learn C Price: 675.500000 No of Pages: 325 Points to Note The dot operator (.) is used to access the struct elements via the struct variable. To access the elements via its pointer, we must use the indirection operator (→). Example Let”s consider another example to understand how pointers to structures actually work. Here, we will use the keyword struct to define a new derived data type called person and then we will declare a variable of its type and a pointer. The user is asked to input the name, age and weight of the person. The values are stored in the structure elements by accessing them with the indirection operator. #include <stdio.h> #include <string.h> struct person{ char *name; int age; float weight; }; int main(){ struct person *personPtr, person1; strcpy(person1.name, “Meena”); person1.age = 40; person1.weight = 60; personPtr = &person1; printf(“Displaying the Data: n”); printf(“Name: %sn”, personPtr -> name); printf(“Age: %dn”, personPtr -> age); printf(“Weight: %f”, personPtr -> weight); return 0; } Output When you runt this program, it will produce the following output − Displaying the Data: Name: Meena Age: 40 weight: 60.000000 C allows you to declare an “array of struct” as well as an “array of pointers”. Here, each element in the struct pointer array is a reference to a struct variable. A struct variable is like a normal variable of primary type, in the sense that you can have an array of struct, you can pass the struct variable to a function, as well as return a struct from a function. Note: You need to prefix “struct type” to the name of the variable or pointer at the time of declaration. However, you can avoid it by creating a shorthand notation using the typedef keyword. Why Do We Need Pointers to Structures? Pointers to structures are very important because you can use them to create complex and dynamic data structures such as linked lists, trees, graphs, etc. Such data structures use self-referential structs, where we define a struct type having one of its elements as a pointer to the same type. An example of a self-referential structure with a pointer to an element of its own type is defined as follows − struct mystruct{ int a; struct mystruct *b; }; We shall learn about self-referential structures in the next chapter. Print Page Previous Next Advertisements ”;
C – Variable Length Arrays
Variable Length Arrays in C ”; Previous Next A variable length array in C is also called a variable-sized or runtime-sized array. It is an array whose length is determined at the runtime rather than at the time of compiling the program. Its size depends on a value generated during the runtime of a program, usually received as an input from the user. Usually, the array size is declared beforehand in the program as follows − int arr[10]; The size of an array, once declared, remains fixed during the execution of a program and cannot be changed during its runtime. However, in case of a Variable Length Array (VLA), the compiler allocates the memory with automatic storage duration on the stack. The support for VLAs was added in the C99 standard. Creating a Variable Length Array The syntax for creating a variable length arrays is as follows − void arr_init(int length){ int arr[length]; //code using arr; }; Example The following example demonstrates how you can create a variable length array − #include <stdio.h> int main(){ int i, j; int size; // variable to hold size of one-dimensional array printf(“Enter the size of one-dimensional array: “); scanf(“%d”, &size); int arr[size]; for(i = 0; i < size; ++i){ printf(“Enter a number: “); scanf(“%d”, &j); arr[i] = j; } for(i = 0; i < size; ++i) printf(“a[%d]: %dn”, i, arr[i]); return 0; } Output When you run this code, it will ask you enter the size of the array. Notice that the length of the array is not fixed at the time of declaration. You define its size at runtime. Enter the size of one-dimensional array: 5 Enter a number: 1 Enter a number: 5 Enter a number: 7 Enter a number: 8 Enter a number: 7 a[0]: 1 a[1]: 5 a[2]: 7 a[3]: 8 a[4]: 7 Two-dimensional Variable Length Arrays We can also declare and use a two-dimensional variable length array. Example 1 Take a look at the following example − #include <stdio.h> int main(){ int i, j, x; int row, col; // number of rows & columns of two D array printf(“Enter number of rows & columns of 2-D array:n”); scanf(“%d %d”, &row, &col); int arr2D[row][col]; for(i = 0; i < row; ++i){ for(j = 0; j < col; ++j){ printf(“Enter a number: “); scanf(“%d”, &x); arr2D[i][j] = x; } } for(i = 0; i < row; ++i){ printf(“n”); for(j = 0; j < col; ++j) printf(“%dt”, arr2D[i][j]); } return 0; } Output Run the code and check its output − Enter number of rows & columns of 2-D array: 2 3 Enter a number: 10 Enter a number: 20 Enter a number: 30 Enter a number: 40 Enter a number: 50 Enter a number: 60 10 20 30 40 50 60 Example 2 The following code declares a variable length one-dimensional array and populates it with incrementing numbers − #include <stdio.h> int main(){ int n; printf(“Enter the size of the array: n”); scanf(“%d”, &n); int arr[n]; for(int i = 0; i < n; i++) arr[i] = i+1; printf(“The array elements are: “); for(int i = 0; i < n; i++) printf(“%d “, arr[i]); return 0; } Output Run the code and check its output − Enter the size of the array: 5 The array elements are: 1 2 3 4 5 …. Example 3 The following code fills the variable length array with randomly generated numbers using the functions srand() and rand() from the stdlib.h header file. #include <stdio.h> #include <stdlib.h> #include <time.h> void oneDArray(int length, int a[length]); // function prototype void twoDArray(int row, int col, int a[row][col]); // function prototype int main(){ int i, j; // counter variable int size; // variable to hold size of one dimensional array int row, col; // number of rows & columns of two D array srand(time(NULL)); printf(“Enter the size of one-dimensional array: “); scanf(“%d”, &size); printf(“Enter the number of rows & columns of 2-D array:n”); scanf(“%d %d”, &row, &col); // declaring arrays int arr[size]; // 2-D array int arr2D[row][col]; // one dimensional array for(i = 0; i < size; ++i){ arr[i] = rand() % 100 + 1; } // two dimensional array for(i = 0; i < row; ++i){ for(j = 0; j < col; ++j){ arr2D[i][j] = rand() % 100 + 1; } } // printing arrays printf(“One-dimensional array:n”); // oneDArray(size, arr); for(i = 0; i < size; ++i) printf(“a[%d]: %dn”, i, arr[i]); printf(“nTwo-dimensional array:n”); // twoDArray(row1, col1, arr2D); for(i = 0; i < row; ++i){ printf(“n”); for (j = 0; j < col; ++j) printf(“%5d”, arr2D[i][j]); } } Output Run the code and check its output − Enter the size of one-dimensional array: 5 Enter the number of rows & columns of 2-D array: 4 4 One-dimensional array: a[0]: 95 a[1]: 93 a[2]: 4 a[3]: 52 a[4]: 68 Two-dimensional array: 92 19 79 23 56 21 44 98 8 22 89 54 93 1 63 38 Jagged Array A jagged array is a collection of two or more arrays of similar data types of variable length. In C, the concept of jagged array is implemented with the help of pointers of arrays. A jagged array is represented by the following figure − Example In this program, we declare three one-dimensional arrays of different sizes and store their pointers in an array of pointers that acts as a jagged array. #include <stdio.h> int