Functions in C ”; Previous Next A function in C is a block of organized reusuable code that is performs a single related action. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions. When the algorithm of a certain problem involves long and complex logic, it is broken into smaller, independent and reusable blocks. These small blocks of code are known by different names in different programming languages such as a module, a subroutine, a function or a method. You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task. A function declaration tells the compiler about a function”s name, return type, and parameters. A function definition provides the actual body of the function. The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions. Modular Programming in C Functions are designed to perform a specific task that is a part of an entire process. This approach towards software development is called modular programming. Modular programming takes a top-down approach towards software development. The programming solution has a main routine through which smaller independent modules (functions) are called upon. Each function is a separate, complete and reusable software component. When called, a function performs a specified task and returns the control back to the calling routine, optionally along with result of its process. The main advantage of this approach is that the code becomes easy to follow, develop and maintain. Library Functions in C C offers a number of library functions included in different header files. For example, the stdio.h header file includes printf() and scanf() functions. Similarly, the math.h header file includes a number of functions such as sin(), pow(), sqrt() and more. These functions perform a predefined task and can be called upon in any program as per requirement. However, if you don”t find a suitable library function to serve your purpose, you can define one. Defining a Function in C In C, it is necessary to provide the forward declaration of the prototype of any function. The prototype of a library function is present in the corresponding header file. For a user-defined function, its prototype is present in the current program. The definition of a function and its prototype declaration should match. After all the statements in a function are executed, the flow of the program returns to the calling environment. The function may return some data along with the flow control. Function Declarations in C A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts − return_type function_name(parameter list); For the above defined function max(), the function declaration is as follows − int max(int num1, int num2); Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration − int max(int, int); A function declaration is required when you define a function in one source file and you call that function in another file. In such cases, you should declare the function at the top of the file calling the function. Parts of a Function in C The general form of a function definition in C programming language is as follows − return_type function_name(parameter list){ body of the function } A function definition in C programming consists of a function header and a function body. Here are all the parts of a function − Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Argument List − An argument (also called parameter) is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body − The function body contains a collection of statements that defines what the function does. A function in C should have a return type. The type of the variable returned by the function must be the return type of the function. In the above figure, the add() function returns an int type. Example: User-defined Function in C In this program, we have used a user-defined function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two − #include <stdio.h> /* function returning the max between two numbers */ int max(int num1, int num2){ /* local variable declaration */ int result; if(num1 > num2) result = num1; else result = num2; return result; } int main(){ printf(“Comparing two numbers using max() function: n”); printf(“Which of the two, 75 or 57, is greater than the other? n”); printf(“The answer is: %d”, max(75, 57)); return 0; } Output When you runt this code, it will produce the following output − Comparing two numbers using max() function: Which of the two, 75 or 57, is greater
Category: cprogramming
C – Arrays
Arrays in C ”; Previous Next Arrays in C are a kind of data structure that can store a fixed-size sequential collection of elements of the same data type. Arrays are used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. What is an Array in C? An array in C is a collection of data items of similar data type. One or more values same data type, which may be primary data types (int, float, char), or user-defined types such as struct or pointers can be stored in an array. In C, the type of elements in the array should match with the data type of the array itself. The size of the array, also called the length of the array, must be specified in the declaration itself. Once declared, the size of a C array cannot be changed. When an array is declared, the compiler allocates a continuous block of memory required to store the declared number of elements. Why Do We Use Arrays in C? Arrays are used to store and manipulate the similar type of data. Suppose we want to store the marks of 10 students and find the average. We declare 10 different variables to store 10 different values as follows − int a = 50, b = 55, c = 67, . . . ; float avg = (float)(a + b + c +. . . ) / 10; These variables will be scattered in the memory with no relation between them. Importantly, if we want to extend the problem of finding the average of 100 (or more) students, then it becomes impractical to declare so many individual variables. Arrays offer a compact and memory-efficient solution. Since the elements in an array are stored in adjacent locations, we can easily access any element in relation to the current element. As each element has an index, it can be directly manipulated. Example: Use of an Array in C To go back to the problem of storing the marks of 10 students and find the average, the solution with the use of array would be − #include <stdio.h> int main(){ int marks[10] = {50, 55, 67, 73, 45, 21, 39, 70, 49, 51}; int i, sum = 0; float avg; for (i = 0; i <= 9; i++){ sum += marks[i]; } avg = (float)sum / 10; printf(“Average: %f”, avg); return 0; } Output Run the code and check its output − Average: 52.000000 Array elements are stored in contiguous memory locations. Each element is identified by an index starting with “0”. The lowest address corresponds to the first element and the highest address to the last element. Declaration of an Array in C To declare an array in C, you need to specify the type of the elements and the number of elements to be stored in it. Syntax to Declare an Array type arrayName[size]; The “size” must be an integer constant greater than zero and its “type” can be any valid C data type. There are different ways in which an array is declared in C. Example: Declaring an Array in C In the following example, we are declaring an array of 5 integers and printing the indexes and values of all array elements − #include <stdio.h> int main(){ int arr[5]; int i; for (i = 0; i <= 4; i++){ printf(“a[%d]: %dn”, i, arr[i]); } return 0; } Output Run the code and check its output − a[0]: -133071639 a[1]: 32767 a[2]: 100 a[3]: 0 a[4]: 4096 Initialization of an Array in C At the time of declaring an array, you can initialize it by providing the set of comma-separated values enclosed within the curly braces {}. Syntax to Initialize an Array data_type array_name [size] = {value1, value2, value3, …}; Example to Initialize an Array The following example demonstrates the initialization of an integer array: // Initialization of an integer array #include <stdio.h> int main() { int numbers[5] = {10, 20, 30, 40, 50}; int i; // loop counter // Printing array elements printf(“The array elements are : “); for (i = 0; i Output The array elements are : 10 20 30 40 50 Example of Initializing all Array Elements to 0 To initialize all elements to 0, put it inside curly brackets #include <stdio.h> int main(){ int arr[5] = {0}; int i; for(i = 0; i <= 4; i++){ printf(“a[%d]: %dn”, i, arr[i]); } return 0; } Output When you run this code, it will produce the following output − a[0]: 0 a[1]: 0 a[2]: 0 a[3]: 0 a[4]: 0 Example of Partial Initialization of an Array If the list of values is less than the size of the array, the rest of the elements are initialized with “0”. #include <stdio.h> int main(){ int arr[5] = {1,2}; int i; for(i = 0; i <= 4; i++){ printf(“a[%d]: %dn”, i, arr[i]); } return 0; } Output When you run this code, it will produce the following output − a[0]: 1 a[1]: 2 a[2]: 0 a[3]: 0 a[4]: 0 Example of Partial and Specific Elements Initialization If an array is partially initialized, you can specify the element in the square brackets. #include <stdio.h> int main(){ int a[5] = {1,2, [4] = 4}; int i; for(i = 0; i <= 4; i++){ printf(“a[%d]: %dn”, i, a[i]); } return 0; } Output On execution, it will
C – if…else statement
C – The if-else Statement ”; Previous Next The if-else statement is one of the frequently used decision-making statements in C. The if-else statement offers an alternative path when the condition isn”t met. The else keyword helps you to provide an alternative course of action to be taken when the Boolean expression in the if statement turns out to be false. The use of else keyword is optional; it”s up to you whether you want to use it or not. Syntax of if-else Statement Here is the syntax of if-else clause − if (Boolean expr){ Expression; . . . } else{ Expression; . . . } The C compiler evaluates the condition, and executes a statement or a block of statements following the if statement if it is true. If the programming logic needs the computer to execute some other instructions when the condition is false, they are put as a part of the else clause. An if statement is followed by an optional else statement, which executes when the Boolean expression is false. Flowchart of if-else Statement The following flowchart represents how the if-else clause works in C − Note that the curly brackets in the if as well as the else clause are necessary if you have more than one statements to be executed. For example, in the following code, we don’t need curly brackets. if (marks<50) printf(“Result: Failn”); else printf(“Result: Passn”); However, when there are more than one statements, either in the if or in the else part, you need to tell the compiler that they need to be treated as a compound statement. C if-else Statement Examples Example: Tax Calculation Using if-else Statement In the code given below, the tax on employee’s income is computed. If the income is below 10000, the tax is applicable at 10%. For the income above 10000, the excess income is charged at 15%. #include <stdio.h> int main() { int income = 5000; float tax; printf(“Income: %dn”, income); if (income<10000){ tax = (float)(income * 10 / 100); printf(“tax: %f n”, tax); } else { tax= (float)(1000 + (income-10000) * 15 / 100); printf(“tax: %f”, tax); } } Output Run the code and check its output − Income: 5000 tax: 500.000000 Set the income variable to 15000, and run the program again. Income: 15000 tax: 1750.000000 Example: Checking Digit Using if-else Statement The following program checks if a char variable stores a digit or a non-digit character. #include <stdio.h> int main() { char ch=”7”; if (ch>=48 && ch<=57){ printf(“The character is a digit.”); } else{ printf(“The character is not a digit.”); } return 0; } Output Run the code and check its output − The character is a digit. Assign any other character such as “*” to “ch” and see the result. The character is not a digit. Example: if-else Statement Without Curly Braces Consider the following code. It intends to calculate the discount at 10% if the amount is greater than 100, and no discount otherwise. #include <stdio.h> int main() { int amount = 50; float discount; printf(“Amount: %dn”, amount); if (amount >= 100) discount = amount * 10 / 100; printf(“Discount: %f n”, discount); else printf(“Discount not applicablen”); return 0; } Output The program shows the following errors during the compilation − error: ”else” without a previous ”if” The compiler will execute the first statement after the if clause and assumes that since the next statement is not else (it is optional anyway), the subsequent printf() statement is unconditional. However, the next else is not connected to any if statement, hence the error. Example: if-else Statement Without Curly Braces Consider the following code too − #include <stdio.h> int main() { int amount = 50; float discount, nett; printf(“Amount: %dn”, amount); if (amount<100) printf(“Discount not applicablen”); else printf(“Discount applicable”); discount = amount*10/100; nett = amount – discount; printf(“Discount: %f Net payable: %f”, discount, nett); return 0; } Output The code doesn’t give any compiler error, but gives incorrect output − Amount: 50 Discount not applicable Discount: 5.000000 Net payable: 45.000000 It produces an incorrect output because the compiler assumes that there is only one statement in the else clause, and the rest of the statements are unconditional. The above two code examples emphasize the fact that when there are more than one statements in the if or else else, they must be put in curly brackets. To be safe, it is always better to use curly brackets even for a single statement. In fact, it improves the readability of the code. The correct solution for the above problem is shown below − if (amount >= 100){ discount = amount * 10 / 100; printf(“Discount: %f n”, discount); } else { printf(“Discount not applicablen”); } The else-if Statement in C C also allows you to use else-if in the programs. Let”s see where you may have to use an else-if clause. Let”s suppose you have a situation like this. If a condition is true, run the given block that follows. If it isn”t, run the next block instead. However, if none of the above is true and all else fails, finally run another block. In such cases, you would use an else-if clause. Syntax of else-if Statement Here is the syntax of the else-if clause − if (condition){ // if the condition is true, // then run this code } else if(another_condition){ // if the above condition was false // and this condition is true, // then run the code in this block }
C – Continue Statement
Continue Statement in C ”; Previous Next The behaviour of continue statement in C is somewhat opposite to the break statement. Instead of forcing the termination of a loop, it forces the next iteration of the loop to take place, skipping the rest of the statements in the current iteration. What is Continue Statement in C? The continue statement is used to skip the execution of the rest of the statement within the loop in the current iteration and transfer it to the next loop iteration. It can be used with all the C language loop constructs (while, do while, and for). Continue Statement Syntax The continue statement is used as per the following structure − while (expr){ . . . . . . if (condition) continue; . . . } Continue Statement Flowchart The following flowchart represents how continue works − You must use the continue statement inside a loop. If you use a continue statement outside a loop, then it will result in compilation error. Unlike the break statement, continue is not used with the switch-case statement. Continue Statement with Nested Loops In case of nested loops, continue will continue the next iteration of the nearest loop. The continue statement is often used with if statements. Continue Statement Examples Example: Continue Statement with While Loop In this program the loop generates 1 to 10 values of the variable “i”. Whenever it is an even number, the next iteration starts, skipping the printf statement. Only the odd numbers are printed. #include <stdio.h> int main(){ int i = 0; while (i < 10){ i++; if(i%2 == 0) continue; printf(“i: %dn”, i); } } Output i: 1 i: 3 i: 5 i: 7 i: 9 Example: Continue Statement with For Loop The following program filters out all the vowels in a string − #include <stdio.h> #include <string.h> int main () { char string[] = “Welcome to TutorialsPoint C Tutorial”; int len = strlen(string); int i; printf(“Given string: %sn”, string); printf(“after removing the vowelsn”); for (i=0; i<len; i++){ if (string[i]==”a” || string[i]==”e” || string[i] == ”i” || string[i] == ”o” || string[i] == ”u”) continue; printf(“%c”, string[i]); } return 0; } Output Run the code and check its output − Given string: Welcome to TutorialsPoint C Tutorial after removing the vowels Wlcm t TtrlsPnt C Ttrl Example: Continue Statement with Nested Loops If a continue statement appears inside an inner loop, the program control jumps to the beginning of the corresponding loop. In the example below, there are three for loops one inside the other. These loops are controlled by the variables i, j, and k respectively. The innermost loop skips the printf statement if k is equal to either i or j, and goes to its next value of k. The second j loop executes the continue when it equals i. As a result, all the unique combinations of three digits 1, 2 and 3 are displayed. #include <stdio.h> int main (){ int i, j, k; for(i = 1; i <= 3; i++){ for(j = 1; j <= 3; j++){ if (i == j) continue; for (k=1; k <= 3; k++){ if (k == j || k == i) continue; printf(“%d %d %d n”, i,j,k); } } } return 0; } Output Run the code and check its output − 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 Example: Removing Spaces Between Words in a String The following code detects the blankspaces between the words in a string, and prints each word on a different line. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> int main(){ char string[] = “Welcome to TutorialsPoint C Tutorial”; int len = strlen(string); int i; printf(“Given string: %sn”, string); for (i = 0; i < len; i++){ if (string[i] == ” ”){ printf(“n”); continue; } printf(“%c”, string[i]); } return 0; } Output On executing this code, you will get the following output − Given string: Welcome to TutorialsPoint C Tutorial Welcome to TutorialsPoint C Tutorial Example: Finding Prime Factors of a Number One of the cases where the continue statement proves very effective is in the problem of writing a program to find prime factors of a given number. The algorithm of this program works like this − The given number is successively divided by numbers starting with 2. If the number is divisible, the given number is reduced to the division, and the resultant number is checked for divisibility with 2 until it is no longer divisible. If not by 2, the process is repeated for all the odd numbers starting with 3. The loop runs while the given number reduces to 1. Here’s the program to find the prime factors − #include <stdio.h> int main (){ int n = 64; int i, m = 2; printf(“Prime factors of %d: n”, n); while (n > 1){ if (n % m == 0){ n = n/m; printf(“%d “, m); continue; } if (m == 2) m++; else m = m+2; } return 0; } Output Here, the given number is 64. So, when you run this code, it will produce the following output − Prime factors of 64: 2 2 2 2 2 2 Change the number to 45 and then 90. Run the code again. Now you will get the following outputs − Prime factors of 45: 3 3 5 Prime factors of 90: 2 3 3 5 c_loops.htm
C – Infinite loop
C – Infinite Loop ”; Previous Next In C language, an infinite loop (or, an endless loop) is a never-ending looping construct that executes a set of statements forever without terminating the loop. It has a true condition that enables a program to run continuously. Flowchart of an Infinite Loop If the flow of the program is unconditionally directed to any previous step, an infinite loop is created, as shown in the following flowchart − An infinite loop is very rarely created intentionally. In case of embedded headless systems and server applications, the application runs in an infinite loop to listen to the client requests. In other circumstances, infinite loops are mostly created due to inadvertent programming errors. How to Create an Infinite Loop in C? To create an infinite loop, you need to use one of the loop constructs (while, do while, or for) with a non-zero value as a test condition. Generally, 1 is used as the test condition, you can use any non-zero value. A non-zero value is considered as true. Example #include <stdio.h> int main() { while (1) { printf(“Hello World”); } return 0; } Hello WorldHello WorldHello WorldHello WorldHello WorldHello World Hello WorldHello WorldHello WorldHello WorldHello WorldHello World Hello WorldHello WorldHello … Types of Infinite Loops in C In C language, infinite while, infinite do while, and infinite for are the three infinite loops. These loops execute the code statement continuously. Let us understand the implementation of infinite loops using all loop constructs. Infinite While Loop The while keyword is used to form a counted loop. The loop is scheduled to repeat till the value of some variable successively increments to a predefined value. However, if the programmer forgets to put the increment statement within the loop body, the test condition doesn’t arrive at all, hence it becomes endless or infinite. Example 1 Take a look at the following example − #include <stdio.h> // infinite while loop int main(){ int i = 0; while (i <= 10){ // i++; printf(“i: %dn”, i); } return 0; } Output Since the increment statement is commented out here, the value of “i” continues to remain “0”, hence the output shows “i: 0” continuously until you forcibly stop the execution. i: 0 i: 0 i: 0 … … Example 2 The parenthesis of while keyword has a Boolean expression that initially evaluates to True, and is eventually expected to become False. Note that any non-zero number is treated as True in C. Hence, the following while loop is an infinite loop: #include <stdio.h> // infinite while loop int main(){ while(1){ printf(“Hello World n”); } return 0; } Output It will keep printing “Hello World” endlessly. Hello World Hello World Hello World … … The syntax of while loop is as follows − while (condition){ . . . . . . } Note that the there is no semicolon symbol in front of while, indicating that the following code block (within the curly brackets) is the body of the loop. If we place a semicolon, the compiler treats this as a loop without body, and hence the while condition is never met. Example 3 In the following code, an increment statement is put inside the loop block, but because of the semicolon in front of while, the loop becomes infinite. #include <stdio.h> // infinite while loop int main(){ int i = 0; while(i < 10);{ i++; printf(“Hello World n”); } return 0; } Output When the program is run, it won”t print the message “Hello World”. There is no output because the while loop becomes an infinite loop with no body. Infinite For Loop The for loop in C is used for performing iteration of the code block for each value of a variable from its initial value to the final value, incrementing it on each iteration. Take a look at its syntax − for (initial val; final val; increment){ . . . . . . } Example 1 Note that all the three clauses of the for statement are optional. Hence, if the middle clause that specifies the final value to be tested is omitted, the loop turns infinite. #include <stdio.h> // infinite for loop int main(){ int i; for(i=1; ; i++){ i++; printf(“Hello World n”); } return 0; } Output The program keeps printing Hello World endlessly until you stop it forcibly, because it has no effect of incrementing “i” on each turn. Hello World Hello World Hello World … … You can also construct a for loop for decrementing the values of a looping variable. In that case, the initial value should be greater than the final test value, and the third clause in for must be a decrement statement (using the “–” operator). If the initial value is less than the final value and the third statement is decrement, the loop becomes infinite. The loop still becomes infinite if the initial value is larger but you mistakenly used an increment statement. Hence, both the for loops result in an infinite loop. Example 2 Take a look at the following example − #include <stdio.h> int main(){ // infinite for loop for(int i = 10; i >= 1; i++){ i++; printf(“Hello World n”); } } Output The program will print a series of “Hello World” in an infinite loop − Hello World Hello World Hello World … … Example 3 Take a look at the following example −
C – Pointers and Arrays
Pointers and Arrays in C ”; Previous Next In C programming, the concepts of arrays and pointers have a very important role. There is also a close association between the two. In this chapter, we will explain in detail the relationship between arrays and pointers in C programming. Arrays in C An array in C is a homogenous collection of elements of a single data type stored in a continuous block of memory. The size of an array is an integer inside square brackets, put in front of the name of the array. Declaring an Array To declare an array, the following syntax is used − data_type arr_name[size]; Each element in the array is identified by a unique incrementing index, starting from “0”. An array can be declared and initialized in different ways. You can declare an array and then initialize it later in the code, as and when required. For example − int arr[5]; … … a[0] = 1; a[1] = 2; … … You can also declare and initialize an array at the same time. The values to be stored are put as a comma separated list inside curly brackets. int a[5] = {1, 2, 3, 4, 5}; Note: When an array is initialized at the time of declaration, mentioning its size is optional, as the compiler automatically computes the size. Hence, the following statement is also valid − int a[] = {1, 2, 3, 4, 5}; Example: Lower Bound and Upper Bound of an Array All the elements in an array have a positional index, starting from “0”. The lower bound of the array is always “0”, whereas the upper bound is “size − 1”. We can use this property to traverse, assign, or read inputs into the array subscripts with a loop. Take a look at this following example − #include <stdio.h> int main(){ int a[5], i; for(i = 0; i <= 4; i++){ scanf(“%d”, &a[i]); } for(i = 0; i <= 4; i++){ printf(“a[%d] = %dn”,i, a[i]); } return 0; } Output Run the code and check its output − a[0] = 712952649 a[1] = 32765 a[2] = 100 a[3] = 0 a[4] = 4096 Pointers in C A pointer is a variable that stores the address of another variable. In C, the symbol (&) is used as the address-of operator. The value returned by this operator is assigned to a pointer. To declare a variable as a pointer, you need to put an asterisk (*) before the name. Also, the type of pointer variable must be the same as the type of the variable whose address it stores. In this code snippet, “b” is an integer pointer that stores the address of an integer variable “a” − int a = 5; int *b = &a; In case of an array, you can assign the address of its 0th element to the pointer. int arr[] = {1, 2, 3, 4, 5}; int *b = &arr[0]; In C, the name of the array itself resolves to the address of its 0th element. It means, in the above case, we can use “arr” as equivalent to “&[0]”: int *b = arr; Example: Increment Operator with Pointer Unlike a normal numeric variable (where the increment operator “++” increments its value by 1), the increment operator used with a pointer increases its value by the sizeof its data type. Hence, an int pointer, when incremented, increases by 4. #include <stdio.h> int main(){ int a = 5; int *b = &a; printf(“Address of a: %dn”, b); b++; printf(“After increment, Address of a: %dn”, b); return 0; } Output Run the code and check its output − Address of a: 6422036 After increment, Address of a: 6422040 The Dereference Operator in C In C, the “*” symbol is used as the dereference operator. It returns the value stored at the address to which the pointer points. Hence, the following statement returns “5”, which is the value stored in the variable “a”, the variable that “b” points to. int a = 5; int *b = &a; printf(“value of a: %dn”, *b); Note: In case of a char pointer, it will increment by 1; in case of a double pointer, it will increment by 8; and in case of a struct type, it increments by the sizeof value of that struct type. Example: Traversing an Array Using a Pointer We can use this property of the pointer to traverse the array element with the help of a pointer. #include <stdio.h> int main(){ int arr[5] = {1, 2, 3, 4, 5}; int *b = arr; printf(“Address of a[0]: %d value at a[0] : %dn”,b, *b); b++; printf(“Address of a[1]: %d value at a[1] : %dn”, b, *b); b++; printf(“Address of a[2]: %d value at a[2] : %dn”, b, *b); b++; printf(“Address of a[3]: %d value at a[3] : %dn”, b, *b); b++; printf(“Address of a[4]: %d value at a[4] : %dn”, b, *b); return 0; } Output Run the code and check its output − address of a[0]: 6422016 value at a[0] : 1 address of a[1]: 6422020 value at a[1] : 2 address of a[2]: 6422024 value at a[2] : 3 address of a[3]: 6422028 value at a[3] : 4 address of a[4]: 6422032 value at a[4] : 5 Points to Note It may be noted that − “&arr[0]” is equivalent to “b” and “arr[0]” to “*b”. Similarly, “&arr[1]” is equivalent to “b + 1” and “arr[1]” is equivalent to
C – Main Function
C – Main Function ”; Previous Next main() Function in C The main() function in C is an entry point of any program. The program execution starts with the main() function. It is designed to perform the main processing of the program and clean up any resources that were allocated by the program. In a C code, there may be any number of functions, but it must have a main() function. Irrespective of its place in the code, it is the first function to be executed. Syntax The following is the syntax of the main() function in C language − int main(){ //one or more statements; return 0; } Syntax Explained As a part of its syntax, a function has a name that follows the rules of forming an identifier (starting with an alphabet or underscore and having alphabet, digit or underscore). The name is followed by a parenthesis. Typically, the main() function is defined with no arguments, although it may have argv and argv argument to receive values from the command line. Valid/Different Signatures of main() Function The signatures (prototype) of a main() function are − int main() { . . return 0; } Or int main(void){ . . return 0; } Or int main(int argc, char *argv[]){ . . return 0; } Example of main() Function The following example demonstrates the main() function: #include <stdio.h> int main() { // Write code from here printf(“Hello World”); return 0; } Important Points about main() Function A C program must have a main() function. The main is not a C keyword.It is classified as a user-defined function because its body is not pre−decided, it depends on the processing logic of the program.By convention, int is the return type of main(). The last statement in the function body of main() returns 0, to indicate that the function has been successfully executed. Any non−zero return value indicates failure. Some old C compilers let you define main() function with void return type. However, this is considered to be non−standard and is not recommended. As compared to other functions, the main() function: Can”t be declared as inline. Can”t be declared as static. Can”t have its address taken. Can”t be called from your program. How does main() Works in C? The program”s execution starts from the main() function as it is an entry point of the program, it starts executing the statements written inside it. Other functions within the source program are defined to perform certain task. The main function can call any of these functions. When main calls another function, it passes execution control to the function, optionally passing the requisite number and type of arguments, so that execution begins at the first statement in the called function. The called function returns control to main when a return statement is executed or when the end of the function is reached. Note that return statement is implicitly present as the last statement when its return type is int. A program usually stops executing when it returns from or reaches the end of main, although it can terminate at other points in the program for various reasons. For example, you may want to force the termination of your program when some error condition is detected. To do so, you can use the exit function. Use of exit() in main() Function The C exit() function is a standard library function used to terminate the calling process. Use exit(0) to indicate no error, and exit(1) to indicate that the program is exiting with because of an error encountered. Example #include <stdio.h> #include <stdlib.h> int add(int, int); int main (){ int i; for ( i = 1; i<=5; i++){ if ( i == 3 ){ printf (” n exiting ..”); exit(0); } else printf (” n Number is %d”, i); } return 0; } Output Number is 1 Number is 2 exiting .. Command-line Arguments with main() Typically, the main() function is defined without any arguments. However, you may define main() with arguments to let it accept the values from the command line. In this type of usage, main() function is defined as follows − Syntax The following is the syntax of main() function with command-line arguments: int main(int argc, char *argv[]){ . . return 0; } Argument Definitions The argument definitions are as follows − argc − The first argument is an integer that contains the count of arguments that follow in argv. The argc parameter is always greater than or equal to 1. argv − The second argument is an array of null−terminated strings representing command-line arguments entered by the user of the program. By convention, argv[0] is the command with which the program is invoked. argv[1] is the first command−line argument. The last argument from the command line is argv[argc − 1], and argv[argc] is always NULL. Example: Using main() Function with Command-line Arguments Consider the following program to understand command−line arguments. #include <stdio.h> #include <stdlib.h> int add(int, int); int main (int argc, char *argv[]){ int x, y, z; if (argc<3){ printf(“insufficient arguments”); } else{ x = atoi(argv[1]); y = atoi(argv[2]); z = x+y; printf(“addition : %d”, z); } return 0; } Just compile and build the program as test.c, donât run from the IDE in which you have edited and compiled. Go to the command prompt and run the program as follows − C:Usersmlath>test 10 20 addition : 30 In this chapter, we learned the importance and syntax of defining a main() function in C. Any C program must have a main() function. As a
C – Break Statement
Break Statement in C ”; Previous Next The break statement in C is used in two different contexts. In switch-case, break is placed as the last statement of each case block. The break statement may also be employed in the body of any of the loop constructs (while, do–while as well as for loops). When used inside a loop, break causes the loop to be terminated. In the switch-case statement, break takes the control out of the switch scope after executing the corresponding case block. Flowchart of Break Statement in C The flowchart of break in loop is as follows − The following flowchart shows how to use break in switch-case − In both the scenarios, break causes the control to be taken out of the current scope. Break Statements in While Loops The break statement is never used unconditionally. It always appears in the True part of an if statement. Otherwise, the loop will terminate in the middle of the first iteration itself. while(condition1){ . . . . . . if(condition2) break; . . . . . . } Example of break Statement with while Loop The following program checks if a given number is prime or not. A prime number is not divisible by any other number except itself and 1. The while loop increments the divisor by 1 and tries to check if it is divisible. If found divisible, the while loop is terminated. #include <stdio.h> /*break in while loop*/ int main () { int i = 2; int x = 121; printf(“x: %dn”, x); while (i < x/2){ if (x % i == 0) break; i++; } if (i >= x/2) printf(“%d is prime”, x); else printf(“%d is not prime”, x); return 0; } Output On executing this code, you will get the following output − x: 121 121 is not prime Now, change the value of “x” to 25 and run the code again. It will produce the following output − x: 25 25 is not prime Break Statements in For Loops You can use a break statement inside a for loop as well. Usually, a for loop is designed to perform a certain number of iterations. However, sometimes it may be required to abandon the loop if a certain condition is reached. The usage of break in for loop is as follows − for (init; condition; increment) { . . . if (condition) break; . . . } Example of break Statement with for Loop The following program prints the characters from a given string before a vowel (a, e, I, or u) is detected. #include <stdio.h> #include <string.h> int main () { char string[] = “Rhythmic”; int len = strlen(string); int i; for (i = 0; i < len; i++){ if (string[i] == ”a” || string[i] == ”e” || string[i] == ”i” || string[i] == ”o” || string[i] == ”u”) break; printf(“%cn”, string[i]); } return 0; } Output Run the code and check its output − R h y t h m If break appears in an inner loop of a nested loop construct, it abandons the inner loop and continues the iteration of the outer loop body. For the next iteration, it enters the inner loop again, which may be broken again if the condition is found to be true. Example of break Statement with Nested for Loops In the following program, two nested loops are employed to obtain a list of all the prime numbers between 1 to 30. The inner loop breaks out when a number is found to be divisible, setting the flag to 1. After the inner loop, the value of flag is checked. If it is “0”, the number is a prime number. #include <stdio.h> int main(){ int i, num, n, flag; printf(“The prime numbers in between the range 1 to 30:n”); for(num = 2; num <= 30; num++){ flag = 0; for(i = 2; i <= num/2; i++){ if(num % i == 0){ flag++; break; } } if(flag == 0) printf(“%d is primen”,num); } return 0; } Output 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime Break Statement in an Infinite Loop An infinite loop is rarely created intentionally. However, in some cases, you may start an infinite loop and break from it when a certain condition is reached. Example of break Statement with Infinite Loop In the following program, an infinite for loop is used. On each iteration, a random number between 1 to 100 is generated till a number that is divisible by 5 is obtained. #include <stdio.h> #include <stdlib.h> #include <time.h> int main(){ int i, num; printf (“Program to get the random number from 1 to 100: n”); srand(time(NULL)); for (; ; ){ num = rand() % 100 + 1; // random number between 1 to 100 printf (” %dn”, num); if (num%5 == 0) break; } } Output On running this code, you will get an output like the one shown here − Program to get the random number from 1 to 100: 6 56 42 90 Break Statements in Switch Case To transfer the control out of the switch scope, every case block ends with a break statement. If not, the program falls through all the case blocks, which is not desired. Example of break Statement with switch In the following code, a series of if-else statements print three different greeting messages based on the value of a
C – While loop
C – While Loop ”; Previous Next In C, while is one of the keywords with which we can form loops. The while loop is one of the most frequently used types of loops in C. The other looping keywords in C are for and do-while. The while loop is often called the entry verified loop, whereas the do-while loop is an exit verified loop. The for loop, on the other hand, is an automatic loop. Syntax of C while Loop The syntax of constructing a while loop is as follows − while(expression){ statement(s); } The while keyword is followed by a parenthesis, in which there should be a Boolean expression. Followed by the parenthesis, there is a block of statements inside the curly brackets. Flowchart of C while Loop The following flowchart represents how the while loop works − How while Loop Works in C? The C compiler evaluates the expression. If the expression is true, the code block that follows, will be executed. If the expression is false, the compiler ignores the block next to the while keyword, and proceeds to the immediately next statement after the block. Since the expression that controls the loop is tested before the program enters the loop, the while loop is called the entry verified loop. Here, the key point to note is that a while loop might not execute at all if the condition is found to be not true at the very first instance itself. The while keyword implies that the compiler continues to execute the ensuing block as long as the expression is true. The condition sits at the top of the looping construct. After each iteration, the condition is tested. If found to be true, the compiler performs the next iteration. As soon as the expression is found to be false, the loop body will be skipped and the first statement after the while loop will be executed. Example of while Loop in C The following program prints the “Hello World” message five times. #include <stdio.h> int main(){ // local variable definition int a = 1; // while loop execution while(a <= 5){ printf(“Hello World n”); a++; } printf(“End of loop”); return 0; } Output Here, the while loop acts as a counted loop. Run the code and check its output − Hello World Hello World Hello World Hello World Hello World End of loop Example Explanation The variable “a” that controls the number of repetitions is initialized to 1, before the while statement. Since the condition “a <= 5” is true, the program enters the loop, prints the message, increments “a” by 1, and goes back to the top of the loop. In the next iteration, “a” is 2, hence the condition is still true, hence the loop repeats again, and continues till the condition turns false. The loop stops repeating, and the program control goes to the step after the block. Now, change the initial value of “a” to 10 and run the code again. Now the output will show the following − End of loop This is because the condition before the while keyword is false in the very first iteration itself, hence the block is not repeated. A “char” variable represents a character corresponding to its ASCII value. Hence, it can be incremented. Hence, we increment the value of the variable from “a” till it reaches “z”. Using while as Conditional Loop You can use a while loop as a conditional loop where the loop will be executed till the given condition is satisfied. Example In this example, the while loop is used as a conditional loop. The loop continues to repeat till the input received is non-negative. #include <stdio.h> int main(){ // local variable definition char choice = ”a”; int x = 0; // while loop execution while(x >= 0){ (x % 2 == 0) ? printf(“%d is Even n”, x) : printf(“%d is Odd n”, x); printf(“n Enter a positive number: “); scanf(“%d”, &x); } printf(“n End of loop”); return 0; } Output Run the code and check its output − 0 is Even Enter a positive number: 12 12 is Even Enter a positive number: 25 25 is Odd Enter a positive number: -1 End of loop While Loop with break and continue In all the examples above, the while loop is designed to repeat for a number of times, or till a certain condition is found. C has break and continue statements to control the loop. These keywords can be used inside the while loop. Example The break statement causes a loop to terminate − while (expr){ . . . . . . if (condition) break; . . . } Example The continue statement makes a loop repeat from the beginning − while (expr){ . . . . . . if (condition) continue; . . . } More Examples of C while Loop Example: Printing Lowercase Alphabets The following program prints all the lowercase alphabets with the help of a while loop. #include <stdio.h> int main(){ // local variable definition char a = ”a”; // while loop execution while(a <= ”z”) { printf(“%c”, a); a++; } printf(“n End of loop”); return 0; } Output Run the code and check its output − abcdefghijklmnopqrstuvwxyz End of loop Example: Equate Two Variables In the code given below, we have two variables “a” and “b” initialized to 10 and 0, respectively. Inside the loop, “b” is decremented and “a” is incremented on each iteration. The loop is
C – Variadic Functions
Variadic Functions in C ”; Previous Next Variadic functions are one of the powerful but very rarely used features in C language. Variadic functions add a lot of flexibility in programming the application structure. Variadic Function in C A function that can take a variable number of arguments is called a variadic function. One fixed argument is required to define a variadic function. The most frequently used library functions in C, i.e., printf() and scanf() are in fact the best-known examples of variadic functions, as we can put a variable number of arguments after the format specifier string. printf(“format specifier”,arg1, arg2, arg3, . . .); Syntax of Variadic Functions In C, a variadic function is defined to have at least one fixed argument, and then followed by an ellipsis symbol (…) that enables the compiler to parse the variable number of arguments. return_type function_name(type arg1, …); You need to include the stdarg.h header file at the top of the code to handle the variable arguments. This header file provides the following macros to work with the arguments received by the ellipsis symbol. Methods Description va_start(va_list ap, arg) Arguments after the last fixed argument are stored in the va_list. va_arg(va_list ap, type) Each time, the next argument in the variable list va_list and coverts it to the given type, till it reaches the end of list. va_copy(va_list dest, va_list src) This creates a copy of the arguments in va_list va_end(va_list ap) This ends the traversal of the variadic function arguments. As the end of va_list is reached, the list object is cleaned up. Examples of Variadic Functions in C Example: Sum of Numbers Using a Variadic Function The following code uses the concept of a variadic function to return the sum of a variable number of numeric arguments passed to such a function. The first argument to the addition() function is the count of the remaining arguments. Inside the addition() function, we initialize the va_list variable as follows − va_list args; va_start (args, n); Since there are “n” number of arguments that follow, fetch the next argument with “va_arg()” macro for “n” number of times and perform cumulative addition − for(i = 0; i < n; i++){ sum += va_arg (args, int); } Finally, clean up the va_list variable − va_end (args); The function ends by returning the sum of all the arguments. The complete code is given below − #include <stdio.h> #include <stdarg.h> // Variadic function to add numbers int addition(int n, …){ va_list args; int i, sum = 0; va_start (args, n); for (i = 0; i < n; i++){ sum += va_arg (args, int); } va_end (args); return sum; } int main(){ printf(“Sum = %d “, addition(5, 1, 2, 3, 4, 5)); return 0; } Output Run the code and check its output − Sum = 15 You can try providing a different set of numbers as the variadic arguments to the addition() function. Example: Finding the Largest Number Using a Variadic Function We can extend the concept of variadic function to find the largest number in a given list of variable number of values. #include <stdio.h> #include <stdarg.h> // Variadic function to add numbers int largest(int n, …){ va_list args; int i, max = 0; va_start (args, n); for(i = 0; i < n; i++){ int x = va_arg (args, int); if (x >= max) max = x; } va_end (args); return max; } int main(){ printf(“Largest number in the list = %d “, largest(5, 12, 34, 21, 45, 32)); return 0; } Output When you run this code, it will produce the following output − Largest number in the list = 45 Example: Concatenation of Multiple Strings Using Variadic Function In the following code, we pass multiple strings to a variadic function that returns a concatenated string. #include <stdio.h> #include <string.h> #include <stdarg.h> char * concat(int n, …){ va_list args; int i; static char string[100], *word; va_start (args, n); strcpy(string, “”); for (i = 0; i < n; i++){ word= va_arg (args, char *); strcat(string, word); strcat(string, ” “); } va_end (args); return string; } int main(){ char * string1 = concat(2, “Hello”, “World”); printf(“%sn”, string1); char * string2 = concat(3, “How”, “are”, “you?”); printf(“%sn”, string2); return 0; } Output Run the code and check its output − Hello World How are you? Print Page Previous Next Advertisements ”;