C Programs Notes
C Programs Notes
C language Tutorial with programming approach for beginners and professionals, helps you
to understand the C language tutorial easily. Our C tutorial explains each topic with
programs.
The C Language is developed by Dennis Ritchie for creating system applications that directly
interact with the hardware devices such as drivers, kernels, etc.
C programming is considered as the base for other programming languages, that is why it is
known as mother language.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid-level programming language
1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most
of the programming languages follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are being
used in many languages like C++, Java, C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural language
specifies a series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
In the C language, we break the program into parts using functions. It makes the program
easier to understand and modify.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy
to understand.
C Program
In this tutorial, all C programs are given with C compiler so that you can quickly change the
C program code.
File: main.c
1. #include <stdio.h>
2. int main() {
3. printf("Hello C Programming\n");
4. return 0;
5.[1.]
History of C Language
History of C language is interesting to know. Here we are going to discuss a brief history of
the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the
allocated memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.
How to install C
There are many compilers available for c and c++. You need to download any one. Here, we
are going to use Turbo C++. It will work for both C and C++. To install the Turbo C
software, you need to follow following steps.
Select Start installation by the down arrow key then press enter.
Now C is installed, press enter to read documentation or close the software.
To write the first c program, open the C console and write the following code:
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
#include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .
int main() The main() function is the entry point of every program in c language.
return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.
By menu
Now click on the compile menu then compile sub menu to compile the c program.
Then click on the run menu then run sub menu to run the c program.
By shortcut
Or, press ctrl+f9 keys compile and run the program directly.
Compilation process in c
What is a compilation?
The compilation is a process of converting the source code into object code. It is done with
the help of the compiler. The compiler checks the source code for the syntactical or structural
errors, and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the
directive and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed
into an executable form:
Preprocessor
Compiler
Assembler
Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is given
an extension ".c". This source code is first passed to the preprocessor, and then the
preprocessor expands this code. After expanding the code, the expanded code is passed to the
compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the
object file generated by the assembler is the same as the source file. The extension of the
object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is
'hello.c', then the name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The
main working of the linker is to combine the object code of library files with the object code
of our program. Sometimes the situation arises when our program refers to the functions
defined in other files; then linker plays a very important role in this. It links the object code of
these files to our program. Therefore, we conclude that the job of the linker is to link the
object code of our program with the object code of the library files and other files. The output
of the linker is the executable file. The name of the executable file is the same as the source
file but differs only in their extensions. In DOS, the extension of the executable file is '.exe',
and in UNIX, the executable file can be named as 'a.out'. For example, if we are using printf()
function in a program, then the linker adds its associated code in an output file.
hello.c
1. #include <stdio.h>
2. int main()
3. {
4. printf("Hello javaTpoint");
5. return 0;
6. }
Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor
converts the source code into expanded source code. The extension of the expanded source
code would be hello.i.
The expanded source code is passed to the compiler, and the compiler converts this
expanded source code into assembly code. The extension of the assembly code would be
hello.s.
This assembly code is then sent to the assembler, which converts the assembly code into
object code.
After the creation of an object code, the linker creates the executable file. The loader will
then load the executable file for the execution.
printf() function
The printf() function is used for output. It prints the given statement to the console.
1. printf("format string",argument_list);
scanf() function
The scanf() function is used for input. It reads the input data from the console.
1. scanf("format string",argument_list);
Let's see a simple example of c language that gets input from the user and prints the cube of
the given number.
1. #include<stdio.h>
2. int main(){
3. int number;
4. printf("enter a number:");
5. scanf("%d",&number);
6. printf("cube of number is:%d ",number*number*number);
7. return 0;
8. }
Output
enter a number:5
cube of number is:125
The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.
Let's see a simple example of input and output in C language that prints addition of 2
numbers.
1. #include<stdio.h>
2. int main(){
3. int x=0,y=0,result=0;
4.
5. printf("enter first number:");
6. scanf("%d",&x);
7. printf("enter second number:");
8. scanf("%d",&y);
9.
10. result=x+y;
11. printf("sum of 2 numbers:%d ",result);
12.
13. return 0;
14. }
Output
Variables in C
A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
1. type variable_list;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
1. int a;
2. int _ab;
3. int a30;
1. int 2;
2. int a b;
3. int long;
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
1. void function1(){
2. int x=10;//local variable
3. }
Global Variable
A variable that is declared outside the function or block is called a global variable. Any
function can change the value of the global variable. It is available to all the functions.
Static Variable
A variable that is declared with the static keyword is called static variable.
1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }
If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We
can explicitly declare an automatic variable using auto keyword.
1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }
External Variable
We can share a variable in multiple C source files by using an external variable. To declare
an external variable, you need to use extern keyword.
myfile.h
1. extern int x=10;//external variable (also global)
program1.c
1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
The memory size of the basic data types may change according to 32 or 64-bit operating
system.
Let's see the basic data types. Its size is given according to 32-bit architecture.
float 4 byte
double 8 byte
Keywords in C
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc.
There are only 32 reserved words (keywords) in the C language.
A list of 32 keywords in the c language is given below:
C Identifiers
C identifiers represent the name in the C program, for example, variables, functions, arrays,
structures, unions, labels, etc. An identifier can be composed of letters such as uppercase,
lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an
underscore. If the identifier is not used in the external linkage, then it is called as an internal
identifier. If the identifier is used in the external linkage, then it is called as an external
identifier.
We can say that an identifier is a collection of alphanumeric characters that begins either with
an alphabetical character or an underscore, which are used to represent various programming
elements such as variables, functions, arrays, structures, unions, labels, etc. There are 52
alphabetical characters (uppercase and lowercase), underscore character, and ten numerical
digits (0-9) that represent the identifiers. There is a total of 63 alphanumerical characters that
represent the identifiers.
Types of identifiers
Internal identifier
External identifier
Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal identifier.
The internal identifiers can be local variables.
External Identifier
If the identifier is used in the external linkage, then it is known as an external identifier. The
external identifiers can be function names, global variables.
1. int main()
2. {
3. int a=10;
4. int A=20;
5. printf("Value of a is : %d",a);
6. printf("\nValue of A is :%d",A);
7. return 0;
8. }
Output
Value of a is : 10
Value of A is :20
The above output shows that the values of both the variables, 'a' and 'A' are different.
Therefore, we conclude that the identifiers are case sensitive.
C Operators
An operator is simply a symbol that is used to perform operations. There can be many types
of operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.
Arithmetic Operators
Relational Operators
Shift Operators
Logical Operators
Bitwise Operators
Ternary or Conditional Operators
Assignment Operator
Misc Operator
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to
left.
1. int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).
Comments in C
Comments in C language are used to provide information about lines of code. It is widely
used for documenting code. There are 2 types of comments in the C language.
1. #include<stdio.h>
2. int main(){
3. //printing information
4. printf("Hello C");
5. return 0;
6. }
1. /*
2. code
3. to be commented
4. */
1. #include<stdio.h>
2. int main(){
3. /*printing information
4. Multi-Line Comment*/
5. printf("Hello C");
6. return 0;
7. }
C Format Specifier
The Format specifier is a string used in the formatted input and output functions. The format
string determines the format of the input and output. The format string always starts with a
'%' character.
Format
Description
specifier
It is used to print the signed integer value where signed integer means that the
%d or %i
variable can hold both positive and negative values.
It is used to print the unsigned integer value where the unsigned integer means
%u
that the variable can hold only positive value.
It is used to print the octal unsigned integer where octal integer value always
%o
starts with a 0 value.
It is used to print the hexadecimal unsigned integer where the hexadecimal
%x integer value always starts with a 0x value. In this, alphabetical characters are
printed in small letters such as a, b, c, etc.
It is used to print the hexadecimal unsigned integer, but %X prints the
%X
alphabetical characters in uppercase such as A, B, C, etc.
It is used for printing the decimal floating-point values. By default, it prints the
%f
6 values after '.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.
It is used to print the decimal floating-point values, and it uses the fixed
%g precision, i.e., the value after the decimal in input would be exactly the same as
the value in the output.
%p It is used to print the address in a hexadecimal form.
%c It is used to print the unsigned character.
%s It is used to print the strings.
%ld It is used to print the long-signed integer value.
%d
1. int main()
2. {
3. int b=6;
4. int c=8;
5. printf("Value of b is:%d", b);
6. printf("\nValue of c is:%d",c);
7.
8. return 0;
9. }
In the above code, we are printing the integer value of b and c by using the %d specifier.
Output
%u
1. int main()
2. {
3. int b=10;
4. int c= -10;
5. printf("Value of b is:%u", b);
6. printf("\nValue of c is:%u",c);
7.
8. return 0;
9. }
In the above program, we are displaying the value of b and c by using an unsigned format
specifier, i.e., %u. The value of b is positive, so %u specifier prints the exact value of b, but it
does not print the value of c as c contains the negative value.
Output
%o
1. int main()
2. {
3. int a=0100;
4. printf("Octal value of a is: %o", a);
5. printf("\nInteger value of a is: %d",a);
6. return 0;
7. }
In the above code, we are displaying the octal value and integer value of a.
Output
%x and %X
1. int main()
2. {
3. int y=0xA;
4. printf("Hexadecimal value of y is: %x", y);
5. printf("\nHexadecimal value of y is: %X",y);
6. printf("\nInteger value of y is: %d",y);
7. return 0;
8. }
In the above code, y contains the hexadecimal value 'A'. We display the hexadecimal value of
y in two formats. We use %x and %X to print the hexadecimal value where %x displays the
value in small letters, i.e., 'a' and %X displays the value in a capital letter, i.e., 'A'.
Output
%f
1. int main()
2. {
3. float y=3.4;
4. printf("Floating point value of y is: %f", y);
5. return 0;
6. }
Output
%e
1. int main()
2. {
3. float y=3;
4. printf("Exponential value of y is: %e", y);
5. return 0;
6. }
Output
%E
1. int main()
2. {
3. float y=3;
4. printf("Exponential value of y is: %E", y);
5. return 0;
6. }
Output
%g
1. int main()
2. {
3. float y=3.8;
4. printf("Float value of y is: %g", y);
5. return 0;
6. }
In the above code, we are displaying the floating value of y by using %g specifier. The %g
specifier displays the output same as the input with a same precision.
Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't represent itself
when used inside string literal or character.
It is composed of two or more characters starting with backslash \. For example: \n represents
new line.
In C programming language, a character variable does not contain a character value itself
rather the ascii value of the character variable. The ascii value represents the character
variable in numbers, and each character variable is assigned with some number range from 0
to 127. For example, the ascii value of 'A' is 65.
In the above example, we assign 'A' to the character variable whose ascii value is 65, so 65
will be stored in the character variable rather than 'A'.
We will create a program which will display the ascii value of the character variable.
1. #include <stdio.h>
2. int main()
3. {
4. char ch; // variable declaration
5. printf("Enter a character");
6. scanf("%c",&ch); // user input
7. printf("\n The ascii value of the ch variable is : %d", ch);
8. return 0;
9. }
In the above code, the first user will give the character input, and the input will get stored in
the 'ch' variable. If we print the value of the 'ch' variable by using %c format specifier, then it
will display 'A' because we have given the character input as 'A', and if we use the %d format
specifier then its ascii value will be displayed, i.e., 65.
Output
The above output shows that the user gave the input as 'A', and after giving input, the ascii
value of 'A' will get printed, i.e., 65.
Now, we will create a program which will display the ascii value of all the characters.
1. #include <stdio.h>
2. int main()
3. {
4. int k; // variable declaration
5. for(int k=0;k<=255;k++) // for loop from 0-255
6. {
7. printf("\nThe ascii value of %c is %d", k,k);
8. }
9. return 0;
10. }
Constants in C
A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a',
3.4, "c programming" etc.
List of Constants in C
Constant Example
1. const keyword
2. #define preprocessor
1) C const keyword
The const keyword is used to define constant in C programming.
1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. printf("The value of PI is: %f",PI);
5. return 0;
6. }
Output:
If you try to change the the value of PI, it will render compile time error.
1. #include<stdio.h>
2. int main(){
3. const float PI=3.14;
4. PI=4.5;
5. printf("The value of PI is: %f",PI);
6. return 0;
7. }
Output:
2) C #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define
preprocessor directive later.
Types of literals
There are four types of literals that exist in C programming:
Integer literal
Float literal
Character literal
String literal
Integer literal
It is a numeric literal that represents only integer type values. It represents the value neither in
fractional nor exponential part.
It is defined by representing the digits between 0 to 9. For example, 45, 67, etc.
L or l: It is a size qualifier that specifies the size of the integer type as long.
U or u: It is a sign qualifier that represents the type of the integer as unsigned. An unsigned
qualifier contains only positive values.
Note: The order of the qualifier is not considered, i.e., both lu and ul are the same.
1. #include <stdio.h>
2. int main()
3. {
4. const int a=23; // constant integer literal
5. printf("Integer literal : %d", a);
6. return 0;
7. }
Output
Integer literal : 23
Float literal
It is a literal that contains only floating-point values or real numbers. These real numbers
contain the number of parts such as integer part, real part, exponential part, and fractional
part. The floating-point literal must be specified either in decimal or in exponential form.
Let's understand these forms in brief.
Decimal form
The decimal form must contain either decimal point, exponential part, or both. If it does not
contain either of these, then the compiler will throw an error. The decimal notation can be
prefixed either by '+' or '-' symbol that specifies the positive and negative numbers.
1. #include <stdio.h>
2. int main()
3. {
4. const float a=4.5; // constant float literal
5. const float b=5.6; // constant float literal
6. float sum;
7. sum=a+b;
8. printf("%f", sum);
9. return 0;
10. }
Output
10.100000
Exponential form
The exponential form is useful when we want to represent the number, which is having a big
magnitude. It contains two parts, i.e., mantissa and exponent. For example, the number is
2340000000000, and it can be expressed as 2.34e12 in an exponential form.
A character literal contains a single character enclosed within single quotes. If multiple
characters are assigned to the variable, then we need to create a character array. If we try to
store more than one character in a variable, then the warning of a multi-character character
constant will be generated. Let's observe this scenario through an example.
1. #include <stdio.h>
2. int main()
3. {
4. const char c='ak';
5. printf("%c",c);
6. return 0;
7. }
String literal
For example,
String1= "javatpoint";
Tokens in C
Tokens in C is the most important element to be used in creating a program in C. We can
define the token as the smallest individual element in C. For `example, we cannot create a
sentence without using words; similarly, we cannot create a program in C without using
tokens in C. Therefore, we can say that tokens in C is the building block or the basic
component for creating a program in C language.
Classification of tokens in C
Keywords in C
Keywords in C can be defined as the pre-defined or the reserved words having its own
importance, and each keyword has its own functionality. Since keywords are the pre-defined
words used by the compiler, so they cannot be used as the variable names. If the keywords
are used as the variable names, it means that we are assigning a different meaning to the
keyword, which is not allowed. C language supports 32 keywords given below:
Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in
C are the user-defined words. It can be composed of uppercase letters, lowercase letters,
underscore, or digits, but the starting letter should be either an underscore or an alphabet.
Identifiers cannot be used as keywords. Rules for constructing identifiers in C are given
below:
The first character of an identifier should be either an alphabet or an underscore, and then it
can be followed by any of the character, digit, or underscore.
It should not begin with any numerical digit.
In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that
identifiers are case sensitive.
Commas or blank spaces cannot be specified within an identifier.
Keywords cannot be represented as an identifier.
The length of the identifiers should not be more than 31 characters.
Identifiers should be written in such a way that it is meaningful, short, and easy to read.
Strings in C
Strings in C are always represented as an array of characters having null character '\0' at the
end of the string. This null character denotes the end of the string. Strings in C are enclosed
within double quotes, while characters are enclosed within single characters. The size of a
string is a number of characters that the string contains.
char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.
char a[] = "javatpoint"; // The compiler allocates the memory at the run time.
Operators in C
Operators in C is a special symbol used to perform the functions. The data items on which the
operators are applied are known as operands. Operators are applied between the operands.
Depending on the number of operands, operators are classified as follows:
Unary Operator
A unary operator is an operator applied to the single operand. For example: increment
operator (++), decrement operator (--), sizeof, (type)*.
Binary Operator
The binary operator is an operator applied between two operands. The following is the list of
the binary operators:
Arithmetic Operators
Relational Operators
Shift Operators
Logical Operators
Bitwise Operators
Conditional Operators
Assignment Operator
Misc Operator
Constants in C
A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.
Types of constants in C
Constant Example
Special characters in C
Some special characters are used in C, and they have a special meaning which cannot be used
for another purpose.
Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
Simple brackets ( ): It is used in function declaration and function calling. For example,
printf() is a pre-defined function.
Curly braces { }: It is used in the opening and closing of the code. It is used in the opening
and closing of the loops.
Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when printing the
value of more than one variable using a single printf statement.
Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that we
are using the header file.
Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
Tilde (~): It is used as a destructor to free memory.
Period (.): It is used to access a member of a structure or a union.
C Boolean
In C, Boolean is a data type that contains two types of values, i.e., 0 and 1. Basically, the bool
type value represents two types of behavior, either true or false. Here, '0' represents false
value, while '1' represents true value.
In C Boolean, '0' is stored as 0, and another integer is stored as 1. We do not require to use
any header file to use the Boolean data type in C++, but in C, we have to use the header file,
i.e., stdbool.h. If we do not use the header file, then the program will not compile.
Syntax
1. bool variable_name;
Static in C
Static is a keyword used in C programming language. It can be used with both variables and
functions, i.e., we can declare a static variable and static function as well. An ordinary
variable is limited to the scope in which it is defined, while the scope of the static variable is
throughout the program.
1. #include <stdio.h>
2. int main()
3. {
4. printf("%d",func());
5. printf("\n%d",func());
6. return 0;
7. }
8. int func()
9. {
10. int count=0; // variable initialization
11. count++; // incrementing counter variable
12.
13. return count; }
In the above code, the func() function is called. In func(), count variable gets updated. As
soon as the function completes its execution, the memory of the count variable will be
removed. If we do not want to remove the count from memory, then we need to use the count
variable as static. If we declare the variable as static, then the variable will not be removed
from the memory even when the function completes its execution.
Static variable
A static variable is a variable that persists its value across the various function calls.
Syntax
1. #include <stdio.h>
2. int main()
3. {
4. printf("%d",func());
5. printf("\n%d",func());
6.
7. return 0;
8. }
9. int func()
10. {
11. static int count=0;
12. count++;
13. return count;
14. }
In the above code, we have declared the count variable as static. When the func() is called,
the value of count gets updated to 1, and during the next function call, the value of the count
variable becomes 2. Therefore, we can say that the value of the static variable persists within
the function call.
Output
1
2
Static Function
As we know that non-static functions are global by default means that the function can be
accessed outside the file also, but if we declare the function as static, then it limits the
function scope. The static function can be accessed within a file only.
Global variables are the variables that are declared outside the function. These global
variables exist at the beginning of the program, and its scope remains till the end of the
program. It can be accessed outside the program also.
Static variables are limited to the source file in which they are defined, i.e., they are not
accessible by the other source files.
Both the static and global variables have static initialization. Here, static initialization means
if we do not assign any value to the variable then by default, 0 value will be assigned to the
variable.
If the variable declared with a static keyword outside the function, then it is known as a static
global variable. It is accessible throughout the program.
The variable with a static keyword is declared inside a function is known as a static local
variable. The scope of the static local variable will be the same as the automatic local
variables, but its memory will be available throughout the program execution. When the
function modifies the value of the static local variable during one function call, then it will
remain the same even during the next function call.
Programming Errors in C
Errors are the problems or the faults that occur in the program, which makes the behavior of
the program abnormal, and experienced developers can also make these faults. Programming
errors are also known as the bugs or faults, and the process of removing these bugs is known
as debugging.
These errors are detected either during the time of compilation or execution. Thus, the errors
must be removed from the program for the successful execution of the program.
Syntax error
Run-time error
Linker error
Logical error
Semantic error
Syntax error
Syntax errors are also known as the compilation errors as they occurred at the compilation
time, or we can say that the syntax errors are thrown by the compilers. These errors are
mainly occurred due to the mistakes while typing or do not follow the syntax of the specified
programming language. These mistakes are generally made by beginners only because they
are new to the language. These errors can be easily debugged or corrected.
For example:
1. #include <stdio.h>
2. int main()
3. {
4. a = 10;
5. printf("The value of a is : %d", a);
6. return 0;
7. }
Output
In the above output, we observe that the code throws the error that 'a' is undeclared. This error
is nothing but the syntax error only.
There can be another possibility in which the syntax error can exist, i.e., if we make mistakes
in the basic construct. Let's understand this scenario through an example.
1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. if(.) // syntax error
6.
7. printf("a is greater than 1");
8. return 0;
9. }
In the above code, we put the (.) instead of condition in 'if', so this generates the syntax error
as shown in the below screenshot.
Output
Run-time error
Sometimes the errors exist during the execution-time even after the successful compilation
known as run-time errors. When the program is running, and it is not able to perform the
operation is the main cause of the run-time error. The division by zero is the common
example of the run-time error. These errors are very difficult to find, as the compiler does not
point to these errors.
Let's understand through an example.
1. #include <stdio.h>
2. int main()
3. {
4. int a=2;
5. int b=2/0;
6. printf("The value of b is : %d", b);
7. return 0;
8. }
Output
In the above output, we observe that the code shows the run-time error, i.e., division by zero.
Linker error
Linker errors are mainly generated when the executable file of the program is not created.
This can be happened either due to the wrong function prototyping or usage of the wrong
header file. For example, the main.c file contains the sub() function whose declaration and
definition is done in some other file such as func.c. During the compilation, the compiler
finds the sub() function in func.c file, so it generates two object files, i.e., main.o and func.o.
At the execution time, if the definition of sub() function is not found in the func.o file, then
the linker error will be thrown. The most common linker error that occurs is that we use
Main() instead of main().
1. #include <stdio.h>
2. int Main()
3. {
4. int a=78;
5. printf("The value of a is : %d", a);
6. return 0;
7. }
Output
Logical error
The logical error is an error that leads to an undesired output. These errors produce the
incorrect output, but they are error-free, known as logical errors. These types of mistakes are
mainly done by beginners. The occurrence of these errors mainly depends upon the logical
thinking of the developer. If the programmers sound logically good, then there will be fewer
chances of these errors.
1. #include <stdio.h>
2. int main()
3. {
4. int sum=0; // variable initialization
5. int k=1;
6. for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loop
7. {
8. sum=sum+k;
9. k++;
10. }
11. printf("The value of sum is %d", sum);
12. return 0;
13. }
Output
In the above code, we are trying to print the sum of 10 digits, but we got the wrong output as
we put the semicolon (;) after the for loop, so the inner statements of the for loop will not
execute. This produces the wrong output.
Semantic error
Semantic errors are the errors that occurred when the statements are not understandable by
the compiler.
1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. a=2;
6. b=3;
7. c=1;
8. a+b=c; // semantic error
9. return 0;
10. }
In the above code, we use the statement a+b =c, which is incorrect as we cannot use the two
operands on the left-side.
Output
Compile-time errors are the errors that occurred when we write the wrong syntax. If we write
the wrong syntax or semantics of any programming language, then the compile-time errors
will be thrown by the compiler. The compiler will not allow to run the program until all the
errors are removed from the program. When all the errors are removed from the program,
then the compiler will generate the executable file.
Syntax errors
Semantic errors
Syntax errors
When the programmer does not follow the syntax of any programming language, then the
compiler will throw the syntax error.
For example,
int a, b:
The above declaration generates the compile-time error as in C, every statement ends with the
semicolon, but we put a colon (:) at the end of the statement.
Semantic errors
The semantic errors exist when the statements are not meaningful to the compiler.
For example,
a+b=c;
The above statement throws a compile-time errors. In the above statement, we are assigning
the value of 'c' to the summation of 'a' and 'b' which is not possible in C programming
language as it can contain only one variable on the left of the assignment operator while right
of the assignment operator can contain more than one variable.
c=a+b;
Runtime errors
The runtime errors are the errors that occur during the execution and after compilation. The
examples of runtime errors are division by zero, etc. These errors are not easy to detect as the
compiler does not point to these errors.
The compile-time errors are the errors which The runtime errors are the errors which are not
are produced at the compile-time, and they generated by the compiler and produce an
are detected by the compiler. unpredictable result at the execution time.
1. #include <stdio.h>
2. int main()
3. {
4. int a=20;
5. printf("The value of a is : %d",a):
6. return 0;
7. }
In the above code, we have tried to print the value of 'a', but it throws an error. We put the
colon at the end of the statement instead of a semicolon, so this code generates a compile-
time error.
Conditional Operator in C
The conditional operator is also known as a ternary operator. The conditional statements are
the decision-making statements which depends upon the output of the expression. It is
represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else'
statement is also a decision-making statement.
In the above syntax, the expression1 is a Boolean condition that can be either true or false
value.
If the expression1 results into a true value, then the expression2 will execute.
The expression2 is said to be true only when it returns a non-zero value.
If the expression1 returns false value then the expression3 will execute.
The expression3 is said to be false only when it returns zero value.
1. #include <stdio.h>
2. int main()
3. {
4. int age; // variable declaration
5. printf("Enter your age");
6. scanf("%d",&age); // taking user input for age variable
7. (age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional o
perator
8. return 0;
9. }
In the above code, we are taking input as the 'age' of the user. After taking input, we have
applied the condition by using a conditional operator. In this condition, we are checking the
age of the user. If the age of the user is greater than or equal to 18, then the statement1 will
execute, i.e., (printf("eligible for voting")) otherwise, statement2 will execute, i.e.,
(printf("not eligible for voting")).
If we provide the age of user below 18, then the output would be:
If we provide the age of user above 18, then the output would be:
As we can observe from the above two outputs that if the condition is true, then the
statement1 is executed; otherwise, statement2 will be executed.
Till now, we have observed that how conditional operator checks the condition and based on
condition, it executes the statements. Now, we will see how a conditional operator is used to
assign the value to a variable.
1. #include <stdio.h>
2. int main()
3. {
4. int a=5,b; // variable declaration
5. b=((a==5)?(3):(2)); // conditional operator
6. printf("The value of 'b' variable is : %d",b);
7. return 0;
8. }
In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value to the 'a'
variable. After the declaration, we are assigning value to the 'b' variable by using the
conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a 3 value
otherwise 2.
Output
The above output shows that the value of 'b' variable is 3 because the value of 'a' variable is
equal to 5.
As we know that the behavior of conditional operator and 'if-else' is similar but they have
some differences. Let's look at their differences.
Bitwise Operator in C
The bitwise operators are the operators used to perform the operations on the data at the bit-
level. When we perform the bitwise operations, then it is also known as bit-level
programming. It consists of two digits, either 0 or 1. It is mainly used in numerical
computations to make the calculations faster.
We have different types of bitwise operators in the C programming language. The following
is the list of the bitwise operators:
| Bitwise OR operator
0 00 0 0
0 10 1 1
1 00 1 1
1 11 1 1
Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands
are written on both sides of the (&) operator. If the corresponding bits of both the operands
are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0.
For example,
As we can observe from the above result that bits of both the variables are compared one by
one. If the bit of both the variables is 1 then the output would be 1, otherwise 0.
1. #include <stdio.h>
2. int main()
3. {
4. int a=6, b=14; // variable declarations
5. printf("The output of the Bitwise AND operator a&b is %d",a&b);
6. return 0;
7. }
In the above code, we have created two variables, i.e., 'a' and 'b'. The values of 'a' and 'b' are 6
and 14 respectively. The binary value of 'a' and 'b' are 0110 and 1110, respectively. When we
apply the AND operator between these two variables,
Output
Bitwise OR operator
The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are
written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the
output would be 1, otherwise 0.
For example,
As we can observe from the above result that the bits of both the operands are compared one
by one; if the value of either bit is 1, then the output would be 1 otherwise 0.
1. #include <stdio.h>
2. int main()
3. {
4. int a=23,b=10; // variable declarations
5. printf("The output of the Bitwise OR operator a|b is %d",a|b);
6. return 0;
7. }
Output
Bitwise exclusive OR operator
Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both
sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then
the output would be 1, otherwise 0.
For example,
As we can observe from the above result that the bits of both the operands are compared one
by one; if the corresponding bit value of any of the operand is 1, then the output would be 1
otherwise 0.
1. #include <stdio.h>
2. int main()
3. {
4. int a=12,b=10; // variable declarations
5. printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);
6. return 0;
7. }
Output
Bitwise complement operator
For example,
As we can observe from the above result that if the bit is 1, then it gets changed to 0 else 1.
1. #include <stdio.h>
2. int main()
3. {
4. int a=8; // variable declarations
5. printf("The output of the Bitwise complement operator ~a is %d",~a);
6. return 0;
7. }
Output
Bitwise shift operators
Two types of bitwise shift operators exist in C programming. The bitwise shift operators will
shift the bits either on the left-side or right-side. Therefore, we can say that the bitwise shift
operator is divided into two categories:
Left-shift operator
Right-shift operator
Left-shift operator
1. Operand << n
Where,
In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n' bits on the left
side will be popped out, and 'n' bits on the right-side are filled with 0.
For example,
1. #include <stdio.h>
2. int main()
3. {
4. int a=5; // variable initialization
5. printf("The value of a<<2 is : %d ", a<<2);
6. return 0;
7. }
Output
Right-shift operator
1. Operand >> n;
Where,
In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The 'n' bits on
the right-side will be popped out, and 'n' bits on the left-side are filled with 0.
For example,
1. #include <stdio.h>
2. int main()
3. {
4. int a=7; // variable initialization
5. printf("The value of a>>2 is : %d ", a>>2);
6. return 0;
7. }
Output
C 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.
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.
1. if(expression){
2. //code to be executed
3. }
Flowchart of if statement in C
Let's see a simple example of C language if statement.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("Enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. return 0;
10. }
Output
Enter a number:4
4 is even number
enter a number:5
Program to find the largest number of the three.
1. #include <stdio.h>
2. int main()
3. {
4. int a, b, c;
5. printf("Enter three numbers?");
6. scanf("%d %d %d",&a,&b,&c);
7. if(a>b && a>c)
8. {
9. printf("%d is largest",a);
10. }
11. if(b>a && b > c)
12. {
13. printf("%d is largest",b);
14. }
15. if(c>a && c>b)
16. {
17. printf("%d is largest",c);
18. }
19. if(a == b && a == c)
20. {
21. printf("All are equal");
22. }
23. }
Output
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.
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number%2==0){
7. printf("%d is even number",number);
8. }
9. else{
10. printf("%d is odd number",number);
11. }
12. return 0;
13. }
Output
enter a number:4
4 is even number
enter a number:5
5 is odd number
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. if(number==10){
7. printf("number is equals to 10");
8. }
9. else if(number==50){
10. printf("number is equal to 50");
11. }
12. else if(number==100){
13. printf("number is equal to 100");
14. }
15. else{
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
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.
1. #include <stdio.h>
2. int main()
3. {
4. int marks;
5. printf("Enter your marks?");
6. scanf("%d",&marks);
7. if(marks > 85 && marks <= 100)
8. {
9. printf("Congrats ! you scored grade A ...");
10. }
11. else if (marks > 60 && marks <= 85)
12. {
13. printf("You scored grade B + ...");
14. }
15. else if (marks > 40 && marks <= 60)
16. {
17. printf("You scored grade B ...");
18. }
19. else if (marks > 30 && marks <= 40)
20. {
21. printf("You scored grade C ...");
22. }
23. else
24. {
25. printf("Sorry you are fail ...");
26. }
27. }
Output
C 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 in c language is given below:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
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.
1. int x,y,z;
2. char a,b;
3. float f;
1. #include<stdio.h>
2. int main(){
3. int number=0;
4. printf("enter a number:");
5. scanf("%d",&number);
6. switch(number){
7. case 10:
8. printf("number is equals to 10");
9. break;
10. case 50:
11. printf("number is equal to 50");
12. break;
13. case 100:
14. printf("number is equal to 100");
15. break;
16. default:
17. printf("number is not equal to 10, 50 or 100");
18. }
19. return 0;
20. }
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
1. #include <stdio.h>
2. int main()
3. {
4. int x = 10, y = 5;
5. switch(x>y && x+y>0)
6. {
7. case 1:
8. printf("hi");
9. break;
10. case 0:
11. printf("bye");
12. break;
13. default:
14. printf(" Hello bye ");
15. }
16.
17. }
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.
1. #include<stdio.h>
2. int main(){
3. int number=0;
4.
5. printf("enter a number:");
6. scanf("%d",&number);
7.
8. switch(number){
9. case 10:
10. printf("number is equal to 10\n");
11. case 50:
12. printf("number is equal to 50\n");
13. case 100:
14. printf("number is equal to 100\n");
15. default:
16. printf("number is not equal to 10, 50 or 100");
17. }
18. return 0;
19. }
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
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.
1. #include <stdio.h>
2. int main () {
3.
4. int i = 10;
5. int j = 20;
6.
7. switch(i) {
8.
9. case 10:
10. printf("the value of i evaluated in outer switch: %d\n",i);
11. case 20:
12. switch(j) {
13. case 20:
14. printf("The value of j evaluated in nested switch: %d\n",j);
15. }
16. }
17.
18. printf("Exact value of i is : %d\n", i );
19. printf("Exact value of j is : %d\n", j );
20.
21. return 0;
22. }
if-else vs switch
What is an if-else statement?
1. if(expression)
2. {
3. // statements;
4. }
5. else
6. {
7. // statements;
8. }
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.
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
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
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
First, the condition is checked. If It executes one case after another till the break
Sequence of
the condition is true then 'if' block keyword is not found, or the default statement is
execution
is executed otherwise 'else' block executed.
Default If the condition is not true, then by If the value does not match with any case, then
execution default, else block will be executed. by default, default statement is executed.
C 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.
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:
1. do while
2. while
3. 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).
1. do{
2. //code to be executed
3. }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.
1. while(condition){
2. //code to be executed
3. }
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:
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
do while loop in C
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.
1. do{
2. //code to be executed
3. }while(condition);
Example 1
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. char c;
6. int choice,dummy;
7. do{
8. printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
9. scanf("%d",&choice);
10. switch(choice)
11. {
12. case 1 :
13. printf("Hello");
14. break;
15. case 2:
16. printf("Javatpoint");
17. break;
18. case 3:
19. exit(0);
20. break;
21. default:
22. printf("please enter valid choice");
23. }
24. printf("do you want to enter more?");
25. scanf("%d",&dummy);
26. scanf("%c",&c);
27. }while(c=='y');
28. }
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
do while example
There is given the simple program of c language do while loop where we are printing the
table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. do{
5. printf("%d \n",i);
6. i++;
7. }while(i<=10);
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
Program to print table for the given number using do while loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. do{
7. printf("%d \n",(number*i));
8. i++;
9. }while(i<=10);
10. return 0;
11. }
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.
1. do{
2. //statement
3. }while(1);
while loop in C
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.
1. while(condition){
2. //code to be executed
3. }
1. #include<stdio.h>
2. int main(){
3. int i=1;
4. while(i<=10){
5. printf("%d \n",i);
6. i++;
7. }
8. return 0;
9. }
Output
1
2
3
4
5
6
7
8
9
10
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
Example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int j = 1;
5. while(j+=2,j<=10)
6. {
7. printf("%d ",j);
8. }
9. printf("%d",j);
10. }
Output
3 5 7 9 11
Example 2
1. #include<stdio.h>
2. void main ()
3. {
4. while()
5. {
6. printf("hello Javatpoint");
7. }
8. }
Output
compile time error: while loop can't be empty
Example 3
1. #include<stdio.h>
2. void main ()
3. {
4. int x = 10, y = 2;
5. while(x+y-1)
6. {
7. printf("%d %d",x--,y--);
8. }
9. }
Output
infinite loop
1. while(1){
2. //statement
3. }
for loop in C
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.
Let's see the simple program of for loop that prints table of 1.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. for(i=1;i<=10;i++){
5. printf("%d \n",i);
6. }
7. return 0;
8. }
Output
1
2
3
4
5
6
7
8
9
10
C Program: Print table for the given number using C for loop
1. #include<stdio.h>
2. int main(){
3. int i=1,number=0;
4. printf("Enter a number: ");
5. scanf("%d",&number);
6. for(i=1;i<=10;i++){
7. printf("%d \n",(number*i));
8. }
9. return 0;
10. }
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
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a,b,c;
5. for(a=0,b=12,c=23;a<2;a++)
6. {
7. printf("%d ",a+b+c);
8. }
9. }
Output
35 36
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. for(;i<5;i++)
6. {
7. printf("%d ",i);
8. }
9. }
Output
1 2 3 4
Properties of Expression 2
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;i<=4;i++)
6. {
7. printf("%d ",i);
8. }
9. }
output
0 1 2 3 4
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int i,j,k;
5. for(i=0,j=0,k=0;i<4,k<8,j<10;i++)
6. {
7. printf("%d %d %d\n",i,j,k);
8. j+=2;
9. k+=3;
10. }
11. }
Output
0 0 0
1 2 3
2 4 6
3 6 9
4 8 12
Example 3
1. #include <stdio.h>
2. int main()
3. {
4. int i;
5. for(i=0;;i++)
6. {
7. printf("%d",i);
8. }
9. }
Output
infinite loop
Properties of Expression 3
Example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int i=0,j=2;
5. for(i = 0;i<5;i++,j=j+2)
6. {
7. printf("%d %d\n",i,j);
8. }
9. }
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.
1. #include<stdio.h>
2. void main ()
3. {
4. int i;
5. for(i=0;i<10;i++)
6. {
7. int i = 20;
8. printf("%d ",i);
9. }
10. }
Output
20 20 20 20 20 20 20 20 20 20
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.
1. #include<stdio.h>
2. void main ()
3. {
4. for(;;)
5. {
6. printf("welcome to javatpoint");
7. }
8. }
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.
1. Outer_loop
2. {
3. Inner_loop
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do-
while' loop.
The nested for loop means any type of loop which is defined inside the 'for' loop.
1. #include <stdio.h>
2. int main()
3. {
4. int n;// variable declaration
5. printf("Enter the value of n :");
6. // Displaying the n tables.
7. for(int i=1;i<=n;i++) // outer loop
8. {
9. for(int j=1;j<=10;j++) // inner loop
10. {
11. printf("%d\t",(i*j)); // printing the value.
12. }
13. printf("\n");
14. }
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:
The nested while loop means any type of loop which is defined inside the 'while' loop.
1. while(condition)
2. {
3. while(condition)
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Example of nested while loop
1. #include <stdio.h>
2. int main()
3. {
4. int rows; // variable declaration
5. int columns; // variable declaration
6. int k=1; // variable initialization
7. printf("Enter the number of rows :"); // input the number of rows.
8. scanf("%d",&rows);
9. printf("\nEnter the number of columns :"); // input the number of columns.
10. scanf("%d",&columns);
11. int a[rows][columns]; //2d array declaration
12. int i=1;
13. while(i<=rows) // outer loop
14. {
15. int j=1;
16. while(j<=columns) // inner loop
17. {
18. printf("%d\t",k); // printing the value of k.
19. k++; // increment counter
20. j++;
21. }
22. i++;
23. printf("\n");
24. }
25. }
Output:
Nested do..while loop
The nested do..while loop means any type of loop which is defined inside the 'do..while' loop.
1. do
2. {
3. do
4. {
5. // inner loop statements.
6. }while(condition);
7. // outer loop statements.
8. }while(condition);
1. #include <stdio.h>
2. int main()
3. {
4. /*printing the pattern
5. ********
6. ********
7. ********
8. ******** */
9. int i=1;
10. do // outer loop
11. {
12. int j=1;
13. do // inner loop
14. {
15. printf("*");
16. j++;
17. }while(j<=8);
18. printf("\n");
19. i++;
20. }while(i<=4);
21. }
Output:
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.
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:
1. for(; ;)
2. {
3. // body of the for loop.
4. }
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.
1. #include <stdio.h>
2. int main()
3. {
4. for(;;)
5. {
6. printf("Hello javatpoint");
7. }
8. return 0;
9. }
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:
1. while(1)
2. {
3. // body of the loop..
4. }
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.
1. #include <stdio.h>
2. int main()
3. {
4. int i=0;
5. while(1)
6. {
7. i++;
8. printf("i is :%d",i);
9. }
10. return 0;
11. }
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.
1. do
2. {
3. // body of the loop..
4. }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.
1. infinite_loop;
2. // body statements.
3. 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.
1. #include <stdio.h>
2. #define infinite for(;;)
3. int main()
4. {
5.
6. infinite
7. {
8. printf("hello");
9. }
10.
11. return 0;
12. }
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.
1. #include <stdio.h>
2. int main()
3. {
4. char ch;
5. while(1)
6. {
7. ch=getchar();
8. if(ch=='n')
9. {
10. break;
11. }
12. printf("hello");
13. }
14. return 0;
15. }
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.
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.
1. #include <stdio.h>
2. int main()
3. {
4. int i=1;
5. while(i<=10);
6. {
7. printf("%d", i);
8. i++;
9. }
10. return 0;
11. }
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 (= =).
1. #include <stdio.h>
2. int main()
3. {
4. char ch='n';
5. while(ch='y')
6. {
7. printf("hello");
8. }
9. return 0;
10. }
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.
1. #include <stdio.h>
2. int main()
3. {
4. for(int i=1;i>=1;i++)
5. {
6. printf("hello");
7. }
8. return 0;
9. }
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.
1. #include <stdio.h>
2. int main()
3. {
4. while(1)
5. {
6. for(int i=1;i<=10;i++)
7. {
8. if(i%2==0)
9. {
10. break;
11. }
12. }
13. }
14. return 0;
15. }
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.
1. #include <stdio.h>
2. int main()
3. {
4. float x = 3.0;
5. while (x != 4.0) {
6. printf("x = %f\n", x);
7. x += 0.1;
8. }
9. return 0;
10. }
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).
C break statement
The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the loop
one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. The break statement in C can be used in the following two scenarios:
Syntax:
Flowchart of break in c
Example
1. #include<stdio.h>
2. #include<stdlib.h>
3. void main ()
4. {
5. int i;
6. for(i = 0; i<10; i++)
7. {
8. printf("%d ",i);
9. if(i == 5)
10. break;
11. }
12. printf("came outside of loop i = %d",i);
13.
14. }
Output
Click here to see the example of C break with the switch statement.
1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. printf("%d &d\n",i,j);
7. if(i==2 && j==2){
8. break;//will break loop of j only
9. }
10. }//end of for loop
11. return 0;
12. }
Output
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
As you can see the output on the console, 2 3 is not printed because there is a break statement
after printing i==2 and j==2. But 3 1, 3 2 and 3 3 are printed because the break statement is
used to break the inner loop only.
Output
1. #include<stdio.h>
2. void main ()
3. {
4. int n=2,i,choice;
5. do
6. {
7. i=1;
8. while(i<=10)
9. {
10. printf("%d X %d = %d\n",n,i,n*i);
11. i++;
12. }
13. printf("do you want to continue with the table of %d , enter any non-zero value to contin
ue.",n+1);
14. scanf("%d",&choice);
15. if(choice == 0)
16. {
17. break;
18. }
19. n++;
20. }while(1);
21. }
Output
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
do you want to continue with the table of 3 , enter any non-zero value to
continue.1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
do you want to continue with the table of 4 , enter any non-zero value to
continue.0
C continue statement
The continue statement in C language is used to bring the program control to the beginning
of the loop. The continue statement skips some lines of code inside the loop and continues
with the next iteration. It is mainly used for a condition so that we can skip some code for a
particular condition.
Syntax:
1. //loop statements
2. continue;
3. //some lines of the code which is to be skipped
Output
infinite loop
Continue statement example 2
1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }
Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.
1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. if(i==2 && j==2){
7. continue;//will continue loop of j only
8. }
9. printf("%d %d\n",i,j);
10. }
11. }//end of for loop
12. return 0;
13. }
Output
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and
j==2.
C goto statement
The goto statement is known as jump statement in C. As the name suggests, goto is used to
transfer the program control to a predefined label. The goto statment can be used to repeat
some part of the code for a particular condition. It can also be used to break the multiple
loops which can't be done by using a single break statement. However, using goto is avoided
these days since it makes the program less readable and complecated.
Syntax:
1. label:
2. //some part of the code;
3. goto label;
goto example
Let's see a simple example to use goto statement in C language.
1. #include <stdio.h>
2. int main()
3. {
4. int num,i=1;
5. printf("Enter the number whose table you want to print?");
6. scanf("%d",&num);
7. table:
8. printf("%d x %d = %d\n",num,i,num*i);
9. i++;
10. if(i<=10)
11. goto table;
12. }
Output:
1. #include <stdio.h>
2. int main()
3. {
4. int i, j, k;
5. for(i=0;i<10;i++)
6. {
7. for(j=0;j<5;j++)
8. {
9. for(k=0;k<3;k++)
10. {
11. printf("%d %d %d\n",i,j,k);
12. if(j == 3)
13. {
14. goto out;
15. }
16. }
17. }
18. }
19. out:
20. printf("came out of the loop");
21. }
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
0 3 0
came out of the loop
Type Casting in C
Typecasting allows us to convert one data type into other. In C language, we use cast operator
for typecasting which is denoted by (type).
Syntax:
1. (type)value;
Note: It is always recommended to convert the lower value to higher for avoiding data loss.
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
1. #include<stdio.h>
2. int main(){
3. float f= (float)9/4;
4. printf("f : %f\n", f );
5. return 0;
6. }
Output:
f : 2.250000