UNIT 2
Programming Using C
The C Pre-processor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Pre-processor is just a text substitution tool and it instructs the compiler to do require pre-processing before the actual compilation. We'll refer to the C Pre-processor as CPP.
All pre-processor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a pre-processor directive should begin in the first column. The following section lists down all the important preprocessor directives −
Sr.No. | Directive & Description |
1 | #define Substitutes a preprocessor macro. |
2 | #include Inserts a particular header from another file. |
3 | #undef Undefines a preprocessor macro. |
4 | #ifdef Returns true if this macro is defined. |
5 | #ifndef Returns true if this macro is not defined. |
6 | #if Tests if a compile time condition is true. |
7 | #else The alternative for #if. |
8 | #elif #else and #if in one statement. |
9 | #endif Ends preprocessor conditional. |
10 | #error Prints error message on stderr. |
11 | #pragma Issues special commands to the compiler, using a standardized method. |
Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation.
Predefined Macros
ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified.
Sr.No. | Macro & Description |
1 | __DATE__ The current date as a character literal in "MMM DD YYYY" format. |
2 | __TIME__ The current time as a character literal in "HH:MM:SS" format. |
3 | __FILE__ This contains the current filename as a string literal. |
4 | __LINE__ This contains the current line number as a decimal constant. |
5 | __STDC__ Defined as 1 when the compiler complies with the ANSI standard. |
Let's try the following example −
#include <stdio.h>
Int main() {
Printf("File :%s\n", __FILE__ );
Printf("Date :%s\n", __DATE__ );
Printf("Time :%s\n", __TIME__ );
Printf("Line :%d\n", __LINE__ );
Printf("ANSI :%d\n", __STDC__ );
}
When the above code in a file test.c is compiled and executed, it produces the following result −
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
Preprocessor Operators
The C preprocessor offers the following operators to help create macros −
The Macro Continuation (\) Operator
A macro is normally confined to a single line. The macro continuation operator (\) is used to continue a macro that is too long for a single line. For example −
#define message_for(a, b) \
Printf(#a " and " #b ": We love you!\n")
The Stringize (#) Operator
The stringize or number-sign operator ( '#' ), when used within a macro definition, converts a macro parameter into a string constant. This operator may be used only in a macro having a specified argument or parameter list. For example −
#include <stdio.h>
#define message_for(a, b) \
Printf(#a " and " #b ": We love you!\n")
Int main(void) {
Message_for(Carole, Debra);
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Carole and Debra: We love you!
The Token Pasting (##) Operator
The token-pasting operator (##) within a macro definition combines two arguments. It permits two separate tokens in the macro definition to be joined into a single token. For example −
#include <stdio.h>
#define tokenpaster(n) printf ("token" #n " = %d", token##n)
Int main(void) {
Int token34 = 40;
Tokenpaster(34);
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Token34 = 40
It happened so because this example results in the following actual output from the preprocessor−
Printf ("token34 = %d", token34);
This example shows the concatenation of token##n into token34 and here we have used both stringize and token-pasting.
The Defined() Operator
The preprocessordefined operator is used in constant expressions to determine if an identifier is defined using #define. If the specified identifier is defined, the value is true (non-zero). If the symbol is not defined, the value is false (zero). The defined operator is specified as follows −
#include <stdio.h>
#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif
Int main(void) {
Printf("Here is the message: %s\n", MESSAGE);
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Here is the message: You wish!
Parameterized Macros
One of the powerful functions of the CPP is the ability to simulate functions using parameterized macros. For example, we might have some code to square a number as follows −
Int square(int x) {
Return x * x;
}
We can rewrite above the code using a macro as follows −
#define square(x) ((x) * (x))
Macros with arguments must be defined using the #define directive before they can be used. The argument list is enclosed in parentheses and must immediately follow the macro name. Spaces are not allowed between the macro name and open parenthesis. For example −
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
Int main(void) {
Printf("Max between 20 and 10 is %d\n", MAX(10, 20));
Return 0;
}
When the above code is compiled and executed, it produces the following result −
Max between 20 and 10 is 20
When we say Input, it means to feed some data into a program. An input can be given in the form of a file or from the command line. C programming provides a set of built-in functions to read the given input and feed it to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C programming provides a set of built-in functions to output the data on the computer screen as well as to save it in text or binary files.
The Standard Files
C programming treats all the devices as files. So devices such as the display are addressed in the same way as files and the following three files are automatically opened when a program executes to provide access to the keyboard and screen.
Standard File | File Pointer | Device |
Standard input | Stdin | Keyboard |
Standard output | Stdout | Screen |
Standard error | Stderr | Your screen |
The file pointers are the means to access the file for reading and writing purpose. This section explains how to read values from the screen and how to print the result on the screen.
The getchar() and putchar() Functions
The intgetchar(void) function reads the next available character from the screen and returns it as an integer. This function reads only single character at a time. You can use this method in the loop in case you want to read more than one character from the screen.
The intputchar(int c) function puts the passed character on the screen and returns the same character. This function puts only single character at a time. You can use this method in the loop in case you want to display more than one character on the screen. Check the following example −
#include <stdio.h>
Int main( ) {
Int c;
Printf( "Enter a value :");
c = getchar( );
Printf( "\nYou entered: ");
Putchar( c );
Return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads only a single character and displays it as follows −
$./a.out
Enter a value : this is test
You entered: t
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a terminating newline or EOF (End of File).
The intputs(const char *s) function writes the string 's' and 'a' trailing newline to stdout.
NOTE: Though it has been deprecated to use gets() function, Instead of using gets, you want to use fgets().
#include <stdio.h>
Int main( ) {
Charstr[100];
Printf( "Enter a value :");
Gets(str );
Printf( "\nYou entered: ");
Puts(str );
Return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then the program proceeds and reads the complete line till end, and displays it as follows −
$./a.out
Enter a value : this is test
You entered: this is test
The scanf() and printf() Functions
The intscanf(const char *format, ...) function reads the input from the standard input stream stdin and scans that input according to the format provided.
The intprintf(const char *format, ...) function writes the output to the standard output stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings, integer, character or float respectively. There are many other formatting options available which can be used based on requirements. Let us now proceed with a simple example to understand the concepts better −
#include <stdio.h>
Int main( ) {
Charstr[100];
Inti;
Printf( "Enter a value :");
Scanf("%s %d", str, &i);
Printf( "\nYou entered: %s %d ", str, i);
Return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text and press enter, then program proceeds and reads the input and displays it as follows −
$./a.out
Enter a value : seven 7
You entered: seven 7
Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which means you have to provide valid inputs like "string integer". If you provide "string string" or "integer integer", then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as soon as it encounters a space, so "this is test" are three strings for scanf().
There are some library functions which are available for transferring the information between the computer and the standard input and output devices.
These functions are related to the symbolic constants and are available in the header file.
Some of the input and output functions are as follows:
i) printf
This function is used for displaying the output on the screen i.e the data is moved from the computer memory to the output device.
Syntax:
printf(“format string”, arg1, arg2, …..);
In the above syntax, 'format string' will contain the information that is formatted. They are the general characters which will be displayed as they are .
arg1, arg2 are the output data items.
Example: Demonstrating the printf function
printf(“Enter a value:”);
- Printf will generally examine from left to right of the string.
- The characters are displayed on the screen in the manner they are encountered until it comes across % or \.
- Once it comes across the conversion specifiers it will take the first argument and print it in the format given.
Ii) scanf
scanf is used when we enter data by using an input device.
Syntax:
scanf (“format string”, &arg1, &arg2, …..);
The number of items which are successful are returned.
Format string consists of the conversion specifier. Arguments can be variables or array name and represent the address of the variable. Each variable must be preceded by an ampersand (&). Array names should never begin with an ampersand.
Example: Demonstrating scanf
intavg;
float per;
char grade;
scanf(“%d %f %c”,&avg, &per, &grade):
- Scanf works totally opposite to printf. The input is read, interpret using the conversion specifier and stores it in the given variable.
- The conversion specifier for scanf is the same as printf.
- Scanf reads the characters from the input as long as the characters match or it will terminate. The order of the characters that are entered are not important.
- It requires an enter key in order to accept an input.
Iii) getch
This function is used to input a single character. The character is read instantly and it does not require an enter key to be pressed. The character type is returned but it does not echo on the screen.
Syntax:
intgetch(void);
ch=getch();
where,
ch - assigned the character that is returned by getch.
iv) putch
this function is a counterpart of getch. Which means that it will display a single character on the screen. The character that is displayed is returned.
Syntax:
intputch(int);
putch(ch);
where,
ch - the character that is to be printed.
v) getche
This function is used to input a single character. The main difference between getch and getche is that getche displays the (echoes) the character that we type on the screen.
Syntax:
intgetch(void);
ch=getche();
vi) getchar
This function is used to input a single character. The enter key is pressed which is followed by the character that is typed. The character that is entered is echoed.
Syntax:
ch=getchar;
vii) putchar
This function is the other side of getchar. A single character is displayed on the screen.
Syntax:
putchar(ch);
viii) gets and puts
They help in transferring the strings between the computer and the standard input-output devices. Only single arguments are accepted. The arguments must be such that it represents a string. It may include white space characters. If gets is used enter key has to be pressed for ending the string. The gets and puts function are used to offer simple alternatives of scanf and printf for reading and displaying.
Example:
#include <stdio.h>
void main()
{
char line[30];
gets (line);
puts (line);
}
C Standard library functions or simply C Library functions are inbuilt functions in C programming.
The prototype and data definitions of these functions are present in their respective header files. To use these functions we need to include the header file in our program. For example,
If you want to use the printf() function, the header file <stdio.h> should be included.
Intmain()
{
Printf("Catch me if you can.");
}
If you try to use printf() without including the stdio.h header file, you will get an error.
Advantages of Using C library functions
1. They work
One of the most important reasons you should use library functions is simply because they work. These functions have gone through multiple rigorous testing and are easy to use.
2. The functions are optimized for performance
Since, the functions are "standard library" functions, a dedicated group of developers constantly make them better. In the process, they are able to create the most efficient code optimized for maximum performance.
3. It saves considerable development time
Since the general functions like printing to a screen, calculating the square root, and many more are already written. You shouldn't worry about creating them once again.
4. The functions are portable
With ever-changing real-world needs, your application is expected to work every time, everywhere. And, these library functions help you in that they do the same thing on every computer.
Example: Square root using sqrt() function
Suppose, you want to find the square root of a number.
To can compute the square root of a number, you can use the sqrt() library function. The function is defined in the math.h header file.
Intmain()
{
Floatnum, root;
Printf("Enter a number: ");
Scanf("%f", &num);
// Computes the square root of num and stores in root.
Root = sqrt(num);
Printf("Square root of %.2f = %.2f", num, root);
Return0;
}
When you run the program, the output will be:
Enter a number: 12
Square root of 12.00 = 3.46
Library Functions in Different Header Files
C Header Files | |
<assert.h> | Program assertion functions |
<ctype.h> | Character type functions |
<locale.h> | Localization functions |
<math.h> | Mathematics functions |
<setjmp.h> | Jump functions |
<signal.h> | Signal handling functions |
<stdarg.h> | Variable arguments handling functions |
<stdio.h> | Standard Input/Output functions |
<stdlib.h> | Standard Utility functions |
<string.h> | String handling functions |
<time.h> | Date time functions |
The enum in C is also known as the enumerated type. It is a user-defined data type that consists of integer values, and it provides meaningful names to these values. The use of enum in C makes the program easy to understand and maintain. The enum is defined by using the enum keyword.
The following is the way to define the enum in C:
- Enum flag{integer_const1, integer_const2,.....integter_constN};
In the above declaration, we define the enum named as flag containing 'N' integer constants. The default value of integer_const1 is 0, integer_const2 is 1, and so on. We can also change the default value of the integer constants at the time of the declaration.
For example:
- Enum fruits{mango, apple, strawberry, papaya};
The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3. If we want to change these default values, then we can do as given below:
- Enum fruits{
- Mango=2,
- Apple=1,
- Strawberry=5,
- Papaya=7,
- };
Enumerated type declaration
As we know that in C language, we need to declare the variable of a pre-defined type such as int, float, char, etc. Similarly, we can declare the variable of a user-defined data type, such as enum. Let's see how we can declare the variable of an enum type.
Suppose we create the enum of type status as shown below:
- Enum status{false,true};
Now, we create the variable of status type:
- Enum status s; // creating a variable of the status type.
In the above statement, we have declared the 's' variable of type status.
To create a variable, the above two statements can be written as:
- Enum status{false,true} s;
In this case, the default value of false will be equal to 0, and the value of true will be equal to 1.
Let's create a simple program of enum.
- #include <stdio.h>
- Enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
- Int main()
- {
- Enum weekdays w; // variable declaration of weekdays type
- w=Monday; // assigning value of Monday to w.
- Printf("The value of w is %d",w);
- Return 0;
- }
In the above code, we create an enum type named as weekdays, and it contains the name of all the seven days. We have assigned 1 value to the Sunday, and all other names will be given a value as the previous value plus one.
Output
Let's demonstrate another example to understand the enum more clearly.
- #include <stdio.h>
- Enum months{jan=1, feb, march, april, may, june, july, august, september, october, november, december};
- Int main()
- {
- // printing the values of months
- For(int i=jan;i<=december;i++)
- {
- Printf("%d, ",i);
- }
- Return 0;
- }
In the above code, we have created a type of enum named as months which consists of all the names of months. We have assigned a '1' value, and all the other months will be given a value as the previous one plus one. Inside the main() method, we have defined a for loop in which we initialize the 'i' variable by jan, and this loop will iterate till December.
Output
Why do we use enum?
The enum is used when we want our variable to have only a set of values. For example, we create a direction variable. As we know that four directions exist (North, South, East, West), so this direction variable will have four possible values. But the variable can hold only one value at a time. If we try to provide some different value to this variable, then it will throw the compilation error.
The enum is also used in a switch case statement in which we pass the enum variable in a switch parenthesis. It ensures that the value of the case block should be defined in an enum.
Let's see how we can use an enum in a switch case statement.
- #include <stdio.h>
- Enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday};
- Int main()
- {
- Enum days d;
- d=monday;
- Switch(d)
- {
- Case sunday:
- Printf("Today is sunday");
- Break;
- Case monday:
- Printf("Today is monday");
- Break;
- Case tuesday:
- Printf("Today is tuesday");
- Break;
- Case wednesday:
- Printf("Today is wednesday");
- Break;
- Case thursday:
- Printf("Today is thursday");
- Break;
- Case friday:
- Printf("Today is friday");
- Break;
- Case saturday:
- Printf("Today is saturday");
- Break;
- }
- Return 0;
- }
Output
Some important points related to enum
- The enum names available in an enum type can have the same value. Let's look at the example.
- #include <stdio.h>
- Int main(void) {
- Enum fruits{mango = 1, strawberry=0, apple=1};
- Printf("The value of mango is %d", mango);
- Printf("\nThe value of apple is %d", apple);
- Return 0;
- }
Output
- If we do not provide any value to the enum names, then the compiler will automatically assign the default values to the enum names starting from 0.
- We can also provide the values to the enum name in any order, and the unassigned names will get the default value as the previous one plus one.
- The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc.
- All the enum names must be unique in their scope, i.e., if we define two enum having same scope, then these two enums should have different enum names otherwise compiler will throw an error.
Let's understand this scenario through an example.
- #include <stdio.h>
- Enum status{success, fail};
- Enum boolen{fail,pass};
- Int main(void) {
- Printf("The value of success is %d", success);
- Return 0;
- }
Output
- In enumeration, we can define an enumerated data type without the name also.
- #include <stdio.h>
- Enum {success, fail} status;
- Int main(void) {
- Status=success;
- Printf("The value of status is %d", status);
- Return 0;
- }
Output
Enum vs. Macro in C
- Macro can also be used to define the name constants, but in case of an enum, all the name constants can be grouped together in a single statement.
For example,
# define pass 0;
# define success 1;
The above two statements can be written in a single statement by using the enum type.
enum status{pass, success};
- The enum type follows the scope rules while macro does not follow the scope rules.
- In Enum, if we do not assign the values to the enum names, then the compiler will automatically assign the default value to the enum names. But, in the case of macro, the values need to be explicitly assigned.
- The type of enum in C is an integer, but the type of macro can be of any type.
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C language is rich in built-in operators and provides the following types of operators −
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20 then −
Operator | Description | Example |
+ | Adds two operands. | A + B = 30 |
− | Subtracts second operand from the first. | A − B = -10 |
* | Multiplies both operands. | A * B = 200 |
/ | Divides numerator by de-numerator. | B / A = 2 |
% | Modulus Operator and remainder of after an integer division. | B % A = 0 |
++ | Increment operator increases the integer value by one. | A++ = 11 |
-- | Decrement operator decreases the integer value by one. | A-- = 9 |
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and variable B holds 20 then −
Operator | Description | Example |
== | Checks if the values of two operands are equal or not. If yes, then the condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true. | (A <= B) is true. |
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and variable B holds 0, then −
Operator | Description | Example |
&& | Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non-zero, then the condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. | !(A && B) is true. |
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −
p | q | p & q | p | q | p ^ q |
0 | 0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and variable 'B' holds 13, then −
Operator | Description | Example |
& | Binary AND Operator copies a bit to the result if it exists in both operands. | (A & B) = 12, i.e., 0000 1100 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) = 61, i.e., 0011 1101 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (A ^ B) = 49, i.e., 0011 0001 |
~ | Binary One's Complement Operator is unary and has the effect of 'flipping' bits. | (~A ) = ~(60), i.e,. -0111101 |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 = 240 i.e., 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 = 15 i.e., 0000 1111 |
Assignment Operators
The following table lists the assignment operators supported by the C language −
Operator | Description | Example |
= | Simple assignment operator. Assigns values from right side operands to left side operand | C = A + B will assign the value of A + B to C |
+= | Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. | C -= A is equivalent to C = C - A |
*= | Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator. | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator. | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator. | C &= 2 is same as C = C & 2 |
^= | Bitwise exclusive OR and assignment operator. | C ^= 2 is same as C = C ^ 2 |
|= | Bitwise inclusive OR and assignment operator. | C |= 2 is same as C = C | 2 |
Misc Operators ↦sizeof& ternary
Besides the operators discussed above, there are a few other important operators including sizeofand ? : supported by the C Language.
Operator | Description | Example |
Sizeof() | Returns the size of a variable. | Sizeof(a), where a is integer, will return 4. |
& | Returns the address of a variable. | &a; returns the actual address of the variable. |
* | Pointer to a variable. | *a; |
? : | Conditional Expression. | If Condition is true ? then value X : otherwise value Y |
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category | Operator | Associativity |
Postfix | () [] -> . ++ - - | Left to right |
Unary | + - ! ~ ++ - - (type)* &sizeof | Right to left |
Multiplicative | * / % | Left to right |
Additive | + - | Left to right |
Shift | <<>> | Left to right |
Relational | <<= >>= | Left to right |
Equality | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise OR | | | Left to right |
Logical AND | && | Left to right |
Logical OR | || | Left to right |
Conditional | ?: | Right to left |
Assignment | = += -= *= /= %=>>= <<= &= ^= |= | Right to left |
Comma | , | Left to right |
Conditional statements, branching
If else Statement
The if-else statement in C is used to perform the operations based on some specific condition. The operations specified in if block are executed if and only if the given condition is true.
There are the following variants of if statement in C language.
- If statement
- If-else statement
- If else-if ladder
- Nested if
If Statement
The if statement is used to check some given condition and perform some operations depending upon the correctness of that condition. It is mostly used in the scenario where we need to perform the different operations for the different conditions. The syntax of the if statement is given below.
- If(expression){
- //code to be executed
- }
Flowchart of if statement in C
Let's see a simple example of C language if statement.
- #include<stdio.h>
- Int main(){
- Int number=0;
- Printf("Enter a number:");
- Scanf("%d",&number);
- If(number%2==0){
- Printf("%d is even number",number);
- }
- Return 0;
- }
Output
Enter a number:4
4 is even number
Enter a number:5
Program to find the largest number of the three.
- #include <stdio.h>
- Int main()
- {
- Int a, b, c;
- Printf("Enter three numbers?");
- Scanf("%d %d %d",&a,&b,&c);
- If(a>b && a>c)
- {
- Printf("%d is largest",a);
- }
- If(b>a && b > c)
- {
- Printf("%d is largest",b);
- }
- If(c>a && c>b)
- {
- Printf("%d is largest",c);
- }
- If(a == b && a == c)
- {
- Printf("All are equal");
- }
- }
Output
Enter three numbers?
12 23 34
34 is largest
If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition. The syntax of the if-else statement is given below.
- If(expression){
- //code to be executed if condition is true
- }else{
- //code to be executed if condition is false
- }
Flowchart of the if-else statement in C
Let's see the simple example to check whether a number is even or odd using if-else statement in C language.
- #include<stdio.h>
- Int main(){
- Int number=0;
- Printf("enter a number:");
- Scanf("%d",&number);
- If(number%2==0){
- Printf("%d is even number",number);
- }
- Else{
- Printf("%d is odd number",number);
- }
- Return 0;
- }
Output
Enter a number:4
4 is even number
Enter a number:5
5 is odd number
Program to check whether a person is eligible to vote or not.
- #include <stdio.h>
- Int main()
- {
- Int age;
- Printf("Enter your age?");
- Scanf("%d",&age);
- If(age>=18)
- {
- Printf("You are eligible to vote...");
- }
- Else
- {
- Printf("Sorry ... you can't vote");
- }
- }
Output
Enter your age?18
You are eligible to vote...
Enter your age?13
Sorry ... You can't vote
If else-if ladder Statement
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where there are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be executed, otherwise if some other condition is true then the statements defined in the else-if block will be executed, at the last if none of the condition is true then the statements defined in the else block will be executed. There are multiple else-if blocks possible. It is similar to the switch case statement where the default is executed instead of else block if none of the cases is matched.
- If(condition1){
- //code to be executed if condition1 is true
- }else if(condition2){
- //code to be executed if condition2 is true
- }
- Else if(condition3){
- //code to be executed if condition3 is true
- }
- ...
- Else{
- //code to be executed if all the conditions are false
- }
Flowchart of else-if ladder statement in C
The example of an if-else-if statement in C language is given below.
- #include<stdio.h>
- Int main(){
- Int number=0;
- Printf("enter a number:");
- Scanf("%d",&number);
- If(number==10){
- Printf("number is equals to 10");
- }
- Else if(number==50){
- Printf("number is equal to 50");
- }
- Else if(number==100){
- Printf("number is equal to 100");
- }
- Else{
- Printf("number is not equal to 10, 50 or 100");
- }
- Return 0;
- }
Output
Enter a number:4
Number is not equal to 10, 50 or 100
Enter a number:50
Number is equal to 50
Program to calculate the grade of the student according to the specified marks.
- #include <stdio.h>
- Int main()
- {
- Int marks;
- Printf("Enter your marks?");
- Scanf("%d",&marks);
- If(marks > 85 && marks <= 100)
- {
- Printf("Congrats ! you scored grade A ...");
- }
- Else if (marks > 60 && marks <= 85)
- {
- Printf("You scored grade B + ...");
- }
- Else if (marks > 40 && marks <= 60)
- {
- Printf("You scored grade B ...");
- }
- Else if (marks > 30 && marks <= 40)
- {
- Printf("You scored grade C ...");
- }
- Else
- {
- Printf("Sorry you are fail ...");
- }
- }
Output
Enter your marks?10
Sorry you are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats !you scored grade A ...
Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.
The syntax of switch statement is given below:
- Switch(expression){
- Case value1:
- //code to be executed;
- Break; //optional
- Case value2:
- //code to be executed;
- Break; //optional
- ......
- Default:
- Code to be executed if all cases are not matched;
- }
Rules for switch statement in C language
1) The switch expression must be of an integer or character type.
2) The case value must be an integer or character constant.
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all the cases will be executed present after the matched case. It is known as fall through the state of C switch statement.
Let's try to understand it by the examples. We are assuming that there are following variables.
- Int x,y,z;
- Char a,b;
- Float f;
Valid Switch | Invalid Switch | Valid Case | Invalid Case |
Switch(x) | Switch(f) | Case 3; | Case 2.5; |
Switch(x>y) | Switch(x+2.5) | Case 'a'; | Case x; |
Switch(a+b-2) |
| Case 1+2; | Case x+2; |
Switch(func(x,y)) |
| Case 'x'>'y'; | Case 1,2,3; |
Flowchart of switch statement in C
Functioning of switch case statement
First, the integer expression specified in the switch statement is evaluated. This value is then matched one by one with the constant values given in the different cases. If a match is found, then all the statements specified in that case are executed along with the all the cases present after that case including the default statement. No two cases can have similar values. If the matched case contains a break statement, then all the cases present after that will be skipped, and the control comes out of the switch. Otherwise, all the cases following the matched case will be executed.
Let's see a simple example of c language switch statement.
- #include<stdio.h>
- Int main(){
- Int number=0;
- Printf("enter a number:");
- Scanf("%d",&number);
- Switch(number){
- Case 10:
- Printf("number is equals to 10");
- Break;
- Case 50:
- Printf("number is equal to 50");
- Break;
- Case 100:
- Printf("number is equal to 100");
- Break;
- Default:
- Printf("number is not equal to 10, 50 or 100");
- }
- Return 0;
- }
Output
Enter a number:4
Number is not equal to 10, 50 or 100
Enter a number:50
Number is equal to 50
Switch case example 2
- #include <stdio.h>
- Int main()
- {
- Int x = 10, y = 5;
- Switch(x>y && x+y>0)
- {
- Case 1:
- Printf("hi");
- Break;
- Case 0:
- Printf("bye");
- Break;
- Default:
- Printf(" Hello bye ");
- }
- }
Output
Hi
C Switch statement is fall-through
In C language, the switch statement is fall through; it means if you don't use a break statement in the switch case, all the cases after the matching case will be executed.
Let's try to understand the fall through state of switch statement by the example given below.
- #include<stdio.h>
- Int main(){
- Int number=0;
- Printf("enter a number:");
- Scanf("%d",&number);
- Switch(number){
- Case 10:
- Printf("number is equal to 10\n");
- Case 50:
- Printf("number is equal to 50\n");
- Case 100:
- Printf("number is equal to 100\n");
- Default:
- Printf("number is not equal to 10, 50 or 100");
- }
- Return 0;
- }
Output
Enter a number:10
Number is equal to 10
Number is equal to 50
Number is equal to 100
Number is not equal to 10, 50 or 100
Output
Enter a number:50
Number is equal to 50
Number is equal to 100
Number is not equal to 10, 50 or 100
Nested switch case statement
We can use as many switch statement as we want inside a switch statement. Such type of statements is called nested switch case statements. Consider the following example.
- #include <stdio.h>
- Int main () {
- Int i = 10;
- Int j = 20;
- Switch(i) {
- Case 10:
- Printf("the value of i evaluated in outer switch: %d\n",i);
- Case 20:
- Switch(j) {
- Case 20:
- Printf("The value of j evaluated in nested switch: %d\n",j);
- }
- }
- Printf("Exact value of i is : %d\n", i );
- Printf("Exact value of j is : %d\n", j );
- Return 0;
- }
Output
The value of i evaluated in outer switch: 10
The value of j evaluated in nested switch: 20
Exact value of iis : 10
Exact value of j is : 20
If-else vs switch
What is an if-else statement?
An if-else statement in C programming is a conditional statement that executes a different set of statements based on the condition that is true or false. The 'if' block will be executed only when the specified condition is true, and if the specified condition is false, then the else block will be executed.
Syntax of if-else statement is given below:
- If(expression)
- {
- // statements;
- }
- Else
- {
- // statements;
- }
What is a switch statement?
A switch statement is a conditional statement used in C programming to check the value of a variable and compare it with all the cases. If the value is matched with any case, then its corresponding statements will be executed. Each case has some name or number known as the identifier. The value entered by the user will be compared with all the cases until the case is found. If the value entered by the user is not matched with any case, then the default statement will be executed.
Syntax of the switch statement is given below:
- Switch(expression)
- {
- Case constant 1:
- // statements;
- Break;
- Case constant 2:
- // statements;
- Break;
- Case constant n:
- // statements;
- Break;
- Default:
- // statements;
- }
Similarity b/w if-else and switch
Both the if-else and switch are the decision-making statements. Here, decision-making statements mean that the output of the expression will decide which statements are to be executed.
Differences b/w if-else and switch statement
The following are the differences between if-else and switch statement are:
- Definition
If-else
Based on the result of the expression in the 'if-else' statement, the block of statements will be executed. If the condition is true, then the 'if' block will be executed otherwise 'else' block will execute.
Switch statement
The switch statement contains multiple cases or choices. The user will decide the case, which is to execute.
- Expression
If-else
It can contain a single expression or multiple expressions for multiple choices. In this, an expression is evaluated based on the range of values or conditions. It checks both equality and logical expressions.
Switch
It contains only a single expression, and this expression is either a single integer object or a string object. It checks only equality expression.
- Evaluation
If-else
An if-else statement can evaluate almost all the types of data such as integer, floating-point, character, pointer, or Boolean.
Switch
A switch statement can evaluate either an integer or a character.
- Sequence of Execution
If-else
In the case of 'if-else' statement, either the 'if' block or the 'else' block will be executed based on the condition.
Switch
In the case of the 'switch' statement, one case after another will be executed until the break keyword is not found, or the default statement is executed.
- Default Execution
If-else
If the condition is not true within the 'if' statement, then by default, the else block statements will be executed.
Switch
If the expression specified within the switch statement is not matched with any of the cases, then the default statement, if defined, will be executed.
- Values
If-else
Values are based on the condition specified inside the 'if' statement. The value will decide either the 'if' or 'else' block is to be executed.
Switch
In this case, value is decided by the user. Based on the choice of the user, the case will be executed.
- Use
If-else
It evaluates a condition to be true or false.
Switch
A switch statement compares the value of the variable with multiple cases. If the value is matched with any of the cases, then the block of statements associated with this case will be executed.
- Editing
If-else
Editing in 'if-else' statement is not easy as if we remove the 'else' statement, then it will create the havoc.
Switch
Editing in switch statement is easier as compared to the 'if-else' statement. If we remove any of the cases from the switch, then it will not interrupt the execution of other cases. Therefore, we can say that the switch statement is easy to modify and maintain.
- Speed
If-else
If the choices are multiple, then the speed of the execution of 'if-else' statements is slow.
Switch
The case constants in the switch statement create a jump table at the compile time. This jump table chooses the path of the execution based on the value of the expression. If we have a multiple choice, then the execution of the switch statement will be much faster than the equivalent logic of 'if-else' statement.
Let's summarize the above differences in a tabular form.
| If-else | Switch |
Definition | Depending on the condition in the 'if' statement, 'if' and 'else' blocks are executed. | The user will decide which statement is to be executed. |
Expression | It contains either logical or equality expression. | It contains a single expression which can be either a character or integer variable. |
Evaluation | It evaluates all types of data, such as integer, floating-point, character or Boolean. | It evaluates either an integer, or character. |
Sequence of execution | First, the condition is checked. If the condition is true then 'if' block is executed otherwise 'else' block | It executes one case after another till the break keyword is not found, or the default statement is executed. |
Default execution | If the condition is not true, then by default, else block will be executed. | If the value does not match with any case, then by default, default statement is executed. |
Editing | Editing is not easy in the 'if-else' statement. | Cases in a switch statement are easy to maintain and modify. Therefore, we can say that the removal or editing of any case will not interrupt the execution of other cases. |
Speed | If there are multiple choices implemented through 'if-else', then the speed of the execution will be slow. | If we have multiple choices then the switch statement is the best option as the speed of the execution will be much higher than 'if-else'. |
Loops
The looping can be defined as repeating the same process multiple times until a specific condition satisfies. There are three types of loops used in the C language. In this part of the tutorial, we are going to learn all the aspects of C loops.
Why use loops in C language?
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so that instead of writing the same code again and again, we can repeat the same code for a finite number of times. For example, if we need to print the first 10 natural numbers then, instead of using the printf statement 10 times, we can print inside a loop which runs up to 10 iterations.
Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops
There are three types of loops in C language that is given below:
- Do while
- While
- For
Do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it is necessary to execute the loop at least once (mostly menu driven programs).
The syntax of do-while loop in c language is given below:
- Do{
- //code to be executed
- }while(condition);
While loop in C
The while loop in c is to be used in the scenario where we don't know the number of iterations in advance. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop.
The syntax of while loop in c language is given below:
- While(condition){
- //code to be executed
- }
For loop in C
The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance.
The syntax of for loop in c language is given below:
- For(initialization;condition;incr/decr){
- //code to be executed
- }
Do while loop
The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of several parts of the statements. The do-while loop is mainly used in the case where we need to execute the loop at least once. The do-while loop is mostly used in menu-driven programs where the termination condition depends upon the end user.
Do while loop syntax
The syntax of the C language do-while loop is given below:
- Do{
- //code to be executed
- }while(condition);
Example 1
- #include<stdio.h>
- #include<stdlib.h>
- Void main ()
- {
- Char c;
- Int choice,dummy;
- Do{
- Printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
- Scanf("%d",&choice);
- Switch(choice)
- {
- Case 1 :
- Printf("Hello");
- Break;
- Case 2:
- Printf("Javatpoint");
- Break;
- Case 3:
- Exit(0);
- Break;
- Default:
- Printf("please enter valid choice");
- }
- Printf("do you want to enter more?");
- Scanf("%d",&dummy);
- Scanf("%c",&c);
- }while(c=='y');
- }
Output
1. Print Hello
2. Print Javatpoint
3. Exit
1
Hello
Do you want to enter more?
y
1. Print Hello
2. Print Javatpoint
3. Exit
2
Javatpoint
Do you want to enter more?
n
Flowchart of do while loop
do while example
There is given the simple program of c language do while loop where we are printing the table of 1.
- #include<stdio.h>
- Int main(){
- Int i=1;
- Do{
- Printf("%d \n",i);
- i++;
- }while(i<=10);
- Return 0;
- }
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using do while loop
- #include<stdio.h>
- Int main(){
- Int i=1,number=0;
- Printf("Enter a number: ");
- Scanf("%d",&number);
- Do{
- Printf("%d \n",(number*i));
- i++;
- }while(i<=10);
- Return 0;
- }
Output
Enter a number: 5
5
10
15
20
25
30
35
40
45
50
Enter a number: 10
10
20
30
40
50
60
70
80
90
100
Infinitive do while loop
The do-while loop will run infinite times if we pass any non-zero value as the conditional expression.
- Do{
- //statement
- }while(1);
While loop
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance.
Syntax of while loop in C language
The syntax of while loop in c language is given below:
- While(condition){
- //code to be executed
- }
Flowchart of while loop in C
Example of the while loop in C language
Let's see the simple program of while loop that prints table of 1.
- #include<stdio.h>
- Int main(){
- Int i=1;
- While(i<=10){
- Printf("%d \n",i);
- i++;
- }
- Return 0;
- }
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using while loop in C
- #include<stdio.h>
- Int main(){
- Int i=1,number=0,b=9;
- Printf("Enter a number: ");
- Scanf("%d",&number);
- While(i<=10){
- Printf("%d \n",(number*i));
- i++;
- }
- Return 0;
- }
Output
Enter a number: 50
50
100
150
200
250
300
350
400
450
500
Enter a number: 100
100
200
300
400
500
600
700
800
900
1000
Properties of while loop
- A conditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails.
- The condition will be true if it returns 0. The condition will be false if it returns any non-zero number.
- In while loop, the condition expression is compulsory.
- Running a while loop without a body is possible.
- We can have more than one conditional expression in while loop.
- If the loop body contains only one statement, then the braces are optional.
Example 1
- #include<stdio.h>
- Void main ()
- {
- Int j = 1;
- While(j+=2,j<=10)
- {
- Printf("%d ",j);
- }
- Printf("%d",j);
- }
Output
3 5 7 9 11
Example 2
- #include<stdio.h>
- Void main ()
- {
- While()
- {
- Printf("hello Javatpoint");
- }
- }
Output
Compile time error: while loop can't be empty
Example 3
- #include<stdio.h>
- Void main ()
- {
- Int x = 10, y = 2;
- While(x+y-1)
- {
- Printf("%d %d",x--,y--);
- }
- }
Output
Infinite loop
Infinitive while loop in C
If the expression passed in while loop results in any non-zero value then the loop will run the infinite number of times.
- While(1){
- //statement
- }
For loop
The for loop in C language is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like the array and linked list.
Syntax of for loop in C
The syntax of for loop in c language is given below:
- For(Expression 1; Expression 2; Expression 3){
- //code to be executed
- }
Flowchart of for loop in C
C for loop Examples
Let's see the simple program of for loop that prints table of 1.
- #include<stdio.h>
- Int main(){
- Int i=0;
- For(i=1;i<=10;i++){
- Printf("%d \n",i);
- }
- Return 0;
- }
Output
1
2
3
4
5
6
7
8
9
10
C Program: Print table for the given number using C for loop
- #include<stdio.h>
- Int main(){
- Int i=1,number=0;
- Printf("Enter a number: ");
- Scanf("%d",&number);
- For(i=1;i<=10;i++){
- Printf("%d \n",(number*i));
- }
- Return 0;
- }
Output
Enter a number: 2
2
4
6
8
10
12
14
16
18
20
Enter a number: 1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000
Properties of Expression 1
- The expression represents the initialization of the loop variable.
- We can initialize more than one variable in Expression 1.
- Expression 1 is optional.
- In C, we can not declare the variables in Expression 1. However, It can be an exception in some compilers.
Example 1
- #include <stdio.h>
- Int main()
- {
- Int a,b,c;
- For(a=0,b=12,c=23;a<2;a++)
- {
- Printf("%d ",a+b+c);
- }
- }
Output
35 36
Example 2
- #include <stdio.h>
- Int main()
- {
- Int i=1;
- For(;i<5;i++)
- {
- Printf("%d ",i);
- }
- }
Output
1 2 3 4
Properties of Expression 2
- Expression 2 is a conditional expression. It checks for a specific condition to be satisfied. If it is not, the loop is terminated.
- Expression 2 can have more than one condition. However, the loop will iterate until the last condition becomes false. Other conditions will be treated as statements.
- Expression 2 is optional.
- Expression 2 can perform the task of expression 1 and expression 3. That is, we can initialize the variable as well as update the loop variable in expression 2 itself.
- We can pass zero or non-zero value in expression 2. However, in C, any non-zero value is true, and zero is false by default.
Example 1
- #include <stdio.h>
- Int main()
- {
- Int i;
- For(i=0;i<=4;i++)
- {
- Printf("%d ",i);
- }
- }
Output
0 1 2 3 4
Example 2
- #include <stdio.h>
- Int main()
- {
- Int i,j,k;
- For(i=0,j=0,k=0;i<4,k<8,j<10;i++)
- {
- Printf("%d %d %d\n",i,j,k);
- j+=2;
- k+=3;
- }
- }
Output
0 0 0
1 2 3
2 4 6
3 6 9
4 8 12
Example 3
- #include <stdio.h>
- Int main()
- {
- Int i;
- For(i=0;;i++)
- {
- Printf("%d",i);
- }
- }
Output
Infinite loop
Properties of Expression 3
- Expression 3 is used to update the loop variable.
- We can update more than one variable at the same time.
- Expression 3 is optional.
Example 1
- #include<stdio.h>
- Void main ()
- {
- Int i=0,j=2;
- For(i = 0;i<5;i++,j=j+2)
- {
- Printf("%d %d\n",i,j);
- }
- }
Output
0 2
1 4
2 6
3 8
4 10
Loop body
The braces {} are used to define the scope of the loop. However, if the loop contains only one statement, then we don't need to use braces. A loop without a body is possible. The braces work as a block separator, i.e., the value variable declared inside for loop is valid only for that block and not outside. Consider the following example.
- #include<stdio.h>
- Void main ()
- {
- Int i;
- For(i=0;i<10;i++)
- {
- Int i = 20;
- Printf("%d ",i);
- }
- }
Output
20 20 20 20 20 20 20 20 20 20
Infinitive for loop in C
To make a for loop infinite, we need not give any expression in the syntax. Instead of that, we need to provide two semicolons to validate the syntax of the for loop. This will work as an infinite for loop.
- #include<stdio.h>
- Void main ()
- {
- For(;;)
- {
- Printf("welcome to javatpoint");
- }
- }
If you run this program, you will see above statement infinite times.
Nested Loops in C
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Let's observe an example of nesting loops in C.
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
Syntax of Nested loop
- Outer_loop
- {
- Inner_loop
- {
- // inner loop statements.
- }
- // outer loop statements.
- }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-while' loop.
Nested for loop
The nested for loop means any type of loop which is defined inside the 'for' loop.
- For (initialization; condition; update)
- {
- For(initialization; condition; update)
- {
- // inner loop statements.
- }
- // outer loop statements.
- }
Example of nested for loop
- #include <stdio.h>
- Int main()
- {
- Int n;// variable declaration
- Printf("Enter the value of n :");
- // Displaying the n tables.
- For(int i=1;i<=n;i++) // outer loop
- {
- For(int j=1;j<=10;j++) // inner loop
- {
- Printf("%d\t",(i*j)); // printing the value.
- }
- Printf("\n");
- }
Explanation of the above code
- First, the 'i' variable is initialized to 1 and then program control passes to the i<=n.
- The program control checks whether the condition 'i<=n' is true or not.
- If the condition is true, then the program control passes to the inner loop.
- The inner loop will get executed until the condition is true.
- After the execution of the inner loop, the control moves back to the update of the outer loop, i.e., i++.
- After incrementing the value of the loop counter, the condition is checked again, i.e., i<=n.
- If the condition is true, then the inner loop will be executed again.
- This process will continue until the condition of the outer loop is true.
Output:
Nested while loop
The nested while loop means any type of loop which is defined inside the 'while' loop.
- While(condition)
- {
- While(condition)
- {
- // inner loop statements.
- }
- // outer loop statements.
- }
Example of nested while loop
- #include <stdio.h>
- Int main()
- {
- Int rows; // variable declaration
- Int columns; // variable declaration
- Int k=1; // variable initialization
- Printf("Enter the number of rows :"); // input the number of rows.
- Scanf("%d",&rows);
- Printf("\nEnter the number of columns :"); // input the number of columns.
- Scanf("%d",&columns);
- Int a[rows][columns]; //2d array declaration
- Int i=1;
- While(i<=rows) // outer loop
- {
- Int j=1;
- While(j<=columns) // inner loop
- {
- Printf("%d\t",k); // printing the value of k.
- k++; // increment counter
- j++;
- }
- i++;
- Printf("\n");
- }
- }
Explanation of the above code.
- We have created the 2d array, i.e., inta[rows][columns].
- The program initializes the 'i' variable by 1.
- Now, control moves to the while loop, and this loop checks whether the condition is true, then the program control moves to the inner loop.
- After the execution of the inner loop, the control moves to the update of the outer loop, i.e., i++.
- After incrementing the value of 'i', the condition (i<=rows) is checked.
- If the condition is true, the control then again moves to the inner loop.
- This process continues until the condition of the outer loop is true.
Output:
Nested do..while loop
The nested do..while loop means any type of loop which is defined inside the 'do..while' loop.
- Do
- {
- Do
- {
- // inner loop statements.
- }while(condition);
- // outer loop statements.
- }while(condition);
Example of nested do..while loop.
- #include <stdio.h>
- Int main()
- {
- /*printing the pattern
- ********
- ********
- ********
- ******** */
- Int i=1;
- Do // outer loop
- {
- Int j=1;
- Do // inner loop
- {
- Printf("*");
- j++;
- }while(j<=8);
- Printf("\n");
- i++;
- }while(i<=4);
- }
Output:
Explanation of the above code.
- First, we initialize the outer loop counter variable, i.e., 'i' by 1.
- As we know that the do..while loop executes once without checking the condition, so the inner loop is executed without checking the condition in the outer loop.
- After the execution of the inner loop, the control moves to the update of the i++.
- When the loop counter value is incremented, the condition is checked. If the condition in the outer loop is true, then the inner loop is executed.
- This process will continue until the condition in the outer loop is true.
Infinite Loop in C
What is infinite loop?
An infinite loop is a looping construct that does not terminate the loop and executes the loop forever. It is also called an indefinite loop or an endless loop. It either produces a continuous output or no output.
When to use an infinite loop
An infinite loop is useful for those applications that accept the user input and generate the output continuously until the user exits from the application manually. In the following situations, this type of loop can be used:
- All the operating systems run in an infinite loop as it does not exist after performing some task. It comes out of an infinite loop only when the user manually shuts down the system.
- All the servers run in an infinite loop as the server responds to all the client requests. It comes out of an indefinite loop only when the administrator shuts down the server manually.
- All the games also run in an infinite loop. The game will accept the user requests until the user exits from the game.
We can create an infinite loop through various loop structures. The following are the loop structures through which we will define the infinite loop:
- For loop
- While loop
- Do-while loop
- Go to statement
- C macros
For loop
Let's see the infinite 'for' loop. The following is the definition for the infinite for loop:
- For(; ;)
- {
- // body of the for loop.
- }
As we know that all the parts of the 'for' loop are optional, and in the above for loop, we have not mentioned any condition; so, this loop will execute infinite times.
Let's understand through an example.
- #include <stdio.h>
- Int main()
- {
- For(;;)
- {
- Printf("Hello javatpoint");
- }
- Return 0;
- }
In the above code, we run the 'for' loop infinite times, so "Hello javatpoint" will be displayed infinitely.
Output
While loop
Now, we will see how to create an infinite loop using a while loop. The following is the definition for the infinite while loop:
- While(1)
- {
- // body of the loop..
- }
In the above while loop, we put '1' inside the loop condition. As we know that any non-zero integer represents the true condition while '0' represents the false condition.
Let's look at a simple example.
- #include <stdio.h>
- Int main()
- {
- Int i=0;
- While(1)
- {
- i++;
- Printf("i is :%d",i);
- }
- Return 0;
- }
In the above code, we have defined a while loop, which runs infinite times as it does not contain any condition. The value of 'i' will be updated an infinite number of times.
Output
Do..while loop
The do..while loop can also be used to create the infinite loop. The following is the syntax to create the infinite do..while loop.
- Do
- {
- // body of the loop..
- }while(1);
The above do..while loop represents the infinite condition as we provide the '1' value inside the loop condition. As we already know that non-zero integer represents the true condition, so this loop will run infinite times.
Goto statement
We can also use the goto statement to define the infinite loop.
- Infinite_loop;
- // body statements.
- Goto infinite_loop;
In the above code, the goto statement transfers the control to the infinite loop.
Macros
We can also create the infinite loop with the help of a macro constant. Let's understand through an example.
- #include <stdio.h>
- #define infinite for(;;)
- Int main()
- {
- Infinite
- {
- Printf("hello");
- }
- Return 0;
- }
In the above code, we have defined a macro named as 'infinite', and its value is 'for(;;)'. Whenever the word 'infinite' comes in a program then it will be replaced with a 'for(;;)'.
Output
Till now, we have seen various ways to define an infinite loop. However, we need some approach to come out of the infinite loop. In order to come out of the infinite loop, we can use the break statement.
Let's understand through an example.
- #include <stdio.h>
- Int main()
- {
- Char ch;
- While(1)
- {
- Ch=getchar();
- If(ch=='n')
- {
- Break;
- }
- Printf("hello");
- }
- Return 0;
- }
In the above code, we have defined the while loop, which will execute an infinite number of times until we press the key 'n'. We have added the 'if' statement inside the while loop. The 'if' statement contains the break keyword, and the break keyword brings control out of the loop.
Unintentional infinite loops
Sometimes the situation arises where unintentional infinite loops occur due to the bug in the code. If we are the beginners, then it becomes very difficult to trace them. Below are some measures to trace an unintentional infinite loop:
- We should examine the semicolons carefully. Sometimes we put the semicolon at the wrong place, which leads to the infinite loop.
- #include <stdio.h>
- Int main()
- {
- Int i=1;
- While(i<=10);
- {
- Printf("%d", i);
- i++;
- }
- Return 0;
- }
In the above code, we put the semicolon after the condition of the while loop which leads to the infinite loop. Due to this semicolon, the internal body of the while loop will not execute.
- We should check the logical conditions carefully. Sometimes by mistake, we place the assignment operator (=) instead of a relational operator (= =).
- #include <stdio.h>
- Int main()
- {
- Char ch='n';
- While(ch='y')
- {
- Printf("hello");
- }
- Return 0;
- }
In the above code, we use the assignment operator (ch='y') which leads to the execution of loop infinite number of times.
- We use the wrong loop condition which causes the loop to be executed indefinitely.
- #include <stdio.h>
- Int main()
- {
- For(int i=1;i>=1;i++)
- {
- Printf("hello");
- }
- Return 0;
- }
The above code will execute the 'for loop' infinite number of times. As we put the condition (i>=1), which will always be true for every condition, it means that "hello" will be printed infinitely.
- We should be careful when we are using the break keyword in the nested loop because it will terminate the execution of the nearest loop, not the entire loop.
- #include <stdio.h>
- Int main()
- {
- While(1)
- {
- For(int i=1;i<=10;i++)
- {
- If(i%2==0)
- {
- Break;
- }
- }
- }
- Return 0;
- }
In the above code, the while loop will be executed an infinite number of times as we use the break keyword in an inner loop. This break keyword will bring the control out of the inner loop, not from the outer loop.
- We should be very careful when we are using the floating-point value inside the loop as we cannot underestimate the floating-point errors.
- #include <stdio.h>
- Int main()
- {
- Float x = 3.0;
- While (x != 4.0) {
- Printf("x = %f\n", x);
- x += 0.1;
- }
- Return 0;
- }
In the above code, the loop will run infinite times as the computer represents a floating-point value as a real value. The computer will represent the value of 4.0 as 3.999999 or 4.000001, so the condition (x !=4.0) will never be false. The solution to this problem is to write the condition as (k<=4.0).
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value of a variable. There are four types of storage classes in C
- Automatic
- External
- Static
- Register
Storage Classes | Storage Place | Default Value | Scope | Lifetime |
Auto | RAM | Garbage Value | Local | Within function |
Extern | RAM | Zero | Global | Till the end of the main program Maybe declared anywhere in the program |
Static | RAM | Zero | Local | Till the end of the main program, Retains value between multiple functions call |
Register | Register | Garbage Value | Local | Within the function |
Automatic
- Automatic variables are allocated memory automatically at runtime.
- The visibility of the automatic variables is limited to the block in which they are defined.
The scope of the automatic variables is limited to the block in which they are defined.
- The automatic variables are initialized to garbage by default.
- The memory assigned to automatic variables gets freed upon exiting from the block.
- The keyword used for defining automatic variables is auto.
- Every local variable is automatic in C by default.
Example 1
- #include <stdio.h>
- Int main()
- {
- Int a; //auto
- Char b;
- Float c;
- Printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
- Return 0;
- }
Output:
Garbagegarbagegarbage
Example 2
- #include <stdio.h>
- Int main()
- {
- Int a = 10,i;
- Printf("%d ",++a);
- {
- Int a = 20;
- For (i=0;i<3;i++)
- {
- Printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
- }
- }
- Printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
- }
Output:
11 20 20 20 11
Static
- The variables defined as static specifier can hold their value between the multiple function calls.
- Static local variables are visible only to the function or the block in which they are defined.
- A same static variable can be declared many times but can be assigned at only one time.
- Default initial value of the static integral variable is 0 otherwise null.
- The visibility of the static global variable is limited to the file in which it has declared.
- The keyword used to define static variable is static.
Example 1
- #include<stdio.h>
- Static char c;
- Static int i;
- Static float f;
- Static char s[100];
- Void main ()
- {
- Printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
- }
Output:
0 0 0.000000 (null)
Example 2
- #include<stdio.h>
- Void sum()
- {
- Static int a = 10;
- Static int b = 24;
- Printf("%d %d \n",a,b);
- a++;
- b++;
- }
- Void main()
- {
- Int i;
- For(i = 0; i< 3; i++)
- {
- Sum(); // The static variables holds their value between multiple function calls.
- }
- }
Output:
10 24
11 25
12 26
Register
- The variables defined as the register is allocated the memory into the CPU registers depending upon the size of the memory remaining in the CPU.
- We can not dereference the register variables, i.e., we can not use &operator for the register variable.
- The access time of the register variables is faster than the automatic variables.
- The initial default value of the register local variables is 0.
- The register keyword is used for the variable which should be stored in the CPU register. However, it is compiler?s choice whether or not; the variables can be stored in the register.
- We can store pointers into the register, i.e., a register can store the address of a variable.
- Static variables can not be stored into the register since we can not use more than one storage specifier for the same variable.
Example 1
- #include <stdio.h>
- Int main()
- {
- Register int a; // variable a is allocated memory in the CPU register. The initial default value of a is 0.
- Printf("%d",a);
- }
Output:
0
Example 2
- #include <stdio.h>
- Int main()
- {
- Register int a = 0;
- Printf("%u",&a); // This will give a compile time error since we can not access the address of a register variable.
- }
Output:
Main.c:5:5: error: address of register variable ?a? requested
Printf("%u",&a);
^~~~~~
External
- The external storage class is used to tell the compiler that the variable defined as extern is declared with an external linkage elsewhere in the program.
- The variables declared as extern are not allocated any memory. It is only declaration and intended to specify that the variable is declared elsewhere in the program.
- The default initial value of external integral type is 0 otherwise null.
- We can only initialize the extern variable globally, i.e., we can not initialize the external variable within any block or method.
- An external variable can be declared many times but can be initialized at only once.
- If a variable is declared as external then the compiler searches for that variable to be initialized somewhere in the program which may be extern or static. If it is not, then the compiler will show an error.
Example 1
- #include <stdio.h>
- Int main()
- {
- Extern int a;
- Printf("%d",a);
- }
Output
Main.c:(.text+0x6): undefined reference to a'
Collect2: error: ld returned 1 exit status
Example 2
- #include <stdio.h>
- Int a;
- Int main()
- {
- Extern int a; // variable a is defined globally, the memory will not be allocated to a
- Printf("%d",a);
- }
Output
0
Example 3
- #include <stdio.h>
- Int a;
- Int main()
- {
- Extern int a = 0; // this will show a compiler error since we can not use extern and initializer at same time
- Printf("%d",a);
- }
Output
Compile time error
Main.c: In function ?main?:
Main.c:5:16: error: ?a? has both ?extern? and initializer
Externint a = 0;
Example 4
- #include <stdio.h>
- Int main()
- {
- Extern int a; // Compiler will search here for a variable a defined and initialized somewhere in the pogram or not.
- Printf("%d",a);
- }
- Int a = 20;
Output
20
Example 5
- Extern int a;
- Int a = 10;
- #include <stdio.h>
- Int main()
- {
- Printf("%d",a);
- }
- Int a = 20; // compiler will show an error at this line
Output
Compile time error
Text Books:
[T1] Herbert Schildt, ―C: The Complete Reference‖, OsbourneMcgraw Hill, 4th Edition, 2002.
[T2] Forouzan Behrouz A. ―Computer Science: A Structured Programming Approach Using C, Cengage Learning 2/e
Reference Books:
[R1] Kernighan & Ritchie, ―C Programming Language‖, The (Ansi C version), PHI, 2/e
[R2] K.R Venugopal, ―Mastering C ‖, TMH
[R3] R.S. Salaria "Application Programming in C " Khanna Publishers4/e
[R4] YashwantKanetkar― Test your C Skills ‖ , BPB Publications
[R5] http://www.codeblocks.org/
[R6] http://gcc.gnu.org/
[R7] Programming in ANSI C, E. Balagurusamy; Mc Graw Hill, 6th Edition.