C Complete Material
C Complete Material
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.
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.
C is a procedural language. In C, variables and function prototypes must
be declared before being used.
History of C Language
Features of 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.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
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) ‘
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.
1. Download Turbo C++
2. Create turboc directory inside c drive and extract the tc3.zip
inside c:\turboc
3. Double click on install.exe file
4. Click on the tc application file located inside c:\TC\BIN to write
the c program
First C Program
Before starting the abcd of C language, you need to learn how to write,
compile and run the first c program.
To write the first c program, open the C console and write the following
code:
#include <stdio.h>
int main(){
printf("Hello C Language");
return 0;
}
#include <stdio.h>
main(){
printf("Hello C Language");
}
You can view the user screen any time by pressing the alt+f5 keys.
Now press Esc to return to the turbo c++ console.
First.c
First.obj
First.bak
First.exe
First.bak
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:
o Preprocessor
o Compiler
o Assembler
o 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.
Let's understand through an example.
hello.c
#include <stdio.h>
int main()
{
printf("Hello javaTpoint");
return 0;
}
Now, we will create a flow diagram of the above program:
In the above flow diagram, the following steps are taken to
execute a program:
o 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.
o 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.
o This assembly code is then sent to the assembler, which converts
the assembly code into object code.
o After the creation of an object code, the linker creates the
executable file. The loader will then load the executable file for the
execution.
scanf() function
The scanf() function is used for input. It reads the input data from the
console.
1. scanf("format string",argument_list);
Program to print cube of given number
Let's see a simple example of c language that gets input from the user
and prints the cube of the given number.
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
return 0;
}
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.
The printf("cube of number is:%d
",number*number*number) statement prints the cube of number on
the console.
Program to print sum of 2 numbers
Let's see a simple example of input and output in C language that prints
addition of 2 numbers.
#include<stdio.h>
int main(){
int x=0,y=0,result=0;
result=x+y;
printf("sum of 2 numbers:%d ",result);
return 0;
}
Output
enter first number:9
enter second number:9
sum of 2 numbers:18
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.
Let's see the syntax to declare a variable:
1. type variable_list;
The example of declaring the variable is given below:
1. int a;
2. float b;
3. char c;
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=10,b=20;//declaring 2 variable of integer type
2. float f=20.8;
3. char c='A';
Rules for defining variables
o A variable can have alphabets, digits, and underscore.
o A variable name can start with the alphabet, and underscore only. It
can't start with a digit.
o No whitespace is allowed within the variable name.
o A variable name must not be any reserved word or keyword, e.g.
int, float, etc.
Valid variable names:
1. int a;
2. int _ab;
3. int a30;
Invalid variable names:
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.
It must be declared at the start of the block.
1. void function1(){
2. int x=10;//local variable
3. }
You must have to initialize the local variable before it is used.
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.
It must be declared at the start of the block.
int value=20;//global variable
void function1(){
int x=10;//local variable
}
Static Variable
A variable that is declared with the static keyword is called static variable.
It retains its value between multiple function calls.
void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
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.
void main(){
int x=10;//local variable (also automatic)
auto int y=20;//automatic variable
}
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
#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
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:
Keyword Identifier
Additive +- Left to
right
Shift << >> Left to
right
Equality == != Left to
right
Bitwise OR | Left to
right
Logical OR || Left to
right
Conditional ?: Right to
left
Comma , Left to
right
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. Single Line Comments
2. Multi-Line Comments
Single Line Comments
Single line comments are represented by double slash \\. Let's see an
example of a single line comment in C.
1. #include<stdio.h>
2. int main(){
3. //printing information
4. printf("Hello C");
5. return 0;
6. }
Output:
Hello C
Even you can place the comment after the statement. For example:
1. printf("Hello C");//printing information
Mult Line Comments
Multi-Line comments are represented by slash asterisk \* ... *\. It can
occupy many lines of code, but it can't be nested. Syntax:
1. /*
2. code
3. to be commented
4. */
Let's see an example of a multi-Line comment in C.
1. #include<stdio.h>
2. int main(){
3. /*printing information
4. Multi-Line Comment*/
5. printf("Hello C");
6. return 0;
7. }
Output:
Hello C
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.
The commonly used format specifiers in printf() function are:
Format Description
specifier
return 0;
}
In the above code, we are printing the integer value of b and c by using
the %d specifier.
Output
o %u
int main()
{
int b=10;
int c= -10;
printf("Value of b is:%u", b);
printf("\nValue of c is:%u",c);
return 0;
}
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 %o
int main()
{
int a=0100;
printf("Octal value of a is: %o", a);
printf("\nInteger value of a is: %d",a);
return 0;
}
In the above code, we are displaying the octal value and integer value of
a.
Output
o %x and %X
int main()
{
int y=0xA;
printf("Hexadecimal value of y is: %x", y);
printf("\nHexadecimal value of y is: %X",y);
printf("\nInteger value of y is: %d",y);
return 0;
}
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
ADVERTISEMENT
o %f
int main()
{
float y=3.4;
printf("Floating point value of y is: %f", y);
return 0;
}
The above code prints the floating value of y.
Output
o %e
int main()
{
float y=3;
printf("Exponential value of y is: %e", y);
return 0;
}
Output
o %E
int main()
{
float y=3;
printf("Exponential value of y is: %E", y);
return 0;
}
Output
o %g
int main()
{
float y=3.8;
printf("Float value of y is: %g", y);
return 0;
}
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.
Output
o %p
int main()
{
int y=5;
printf("Address value of y in hexadecimal form is: %p", &y);
return 0;
}
Output
o %c
int main()
{
char a='c';
printf("Value of a is: %c", a);
return 0;
}
Output
o %s
int main()
{
printf("%s", "India");
return 0;
}
Now we will see how to fill the empty spaces. It is shown in the
below code:
int main()
{
int x=12;
printf("%08d", x);
return 0;
}
In the above program, %08d means that the empty space is filled with
zeroes.
Output
Specifying Precision
We can specify the precision by using '.' (Dot) operator which is followed
by integer and format specifier.
int main()
{
float x=12.2;
printf("%.2f", x);
return 0;
}
Output
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.
List of Escape Sequences in C
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\? Question Mark
\0 Null
ASCII value in C
What is ASCII code?
The full form of ASCII is the American Standard Code for information
interchange. It is a character encoding scheme used for electronics
communication. Each character or a special character is represented by
some ASCII code, and each ascii code occupies 7 bits in memory.
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'.
Let's understand through an example.
We will create a program which will display the ascii value of the
character variable.
#include <stdio.h>
int main()
{
char ch; // variable declaration
printf("Enter a character");
scanf("%c",&ch); // user input
printf("\n The ascii value of the ch variable is : %d", ch);
return 0;
}
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.
#include <stdio.h>
int main()
{
int k; // variable declaration
for(int k=0;k<=255;k++) // for loop from 0-255
{
printf("\nThe ascii value of %c is %d", k,k);
}
return 0;
}
The above program will display the ascii value of all the characters. As we
know that ascii value of all the characters starts from 0 and ends at 255,
so we iterate the for loop from 0 to 255.
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.
There are different types of constants in C programming.
List of Constants in C
Constant Example
Types of literals
There are four types of literals that exist in C programming:
o Integer literal
o Float literal
o Character literal
o 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 can be specified in the following three ways:
Decimal number (base 10)
It is defined by representing the digits between 0 to 9. For example, 45,
67, etc.
Octal number (base 8)
It is defined as a number in which 0 is followed by digits such as
0,1,2,3,4,5,6,7. For example, 012, 034, 055, etc.
Hexadecimal number (base 16)
Warning generated:
1. main.c:6:18: warning: multi-character character constant
2. [-Wmultichar]
3. const char c='ak';
4. main.c:6:18: warning: implicit conversion from 'int' to 'char'
5. changes value from 24939 to 107 [-Wconstant-conversion]
6. const char c='ak';
7. ~ ^~~~
8. 2 warnings generated.
9. ? ./main
Representation of character literal
A character literal can be represented in the following ways:
o It can be represented by specifying a single character within single
quotes. For example, 'a', 'b', etc.
o We can specify the escape sequence character within single quotes
to represent a character literal. For example, '\n', '\a', '\b'.
o We can also use the ASCII in integer to represent a character
literal. For example, the ascii value of 65 is 'A'.
o The octal and hexadecimal notation can be used as an escape
sequence to represent a character literal. For example, '\023', '\
0x12'.
String literal
A string literal represents multiple characters enclosed within double-
quotes. It contains an additional character, i.e., '\0' (null character),
which gets automatically inserted. This null character specifies the
termination of the string. We can use the '+' symbol to concatenate two
strings.
For example,
String1= "Indian";
String2= "family";
To concatenate the above two strings, we use '+' operator, as shown in
the below statement:
"Indian " + "family"= Indian family
Note: If we represent a single character, i.e., 'b', then this character will occupy
a single byte as it is a character literal. And, if we represent the character
within double quotes "b" then it will occupy more bytes as it is a string literal.
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
Tokens in C language can be divided into the following categories:
o Keywords in C
o Identifiers in C
o Strings in C
o Operators in C
o Constant in C
o Special Characters in C
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;
In the above syntax, bool is the data type of the variable,
and variable_name is the name of the variable.
Let's understand through an example.
#include <stdio.h>
#include<stdbool.h>
int main()
{
bool x=false; // variable initialization.
if(x==true) // conditional statements
{
printf("The value of x is true");
}
else
printf("The value of x is FALSE");
return 0;
}
In the above code, we have used <stdbool.h> header file so that we can
use the bool type variable in our program. After the declaration of the
header file, we create the bool type variable 'x' and assigns a 'false'
value to it. Then, we add the conditional statements, i.e., if..else, to
determine whether the value of 'x' is true or not.
Output
The value of x is FALSE
Boolean Array
Now, we create a bool type array. The Boolean array can contain either
true or false value, and the values of the array can be accessed with the
help of indexing.
Let's understand this scenario through an example.
#include <stdio.h>
#include<stdbool.h>
int main()
{
bool b[2]={true,false}; // Boolean type array
for(int i=0;i<2;i++) // for loop
{
printf("%d,",b[i]); // printf statement
}
return 0;
}
In the above code, we have declared a Boolean type array containing two
values, i.e., true and false.
Output
1,0,
typedef
There is another way of using Boolean value, i.e., typedef. Basically,
typedef is a keyword in C language, which is used to assign the name to
the already existing datatype.
Let's see a simple example of typedef.
#include <stdio.h>
typedef enum{false,true} b;
int main()
{
b x=false; // variable initialization
if(x==true) // conditional statements
{
printf("The value of x is true");
}
else
{
printf("The value of x is false");
}
return 0;
}
In the above code, we use the Boolean values, i.e., true and false, but we
have not used the bool type. We use the Boolean values by creating a
new name of the 'bool' type. In order to achieve this, the
typedef keyword is used in the program.
1. typedef enum{false,true} b;
The above statement creates a new name for the 'bool' type, i.e., 'b' as
'b' can contain either true or false value. We use the 'b' type in our
program and create the 'x' variable of type 'b'.
Output
The value of x is false
Boolean with Logical Operators
The Boolean type value is associated with logical operators. There are
three types of logical operators in the C language:
&&(AND Operator): It is a logical operator that takes two operands. If
the value of both the operands are true, then this operator returns true
otherwise false
||(OR Operator): It is a logical operator that takes two operands. If the
value of both the operands is false, then it returns false otherwise true.
!(NOT Operator): It is a NOT operator that takes one operand. If the
value of the operand is false, then it returns true, and if the value of the
operand is true, then it returns false.
Let's understand through an example.
#include <stdio.h>
#include<stdbool.h>
int main()
{
bool x=false;
bool y=true;
printf("The value of x&&y is %d", x&&y);
printf("\nThe value of x||y is %d", x||y);
printf("\nThe value of !x is %d", !x);
}
Output
The value of x&&y is 0
The value of x||y is 1
The value of !x is 1
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.
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.
Output
1
1
Static variable
A static variable is a variable that persists its value across the various
function calls.
Syntax
The syntax of a static variable is given below:
1. static data_type variable_name;
Let's look at a simple example of static variable.
#include <stdio.h>
int main()
{
printf("%d",func());
printf("\n%d",func());
return 0;
}
int func()
{
static int count=0;
count++;
return count;
}
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.
The static function would look like as:
static void func()
{
printf("Hello javaTpoint");
}
Differences b/w static and global variable
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.
Differences b/w static local and static global variable
Static global 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.
Static local variable
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.
Properties of a static variable
The following are the properties of a static variable:
o The memory of a static variable is allocated within a static variable.
o Its memory is available throughout the program, but the scope will
remain the same as the automatic local variables. Its
o value will persist across the various function calls.
o If we do not assign any value to the variable, then the default value
will be 0.
o A global static variable cannot be accessed outside the program,
while a global variable can be accessed by other source files.
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.
There are mainly five types of errors exist in C programming:
o Syntax error
o Run-time error
o Linker error
o Logical error
o 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. If we want to declare the variable of type integer,
2. int a; // this is the correct form
3. Int a; // this is an incorrect form.
Commonly occurred syntax errors are:
o If we miss the parenthesis (}) while writing the code.
o Displaying the value of a variable without its declaration.
o If we miss the semicolon (;) at the end of the statement.
Let's understand through an example.
#include <stdio.h>
int main()
{
a = 10;
printf("The value of a is : %d", a);
return 0;
}
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.
#include <stdio.h>
int main()
{
int a=2;
if(.) // syntax error
printf("a is greater than 1");
return 0;
}
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.
#include <stdio.h>
int main()
{
int a=2;
int b=2/0;
printf("The value of b is : %d", b);
return 0;
}
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().
Let's understand through a simple example.
#include <stdio.h>
int Main()
{
int a=78;
printf("The value of a is : %d", a);
return 0;
}
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.
Let's understand through an example.
#include <stdio.h>
int main()
{
int sum=0; // variable initialization
int k=1;
for(int i=1;i<=10;i++); // logical error, as we put the semicolon after loo
p
{
sum=sum+k;
k++;
}
printf("The value of sum is %d", sum);
return 0;
}
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.
The following can be the cases for the semantic error:
o Use of a un-initialized variable.
int i;
i=i+2;
o Type compatibility
int b = "india";
o Errors in expressions
int a, b, c;
a+b = c;
o Array index out of bound
int a[10];
a[10] = 34;
Let's understand through an example.
#include <stdio.h>
int main()
{
int a,b,c;
a=2;
b=3;
c=1;
a+b=c; // semantic error
return 0;
}
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 Runtime
The compile-time errors are The runtime errors are the errors
the errors which are produced which are not generated by the
at the compile-time, and they compiler and produce an
are detected by the compiler. unpredictable result at the
execution time.
In this case, the compiler In this case, the compiler does not
prevents the code from detect the error, so it cannot
execution if it detects an error prevent the code from the
in the program. execution.
It contains the syntax and It contains the errors such as
semantic errors such as division by zero, determining the
missing semicolon at the end square root of a negative number.
of the statement.
#include <stdio.h>
int main()
{
int a=20;
printf("The value of a is : %d",a):
return 0;
}
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.
Output
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.
Syntax of a conditional operator
1. Expression1? expression2: expression3;
The pictorial representation of the above syntax is shown below:
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.
Let's understand this scenario through an example.
#include <stdio.h>
int main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}
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.
o A conditional operator is a single programming statement, while the
'if-else' statement is a programming block in which statements
come under the parenthesis.
o A conditional operator can also be used for assigning a value to the
variable, whereas the 'if-else' statement cannot be used for the
assignment purpose.
o It is not useful for executing the statements when the statements
are multiple, whereas the 'if-else' statement proves more suitable
when executing multiple statements.
o The nested ternary operator is more complex and cannot be easily
debugged, while the nested 'if-else' statement is easy to read and
maintain.
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 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 1
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,
1. We consider two variables,
2. a = 23;
3. b = 10;
4. The binary representation of the above two variables would be:
5. a = 0001 0111
6. b = 0000 1010
7. When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the output
would be:
8. Result = 0001 1111
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.
Let's understand the bitwise OR operator through a program.
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
In the above figure, the binary number is equal to 00010100, and its one's
complement is calculated by transforming the bit 1 to 0 and 0 to 1 vice versa.
Therefore, one's complement becomes 11101011. After calculating one's
complement, we calculate the two's complement by adding 1 to the one's
complement, and its result is 11101100.
Let's create a program of 2s complement.
1. #include <stdio.h>
2. int main()
3. {
4. int n; // variable declaration
5. printf("Enter the number of bits do you want to enter :");
6. scanf("%d",&n);
7. char binary[n+1]; // binary array declaration;
8. char onescomplement[n+1]; // onescomplement array declaration
9. char twoscomplement[n+1]; // twoscomplement array declaration
10. int carry=1; // variable initialization
11. printf("\nEnter the binary number : ");
12. scanf("%s", binary);
13. printf("%s", binary);
14. printf("\nThe ones complement of the binary number is :");
15. // Finding onescomplement in C
16. for(int i=0;i<n;i++)
17. {
18. if(binary[i]=='0')
19. onescomplement[i]='1';
20. else if(binary[i]=='1')
21. onescomplement[i]='0';
22. }
23. onescomplement[n]='\0';
24. printf("%s",onescomplement);
25.
26.
27. printf("\nThe twos complement of a binary number is : ");
28.
29. // Finding twoscomplement in C
30. for(int i=n-1; i>=0; i--)
31. {
32. if(onescomplement[i] == '1' && carry == 1)
33. {
34. twoscomplement[i] = '0';
35. }
36. else if(onescomplement[i] == '0' && carry == 1)
37. {
38. twoscomplement[i] = '1';
39. carry = 0;
40. }
41. else { twoscomplement[i] = onescomplement[i]; }
42. }
43. twoscomplement[n]='\0';
44. printf("%s",twoscomplement);
45. return 0;
46. }
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.
There are the following variants of if statement in C language.
o If statement
o If-else statement
o If else-if ladder
o 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) { printf("%d is largest",a); }
8. if(b>a && b > c)
9. {
10. printf("%d is largest",b);
11. }
12. if(c>a && c>b)
13. {
14. printf("%d is largest",c);
15. }
16. if(a == b && a == c) { printf("All are equal"); }
17. }
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.
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
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.
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
Program to check whether a person is eligible to vote or not.
1. #include <stdio.h>
2. int main()
3. {
4. int age;
5. printf("Enter your age?");
6. scanf("%d",&age);
7. if(age>=18) { printf("You are eligible to vote..."); }
8. else { printf("Sorry ... you can't vote"); }
9. }
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.
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. }
Flowchart of else-if ladder statement in C
The example of an if-else-if statement in C language is given below.
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.}
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. }
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:
1. if(expression)
2. {
3. // statements;
4. }
5. else
6. {
7. // statements;
8. }
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:
Java Try Catch
1. switch(expression)
2. {
3. case constant 1:
4. // statements;
5. break;
6. case constant 2:
7. // statements;
8. break;
9. case constant n:
10. // statements;
11. break;
12. default:
13. // statements;
14. }
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:
o 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.
o 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.
o 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.
o 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.
o 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.
o 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.
o 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.
o 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.
o 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
Sequence First, the condition is It executes one case after another till
of checked. If the condition is the break keyword is not found, or the
execution true then 'if' block is default statement is executed.
executed otherwise 'else'
block
Default If the condition is not true, If the value does not match with any
execution then by default, else block case, then by default, default
will be executed. statement is executed.
Editing Editing is not easy in the 'if- Cases in a switch statement are easy to
else' statement. 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 If we have multiple choices then the
implemented through 'if- switch statement is the best option as
else', then the speed of the the speed of the execution will be
execution will be slow. much higher than 'if-else'.
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.
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.
Prime Ministers of India | List of Prime Minister of India (1947-2020)
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).
The syntax of do-while loop in c language is given below:
1. do{
2. //code to be executed
3. }while(condition);
Flowchart and Example of do-while loop
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:
1. while(condition){
2. //code to be executed
3. }
Flowchart and Example of while loop
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.
do while loop syntax
The syntax of the C language do-while loop is given below:
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
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.
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
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.
Syntax of while loop in C language
The syntax of while loop in c language is given below:
1. while(condition){
2. //code to be executed
3. }
Flowchart of while loop in C
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.
Syntax of for loop in C
The syntax of for loop in c language is given below:
1. for(Expression 1; Expression 2; Expression 3){
2. //code to be executed
3. }
Flowchart of for loop in C
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
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.
Hello Java Program for Beginners
Nested for loop
The nested for loop means any type of loop which is defined inside the 'for' loop.
1. for (initialization; condition; update)
2. {
3. for(initialization; condition; update)
4. {
5. // inner loop statements.
6. }
7. // outer loop statements.
8. }
Example of nested 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. }
Explanation of the above code
o First, the 'i' variable is initialized to 1 and then program control passes to the
i<=n.
o The program control checks whether the condition 'i<=n' is true or not.
o If the condition is true, then the program control passes to the inner loop.
o The inner loop will get executed until the condition is true.
o After the execution of the inner loop, the control moves back to the update of
the outer loop, i.e., i++.
o After incrementing the value of the loop counter, the condition is checked
again, i.e., i<=n.
o If the condition is true, then the inner loop will be executed again.
o This process will continue until the condition of the outer loop is true.
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.
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:
o 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.
o 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.
o 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:
o for loop
o while loop
o do-while loop
o go to statement
o C macros
For loop
Let's see the infinite 'for' loop. The following is the definition for the infinite for
loop:
Difference between JDK, JRE, and JVM
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.
Let's understand through an example.
1. #include <stdio.h>
2. int main()
3. {
4. for(;;)
5. {
6. printf("Hello india");
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.
Let's look at a simple example.
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.
Let's understand through an example.
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.
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:
o 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.
o 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.
o 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.
o 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.
o 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:
1. With switch case
2. With loop
Syntax:
1. //loop or switch case
2. break;
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
0 1 2 3 4 5 came outside of loop i = 5
Example of C break statement with switch case
Click here to see the example of C break with the switch statement.
C break statement with the nested loop
In such case, it breaks only the inner loop, but not outer loop.
HTML Tutorial
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.
break statement with while loop
Consider the following example to use break statement inside while loop.
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(1)
6. {
7. printf("%d ",i);
8. i++;
9. if(i == 10)
10. break;
11. }
12. printf("came out of while loop");
13. }
Output
0 1 2 3 4 5 6 7 8 9 came out of while loop
break statement with do-while loop
Consider the following example to use the break statement with a do-while loop.
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 t
o continue.",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
Continue statement example 1
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 0;
5. while(i!=10)
6. {
7. printf("%d", i);
8. continue;
9. i++;
10. }
11. }
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.
C continue statement with inner loop
In such case, C continue statement continues only inner loop, but not outer loop.
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:
Enter the number whose table you want to print?10
10 x 1 = 10
10 x 2 = 20
10 x 3 = 30
10 x 4 = 40
10 x 5 = 50
10 x 6 = 60
10 x 7 = 70
10 x 8 = 80
10 x 9 = 90
10 x 10 = 100
When should we use goto?
The only condition in which using goto is preferable is when we need to break the
multiple loops using a single statement at the same time. Consider the following
example.
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.
Without Type Casting:
1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2
With Type Casting:
1. float f=(float) 9/4;
2. printf("f : %f\n", f );//Output: 2.250000
Type Casting example
Let's see a simple example to cast int value into the float.
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
C Functions
In c, we can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}. A function
can be called multiple times to provide reusability and modularity to the C program.
In other words, we can say that the collection of functions creates a program. The
function is also known as procedure or sub routine in other programming languages.
Advantage of functions in C
There are the following advantages of C functions.
o By using functions, we can avoid rewriting same logic/code again and again in
a program.
o We can call C functions any number of times in a program and from any place
in a program.
o We can track a large C program easily when it is divided into multiple
functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.
Function Aspects
There are three aspects of a C function.
o Function declaration A function must be declared globally in a c program to
tell the compiler about the function name, function parameters, and return
type.
o Function call Function can be called from anywhere in the program. The
parameter list must not differ in function calling and function declaration. We
must pass the same number of functions as it is declared in the function
declaration.
The sum is 34
Example for Function without argument and with return value
Example 1
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. int result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. result = sum();
8. printf("%d",result);
9. }
10. int sum()
11. {
12. int a,b;
13. printf("\nEnter two numbers");
14. scanf("%d %d",&a,&b);
15. return a+b;
16. }
Output
Going to calculate the sum of two numbers:
The sum is 34
Example 2: program to calculate the area of the square
1. #include<stdio.h>
2. int sum();
3. void main()
4. {
5. printf("Going to calculate the area of the square\n");
6. float area = square();
7. printf("The area of the square: %f\n",area);
8. }
9. int square()
10. {
11. float side;
12. printf("Enter the length of the side in meters: ");
13. scanf("%f",&side);
14. return side * side;
15. }
Output
Going to calculate the area of the square
Enter the length of the side in meters: 10
The area of the square: 100.000000
Example for Function with argument and without return value
Example 1
1. #include<stdio.h>
2. void sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. sum(a,b);
10. }
11. void sum(int a, int b)
12. {
13. printf("\nThe sum is %d",a+b);
14. }
Output
Going to calculate the sum of two numbers:
The sum is 34
Example 2: program to calculate the average of five numbers.
1. #include<stdio.h>
2. void average(int, int, int, int, int);
3. void main()
4. {
5. int a,b,c,d,e;
6. printf("\nGoing to calculate the average of five numbers:");
7. printf("\nEnter five numbers:");
8. scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
9. average(a,b,c,d,e);
10. }
11. void average(int a, int b, int c, int d, int e)
12. {
13. float avg;
14. avg = (a+b+c+d+e)/5;
15. printf("The average of given five numbers : %f",avg);
16. }
Output
Going to calculate the average of five numbers:
Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000
Example for Function with argument and with return value
Example 1
1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }
Output
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30
Example 2: Program to check whether a number is even or odd
1. #include<stdio.h>
2. int even_odd(int);
3. void main()
4. {
5. int n,flag=0;
6. printf("\nGoing to check whether a number is even or odd");
7. printf("\nEnter the number: ");
8. scanf("%d",&n);
9. flag = even_odd(n);
10. if(flag == 0)
11. {
12. printf("\nThe number is odd");
13. }
14. else
15. {
16. printf("\nThe number is even");
17. }
18. }
19. int even_odd(int n)
20. {
21. if(n%2 == 0)
22. {
23. return 1;
24. }
25. else
26. {
27. return 0;
28. }
29. }
Output
Going to check whether a number is even or odd
Enter the number: 100
The number is even
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a
common place called the library. Such functions are used to perform some specific
operations. For example, printf is a library function used to print on the console. The
library functions are created by the designers of compilers. All C standard library
functions are defined inside the different header files saved with the extension .h. We
need to include these header files in our program to make use of the library
functions defined in such header files. For example, To use the library functions such
as printf/scanf we need to include stdio.h in our program which is a header file that
contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.
SN Header Description
file
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like
malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions
like sqrt(), pow(), etc.
9 signal.h All the signal handling functions are defined in this header file.
Let's understand call by value and call by reference in c language one by one.
Call by value in C
o In call by value method, the value of the actual parameters is copied into the
formal parameters. In other words, we can say that the value of the variable is
used in the function call in the call by value method.
o In call by value method, we can not modify the value of the actual parameter
by the formal parameter.
o In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the formal
parameter.
o The actual parameter is the argument which is used in the function call
whereas formal parameter is the argument which is used in the function
definition.
Let's try to understand the concept of call by value in c language by the example
given below:
1. #include<stdio.h>
2. void change(int num) {
3. printf("Before adding value inside function num=%d \n",num);
4. num=num+100;
5. printf("After adding value inside function num=%d \n", num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(x);//passing value in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
1. #include<stdio.h>
2. void change(int *num) {
3. printf("Before adding value inside function num=%d \n",*num);
4. (*num) += 100;
5. printf("After adding value inside function num=%d \n", *num);
6. }
7. int main() {
8. int x=100;
9. printf("Before function call x=%d \n", x);
10. change(&x);//passing reference in function
11. printf("After function call x=%d \n", x);
12. return 0;
13. }
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Call by reference Example: Swapping the values of the two
variables
1. #include <stdio.h>
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the
value of a and b in main
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actu
al parameters do change in call by reference, a = 10, b = 20
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal para
meters, a = 20, b = 10
18. }
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
2 Changes made inside the function is Changes made inside the function
limited to the function only. The validate outside of the function also.
values of the actual parameters do The values of the actual parameters
not change by changing the formal do change by changing the formal
parameters. parameters.
3 Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory
location location
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of
itself to work on a smaller problem. Any function which calls itself is called recursive
function, and such function calls are called recursive calls. Recursion involves several
numbers of recursive calls. However, it is important to impose a termination
condition of recursion. Recursion code is shorter than iterative code however it is
difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks
that can be defined in terms of similar subtasks. For Example, recursion may be
applied to sorting, searching, and traversal problems.
Generally, iterative solutions are more efficient than recursion since function call is
always overhead. Any problem that can be solved recursively, can also be solved
iteratively. However, some problems are best suited to be solved by the recursion, for
example, tower of Hanoi, Fibonacci series, factorial finding, etc.
In the following example, recursion is used to calculate the factorial of a number.
Hello Java Program for Beginners
1. #include <stdio.h>
2. int fact (int);
3. int main()
4. {
5. int n,f;
6. printf("Enter the number whose factorial you want to calculate?");
7. scanf("%d",&n);
8. f = fact(n);
9. printf("factorial = %d",f);
10. }
11. int fact(int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if ( n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return n*fact(n-1);
24. }
25. }
Output
Enter the number whose factorial you want to calculate?5
factorial = 120
We can understand the above program of the recursive method call by the figure
given below:
Recursive Function
A recursive function performs the tasks by dividing it into the subtasks. There is a
termination condition defined in the function which is satisfied by some specific
subtask. After this, the recursion stops and the final result is returned from the
function.
The case at which the function doesn't recur is called the base case whereas the
instances where the function keeps calling itself to perform a subtask, is called the
recursive case. All the recursive functions can be written using this format.
Pseudocode for writing any recursive function is given below.
1. if (test_for_base)
2. {
3. return some_value;
4. }
5. else if (test_for_another_base)
6. {
7. return some_another_value;
8. }
9. else
10. {
11. // Statements;
12. recursive call;
13. }
Example of recursion in C
Let's see an example to find the nth term of the Fibonacci series.
1. #include<stdio.h>
2. int fibonacci(int);
3. void main ()
4. {
5. int n,f;
6. printf("Enter the value of n?");
7. scanf("%d",&n);
8. f = fibonacci(n);
9. printf("%d",f);
10. }
11. int fibonacci (int n)
12. {
13. if (n==0)
14. {
15. return 0;
16. }
17. else if (n == 1)
18. {
19. return 1;
20. }
21. else
22. {
23. return fibonacci(n-1)+fibonacci(n-2);
24. }
25. }
Output
Enter the value of n?12
144
Memory allocation of Recursive method
Each recursive call creates a new copy of that method in the memory. Once some
data is returned by the method, the copy is removed from the memory. Since all the
variables and other stuff declared inside function get stored in the stack, therefore a
separate stack is maintained at each recursive call. Once the value is returned from
the corresponding function, the stack gets destroyed. Recursion involves so much
complexity in resolving and tracking the values at each recursive call. Therefore we
need to maintain the stack and track the values of the variables defined in the stack.
Let us consider the following example to understand the memory allocation of the
recursive functions.
1. int display (int n)
2. {
3. if(n == 0)
4. return 0; // terminating condition
5. else
6. {
7. printf("%d",n);
8. return display(n-1); // recursive call
9. }
10. }
Explanation
Let us examine this recursive function for n = 4. First, all the stacks are maintained
which prints the corresponding value of n until n becomes 0, Once the termination
condition is reached, the stacks get destroyed one by one by returning 0 to its calling
stack. Consider the following image for more information regarding the stack trace
for the recursive functions.
Storage Classes in C
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
o Automatic
o External
o Static
o Register
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
Automatic
o Automatic variables are allocated memory automatically at runtime.
o 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.
o The automatic variables are initialized to garbage by default.
o The memory assigned to automatic variables gets freed upon exiting from the
block.
o The keyword used for defining automatic variables is auto.
o Every local variable is automatic in C by default.
Example 1
1. #include <stdio.h>
2. int main()
3. {
4. int a; //auto
5. char b;
6. float c;
7. printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, an
d c.
8. return 0;
9. }
Output:
garbage garbage garbage
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. int a = 10,i;
5. printf("%d ",++a);
6. {
7. int a = 20;
8. for (i=0;i<3;i++)
9. {
10. printf("%d ",a); // 20 will be printed 3 times since it is the local value of a
11. }
12. }
13. printf("%d ",a); // 11 will be printed since the scope of a = 20 is ended.
14. }
Output:
11 20 20 20 11
Static
o The variables defined as static specifier can hold their value between the
multiple function calls.
o Static local variables are visible only to the function or the block in which they
are defined.
o A same static variable can be declared many times but can be assigned at only
one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.
Example 1
1. #include<stdio.h>
2. static char c;
3. static int i;
4. static float f;
5. static char s[100];
6. void main ()
7. {
8. printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
9. }
Output:
History of Java
0 0 0.000000 (null)
Example 2
1. #include<stdio.h>
2. void sum()
3. {
4. static int a = 10;
5. static int b = 24;
6. printf("%d %d \n",a,b);
7. a++;
8. b++;
9. }
10. void main()
11. {
12. int i;
13. for(i = 0; i< 3; i++)
14. {
15. sum(); // The static variables holds their value between multiple function calls.
16. }
17. }
Output:
10 24
11 25
12 26
Register
o 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.
o We can not dereference the register variables, i.e., we can not use &operator
for the register variable.
o The access time of the register variables is faster than the automatic variables.
o The initial default value of the register local variables is 0.
o 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.
o We can store pointers into the register, i.e., a register can store the address of
a variable.
o 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
1. #include <stdio.h>
2. int main()
3. {
4. register int a; // variable a is allocated memory in the CPU register. The initial default
value of a is 0.
5. printf("%d",a);
6. }
Output:
0
Example 2
1. #include <stdio.h>
2. int main()
3. {
4. register int a = 0;
5. printf("%u",&a); // This will give a compile time error since we can not access the add
ress of a register variable.
6. }
Output:
main.c:5:5: error: address of register variable ?a? requested
printf("%u",&a);
^~~~~~
External
o 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.
o 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.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize the
external variable within any block or method.
o An external variable can be declared many times but can be initialized at only
once.
o 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
1. #include <stdio.h>
2. int main()
3. {
4. extern int a;
5. printf("%d",a);
6. }
Output
main.c:(.text+0x6): undefined reference to `a'
collect2: error: ld returned 1 exit status
Example 2
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a; // variable a is defined globally, the memory will not be allocated to a
6. printf("%d",a);
7. }
Output
0
Example 3
1. #include <stdio.h>
2. int a;
3. int main()
4. {
5. extern int a = 0; // this will show a compiler error since we can not use extern and ini
tializer at same time
6. printf("%d",a);
7. }
Output
compile time error
main.c: In function ?main?:
main.c:5:16: error: ?a? has both ?extern? and initializer
extern int a = 0;
Example 4
1. #include <stdio.h>
2. int main()
3. {
4. extern int a; // Compiler will search here for a variable a defined and initialized some
where in the pogram or not.
5. printf("%d",a);
6. }
7. int a = 20;
Output
20
Example 5
1. extern int a;
2. int a = 10;
3. #include <stdio.h>
4. int main()
5. {
6. printf("%d",a);
7. }
8. int a = 20; // compiler will show an error at this line
Output
compile time error
C Array
An array is defined as the collection of similar type of data items stored at
contiguous memory locations. Arrays are the derived data type in C programming
language which can store the primitive type of data such as int, char, double, float,
etc. It also has the capability to store the collection of derived data types, such as
pointers, structure, etc. The array is the simplest data structure where each data
element can be randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different
variables for the marks in the different subject. Instead of that, we can define an array
which can store the marks in each subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are
required to access the elements of the array.
Properties of Array
The array contains the following properties.
Features of Java - Javatpoint
o Each element of an array is of same data type and carries the same size, i.e.,
int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the
first element is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size
of the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array
easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we
can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which
we will learn later.
Declaration of C Array
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];
Now, let us see the example to declare the array.
1. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index. Consider the following
example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
80
60
70
85
75
C Array: Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as
the following code.
1. int marks[]={20,30,40,50,60};
Let's see the C program to declare and initialize the array in C.
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60
C Array Example: Sorting an array
In the following program, we are using bubble sort method to sort the array in
ascending order.
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
Program to print the largest and second largest element of the
array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78
56 10 30
34 21 34
45 56 78
Return an Array in C
What is an Array?
An array is a type of data structure that stores a fixed-size of a homogeneous
collection of data. In short, we can say that array is a collection of variables of the
same type.
For example, if we want to declare 'n' number of variables, n1, n2...n., if we create all
these variables individually, then it becomes a very tedious task. In such a case, we
create an array of variables having the same type. Each element of an array can be
accessed using an index of the element.
Let's first see how to pass a single-dimensional array to a function.
Passing array to a function
Is coding hard to learn? It is NOT your fault!
1. #include <stdio.h>
2. void getarray(int arr[])
3. {
4. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ", arr[i]);
8. }
9. }
10. int main()
11. {
12. int arr[5]={45,67,34,78,90};
13. getarray(arr);
14. return 0;
15. }
In the above program, we have first created the array arr[] and then we pass this
array to the function getarray(). The getarray() function prints all the elements of the
array arr[].
Output
Note: From the above examples, we observe that array is passed to a function
as a reference which means that array also persist outside the function.
How to return an array from a function
Returning pointer pointing to the array
1. #include <stdio.h>
2. int *getarray()
3. {
4. int arr[5];
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &arr[i]);
9. }
10. return arr;
11. }
12. int main()
13. {
14. int *n;
15. n=getarray();
16. printf("\nElements of array are :");
17. for(int i=0;i<5;i++)
18. {
19. printf("%d", n[i]);
20. }
21. return 0;
22. }
In the above program, getarray() function returns a variable 'arr'. It returns a local
variable, but it is an illegal memory location to be returned, which is allocated within
a function in the stack. Since the program control comes back to the main() function,
and all the variables in a stack are freed. Therefore, we can say that this program is
returning memory location, which is already de-allocated, so the output of the
program is a segmentation fault.
Output
Using Structure
The structure is a user-defined data type that can contain a collection of items of
different types. Now, we will create a program that returns an array by using
structure.
1. #include <stdio.h>
2. #include<malloc.h>
3. struct array
4. {
5. int arr[8];
6. };
7. struct array getarray()
8. {
9. struct array y;
10. printf("Enter the elements in an array : ");
11. for(int i=0;i<8;i++)
12. {
13. scanf("%d",&y.arr[i]);
14. }
15. return y;
16. }
17. int main()
18. {
19. struct array x=getarray();
20. printf("Elements that you have entered are :");
21. for(int i=0;x.arr[i]!='\0';i++)
22. {
23. printf("%d ", x.arr[i]);
24. }
25. return 0;
26. }
Output
C Pointers
The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function, or any other pointer. The size of
the pointer depends on the architecture. However, in 32-bit architecture the size of a
pointer is 2 byte.
Consider the following example to define a pointer which stores the address of an
integer.
1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n
of type integer.
Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known
as indirection pointer used to dereference a pointer.
1. int *a;//pointer to int
2. char *c;//pointer to char
Pointer Example
An example of using pointers to print the address and value is given below.
Features of Java - Javatpoint
As you can see in the above figure, pointer variable stores the address of number
variable, i.e., fff4. The value of number variable is 50. But the address of pointer
variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Let's see the pointer example as explained for the above figure.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %x \n",p); // p contains the address of the number the
refore printing p gives the address of number.
7. printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a
pointer therefore if we print *p, we will get the value stored at the address contained
by p.
8. return 0;
9. }
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Pointer to array
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer
array arr.
Pointer to a function
1. void show (int);
2. void(*p)(int) = &display; // Pointer p is pointing to the address of a function
Pointer to structure
1. struct st {
2. int i;
3. float f;
4. }ref;
5. struct st *p = &ref;
Advantage of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving
strings, trees, etc. and used with arrays, structures, and functions.
2) We can return multiple values from a function using the pointer.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
There are many applications of pointers in c language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc()
functions where the pointer is used.
2) Arrays, Functions, and Structures
Pointers in c language are widely used in arrays, functions, and structures. It reduces
the code and improves the performance.
Address Of (&) Operator
The address of operator '&' returns the address of a variable. But, we need to use %u
to display the address of a variable.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("value of number is %d, address of number is %u",number,&number);
5. return 0;
6. }
Output
value of number is 50, address of number is fff4
NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL pointer. If
you don't have any address to be specified in the pointer at the time of declaration,
you can assign NULL value. It will provide a better approach.
int *p=NULL;
In the most libraries, the value of the pointer is 0 (zero).
Pointer Program to swap two numbers without using the 3rd
variable.
1. #include<stdio.h>
2. int main(){
3. int a=10,b=20,*p1=&a,*p2=&b;
4.
5. printf("Before swap: *p1=%d *p2=%d",*p1,*p2);
6. *p1=*p1+*p2;
7. *p2=*p1-*p2;
8. *p1=*p1-*p2;
9. printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);
10.
11. return 0;
12. }
Output
Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10
Reading complex pointers
There are several things which must be taken into the consideration while reading
the complex pointers in C. Lets see the precedence and associativity of the operators
which are used regarding pointers.
Data type 3 -
As you can see in the above figure, p2 contains the address of p (fff2), and p contains
the address of number variable (fff4).
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. int **p2;//pointer to pointer
6. p=&number;//stores the address of number variable
7. p2=&p;
8. printf("Address of number variable is %x \n",&number);
9. printf("Address of p variable is %x \n",p);
10. printf("Value of *p variable is %d \n",*p);
11. printf("Address of p2 variable is %x \n",p2);
12. printf("Value of **p2 variable is %d \n",*p);
13. return 0;
14. }
Output
Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50
In the above question, the pointer arithmetic is used with the double pointer. An
array of 6 elements is defined which is pointed by an array of pointer p. The pointer
array p is pointed by a double pointer pp. However, the above image gives you a
brief idea about how the memory is being allocated to the array a and the pointer
array p. The elements of p are the pointers that are pointing to every element of the
array a. Since we know that the array name contains the base address of the array
hence, it will work as a pointer and can the value can be traversed by using *(a),
*(a+1), etc. As shown in the image, a[0] can be accessed in the following ways.
o a[0]: it is the simplest way to access the first element of the array
o *(a): since a store the address of the first element of the array, we can access
its value by using indirection pointer on it.
o *p[0]: if a[0] is to be accessed by using a pointer p to it, then we can use
indirection operator (*) on the first element of the pointer array p, i.e., *p[0].
o **(pp): as pp stores the base address of the pointer array, *pp will give the
value of the first element of the pointer array that is the address of the first
element of the integer array. **p will give the actual value of the first element
of the integer array.
Coming to the program, Line 1 and 2 declare the integer and pointer array relatively.
Line 3 initializes the double pointer to the pointer array p. As shown in the image, if
the address of the array starts from 200 and the size of the integer is 2, then the
pointer array will contain the values as 200, 202, 204, 206, 208, 210. Let us consider
that the base address of the pointer array is 300; the double pointer pp contains the
address of pointer array, i.e., 300. Line number 4 increases the value of pp by 1, i.e.,
pp will now point to address 302.
Line number 5 contains an expression which prints three values, i.e., pp - p, *pp - a,
**pp. Let's calculate them each one of them.
o pp = 302, p = 300 => pp-p = (302-300)/2 => pp-p = 1, i.e., 1 will be printed.
o pp = 302, *pp = 202, a = 200 => *pp - a = 202 - 200 = 2/2 = 1, i.e., 1 will be
printed.
o pp = 302, *pp = 202, *(*pp) = 206, i.e., 206 will be printed.
Therefore as the result of line 5, The output 1, 1, 206 will be printed on the console.
On line 6, *pp++ is written. Here, we must notice that two unary operators * and ++
will have the same precedence. Therefore, by the rule of associativity, it will be
evaluated from right to left. Therefore the expression *pp++ can be rewritten as
(*(pp++)). Since, pp = 302 which will now become, 304. *pp will give 204.
On line 7, again the expression is written which prints three values, i.e., pp-p, *pp-a,
*pp. Let's calculate each one of them.
o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be
printed.
o pp = 304, *pp = 204, a = 200 => *pp-a = (204 - 200)/2 = 2, i.e., 2 will be
printed.
o pp = 304, *pp = 204, *(*pp) = 300, i.e., 300 will be printed.
Therefore, as the result of line 7, The output 2, 2, 300 will be printed on the console.
On line 8, ++*pp is written. According to the rule of associativity, this can be
rewritten as, (++(*(pp))). Since, pp = 304, *pp = 204, the value of *pp = *(p[2]) = 206
which will now point to a[3].
On line 9, again the expression is written which prints three values, i.e., pp-p, *pp-a,
*pp. Let's calculate each one of them.
o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be
printed.
o pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be
printed.
o pp = 304, *pp = 206, *(*pp) = 409, i.e., 409 will be printed.
Therefore, as the result of line 9, the output 2, 3, 409 will be printed on the console.
On line 10, ++**pp is writen. according to the rule of associativity, this can be
rewritten as, (++(*(*(pp)))). pp = 304, *pp = 206, **pp = 409, ++**pp => *pp = *pp +
1 = 410. In other words, a[3] = 410.
On line 11, again the expression is written which prints three values, i.e., pp-p, *pp-a,
*pp. Let's calculate each one of them.
o pp = 304, p = 300 => pp - p = (304 - 300)/2 => pp-p = 2, i.e., 2 will be
printed.
o pp = 304, *pp = 206, a = 200 => *pp-a = (206 - 200)/2 = 3, i.e., 3 will be
printed.
o On line 8, **pp = 410.
Therefore as the result of line 9, the output 2, 3, 410 will be printed on the console.
At last, the output of the complete program will be given as:
Output
1 1 206
2 2 300
2 3 409
2 3 410
Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc.
However, as we know that pointer contains the address, the result of an arithmetic
operation performed on the pointer will also be a pointer if the other operand is of
type integer. In pointer-from-pointer subtraction, the result will be an integer value.
Following arithmetic operations are possible on the pointer in C language:
o Increment
o Decrement
o Addition
o Subtraction
o Comparison
Incrementing Pointer in C
If we increment a pointer by 1, the pointer will start pointing to the immediate next
location. This is somewhat different from the general arithmetic since the value of the
pointer will get increased by the size of the data type to which the pointer is
pointing.
We can traverse an array by using the increment operation on a pointer which will
keep pointing to every element of the array, perform some operation on that, and
update itself in a loop.
HTML Tutorial
The Rule to increment the pointer is given below:
1. new_address= current_address + i * size_of(data type)
Where i is the number by which the pointer get increased.
32-bit
For 32-bit int variable, it will be incremented by 2 bytes.
64-bit
For 64-bit int variable, it will be incremented by 4 bytes.
Let's see the example of incrementing pointer variable on 64-bit architecture.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+1;
8. printf("After increment: Address of p variable is %u \n",p); // in our case, p will get inc
remented by 4 bytes.
9. return 0;
10. }
Output
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
Traversing an array by using pointer
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[5] = {1, 2, 3, 4, 5};
5. int *p = arr;
6. int i;
7. printf("printing array elements...\n");
8. for(i = 0; i< 5; i++)
9. {
10. printf("%d ",*(p+i));
11. }
12. }
Output
printing array elements...
1 2 3 4 5
Decrementing Pointer in C
Like increment, we can decrement a pointer variable. If we decrement a pointer, it will
start pointing to the previous location. The formula of decrementing the pointer is
given below:
1. new_address= current_address - i * size_of(data type)
32-bit
For 32-bit int variable, it will be decremented by 2 bytes.
64-bit
For 64-bit int variable, it will be decremented by 4 bytes.
Let's see the example of decrementing pointer variable on 64-bit OS.
1. #include <stdio.h>
2. void main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-1;
8. printf("After decrement: Address of p variable is %u \n",p); // P will now point to the i
mmidiate previous location.
9. }
Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is
given below:
1. new_address= current_address + (number * size_of(data type))
32-bit
For 32-bit int variable, it will add 2 * number.
64-bit
For 64-bit int variable, it will add 4 * number.
Let's see the example of adding value to pointer variable on 64-bit architecture.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p+3; //adding 3 to pointer variable
8. printf("After adding 3: Address of p variable is %u \n",p);
9. return 0;
10. }
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
As you can see, the address of p is 3214864300. But after adding 3 with p variable, it
is 3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it
increments 12. But if we were using 32-bit architecture, it was incrementing to 6 only,
i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit OS.
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting
any number from a pointer will give an address. The formula of subtracting value
from the pointer variable is given below:
1. new_address= current_address - (number * size_of(data type))
32-bit
For 32-bit int variable, it will subtract 2 * number.
64-bit
For 64-bit int variable, it will subtract 4 * number.
Let's see the example of subtracting value from the pointer variable on 64-bit
architecture.
1. #include<stdio.h>
2. int main(){
3. int number=50;
4. int *p;//pointer to int
5. p=&number;//stores the address of number variable
6. printf("Address of p variable is %u \n",p);
7. p=p-3; //subtracting 3 from pointer variable
8. printf("After subtracting 3: Address of p variable is %u \n",p);
9. return 0;
10. }
Output
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the
previous address value.
However, instead of subtracting a number, we can also subtract an address from
another address (pointer). This will result in a number. It will not be a simple
arithmetic operation, but it will follow the following rule.
If two pointers are of the same type,
1. Address2 - Address1 = (Subtraction of two addresses)/size of data type which pointe
r points
Consider the following example to subtract one pointer from an another.
1. #include<stdio.h>
2. void main ()
3. {
4. int i = 100;
5. int *p = &i;
6. int *temp;
7. temp = p;
8. p = p + 3;
9. printf("Pointer Subtraction: %d - %d = %d",p, temp, p-temp);
10. }
Output
Pointer Subtraction: 1030585080 - 1030585068 = 3
Illegal arithmetic with pointers
There are various operations which can not be performed on pointers. Since, pointer
stores address hence we must ignore the operations which may lead to an illegal
address, for example, addition, and multiplication. A list of such operations is given
below.
o Address + Address = illegal
o Address * Address = illegal
o Address % Address = illegal
o Address / Address = illegal
o Address & Address = illegal
o Address ^ Address = illegal
o Address | Address = illegal
o ~Address = illegal
Pointer to function in C
As we discussed in the previous chapter, a pointer can point to a function in C.
However, the declaration of the pointer variable must be the same as the function.
Consider the following example to make a pointer pointing to the function.
1. #include<stdio.h>
2. int addition ();
3. int main ()
4. {
5. int result;
6. int (*ptr)();
7. ptr = &addition;
8. result = (*ptr)();
9. printf("The sum is %d",result);
10. }
11. int addition()
12. {
13. int a, b;
14. printf("Enter two numbers?");
15. scanf("%d %d",&a,&b);
16. return a+b;
17. }
Output
Enter two numbers?10 15
The sum is 25
Pointer to Array of functions in C
To understand the concept of an array of functions, we must understand the array of
function. Basically, an array of the function is an array which contains the addresses
of functions. In other words, the pointer to an array of functions is a pointer pointing
to an array which contains the pointers to the functions. Consider the following
example.
1. #include<stdio.h>
2. int show();
3. int showadd(int);
4. int (*arr[3])();
5. int (*(*ptr)[3])();
6.
7. int main ()
8. {
9. int result1;
10. arr[0] = show;
11. arr[1] = showadd;
12. ptr = &arr;
13. result1 = (**ptr)();
14. printf("printing the value returned by show : %d",result1);
15. (*(*ptr+1))(result1);
16. }
17. int show()
18. {
19. int a = 65;
20. return a++;
21. }
22. int showadd(int b)
23. {
24. printf("\nAdding 90 to the value returned by show: %d",b+90);
25. }
Output
printing the value returned by show : 65
Adding 90 to the value returned by show: 155
Dangling Pointers in C
The most common bugs related to pointers and memory management is
dangling/wild pointers. Sometimes the programmer fails to initialize the pointer with
a valid address, then this type of initialized pointer is known as a dangling pointer in
C.
Dangling pointer occurs at the time of the object destruction when the object is
deleted or de-allocated from memory without modifying the value of the pointer. In
this case, the pointer is pointing to the memory, which is de-allocated. The dangling
pointer can point to the memory, which contains either the program code or the
code of the operating system. If we assign the value to this pointer, then it overwrites
the value of the program code or operating system instructions; in such cases, the
program will show the undesirable result or may even crash. If the memory is re-
allocated to some other process, then we dereference the dangling pointer will cause
the segmentation faults.
Let's observe the following examples.
In the above figure, we can observe that the Pointer 3 is a dangling pointer. Pointer
1 and Pointer 2 are the pointers that point to the allocated objects, i.e., Object 1 and
Object 2, respectively. Pointer 3 is a dangling pointer as it points to the de-allocated
object.
OOPs Concepts in Java
Let's understand the dangling pointer through some C programs.
Using free() function to de-allocate the memory.
1. #include <stdio.h>
2. int main()
3. {
4. int *ptr=(int *)malloc(sizeof(int));
5. int a=560;
6. ptr=&a;
7. free(ptr);
8. return 0;
9. }
In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a
pointer and 'a' is a integer variable. The *ptr is a pointer variable which is created
with the help of malloc() function. As we know that malloc() function returns void, so
we use int * to convert void pointer into int pointer.
The statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4
bytes shown in the below image:
The statement free(ptr) de-allocates the memory as shown in the below image with
a cross sign, and 'ptr' pointer becomes dangling as it is pointing to the de-allocated
memory.
If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted
memory. Therefore, we can say that ptr is not a dangling pointer, as shown in the
below image:
sizeof() operator in C
The sizeof() operator is commonly used in C. It determines the size of the expression
or the data type specified in the number of char-sized storage units.
The sizeof() operator contains a single operand which can be either an expression or
a data typecast where the cast is data type enclosed within parenthesis. The data
type cannot only be primitive data types such as integer or floating data types, but it
can also be pointer data types and compound data types such as unions and structs.
Need of sizeof() operator
Mainly, programs know the storage size of the primitive data types. Though the
storage size of the data type is constant, it varies when implemented in different
platforms. For example, we dynamically allocate the array space by
using sizeof() operator:
1. int *ptr=malloc(10*sizeof(int));
In the above example, we use the sizeof() operator, which is applied to the cast of
type int. We use malloc() function to allocate the memory and returns the pointer
which is pointing to this allocated memory. The memory space is equal to the
number of bytes occupied by the int data type and multiplied by 10.
Note:
The output can vary on different machines such as on 32-bit operating system
will show different output, and the 64-bit operating system will show the
different outputs of the same data types.
The sizeof() operator behaves differently according to the type of the operand.
o Operand is a data type
o Operand is an expression
When operand is a data type.
1. #include <stdio.h>
2. int main()
3. {
4. int x=89; // variable declaration.
5. printf("size of the variable x is %d", sizeof(x)); // Displaying the size of ?x? variable.
const Pointer in C
Constant Pointers
A constant pointer in C cannot change the address of the variable to which it is
pointing, i.e., the address will remain constant. Therefore, we can say that if a
constant pointer is pointing to some variable, then it cannot point to any other
variable.
Syntax of Constant Pointer
1. <type of pointer> *const <name of pointer>;
Declaration of a constant pointer is given below:
1. int *const ptr;
Let's understand the constant pointer through an example.
1. #include <stdio.h>
2. int main()
3. {
4. int a=1;
5. int b=2;
6. int *const ptr;
7. ptr=&a;
8. ptr=&b;
9. printf("Value of ptr is :%d",*ptr);
10. return 0;
11. }
In the above code:
PHP Design Patterns course preview - PHP Dependency injection and factory pattern -
Advanced OOP PHP
o We declare two variables, i.e., a and b with values 1 and 2, respectively.
o We declare a constant pointer.
o First, we assign the address of variable 'a' to the pointer 'ptr'.
o Then, we assign the address of variable 'b' to the pointer 'ptr'.
o Lastly, we try to print the value of the variable pointed by the 'ptr'.
Output
In the above output, we can observe that the above code produces the error
"assignment of read-only variable 'ptr'". It means that the value of the variable 'ptr'
which 'ptr' is holding cannot be changed. In the above code, we are changing the
value of 'ptr' from &a to &b, which is not possible with constant pointers. Therefore,
we can say that the constant pointer, which points to some variable, cannot point to
another variable.
Pointer to Constant
A pointer to constant is a pointer through which the value of the variable that the
pointer points cannot be changed. The address of these pointers can be changed,
but the value of the variable that the pointer points cannot be changed.
Syntax of Pointer to Constant
1. const <type of pointer>* <name of pointer>
Declaration of a pointer to constant is given below:
1. const int* ptr;
Let's understand through an example.
o First, we write the code where we are changing the value of a pointer
1. #include <stdio.h>
2. int main()
3. {
4. int a=100;
5. int b=200;
6. const int* ptr;
7. ptr=&a;
8. ptr=&b;
9. printf("Value of ptr is :%u",ptr);
10. return 0;
11. }
In the above code:
o We declare two variables, i.e., a and b with the values 100 and 200
respectively.
o We declare a pointer to constant.
o First, we assign the address of variable 'a' to the pointer 'ptr'.
o Then, we assign the address of variable 'b' to the pointer 'ptr'.
o Lastly, we try to print the value of 'ptr'.
Output
The above code runs successfully, and it shows the value of 'ptr' in the output.
o Now, we write the code in which we are changing the value of the variable to
which the pointer points.
1. #include <stdio.h>
2. int main()
3. {
4. int a=100;
5. int b=200;
6. const int* ptr;
7. ptr=&b;
8. *ptr=300;
9. printf("Value of ptr is :%d",*ptr);
10. return 0;
11. }
In the above code:
o We declare two variables, i.e., 'a' and 'b' with the values 100 and 200
respectively.
o We declare a pointer to constant.
o We assign the address of the variable 'b' to the pointer 'ptr'.
o Then, we try to modify the value of the variable 'b' through the pointer 'ptr'.
o Lastly, we try to print the value of the variable which is pointed by the pointer
'ptr'.
Output
The above code shows the error "assignment of read-only location '*ptr'". This error
means that we cannot change the value of the variable to which the pointer is
pointing.
Constant Pointer to a Constant
A constant pointer to a constant is a pointer, which is a combination of the above
two pointers. It can neither change the address of the variable to which it is pointing
nor it can change the value placed at this address.
Syntax
1. const <type of pointer>* const <name of the pointer>;
Declaration for a constant pointer to a constant is given below:
1. const int* const ptr;
Let's understand through an example.
1. #include <stdio.h>
2. int main()
3. {
4. int a=10;
5. int b=90;
6. const int* const ptr=&a;
7. *ptr=12;
8. ptr=&b;
9. printf("Value of ptr is :%d",*ptr);
10. return 0;
11. }
In the above code:
o We declare two variables, i.e., 'a' and 'b' with the values 10 and 90,
respectively.
o We declare a constant pointer to a constant and then assign the address of 'a'.
o We try to change the value of the variable 'a' through the pointer 'ptr'.
o Then we try to assign the address of variable 'b' to the pointer 'ptr'.
o Lastly, we print the value of the variable, which is pointed by the pointer 'ptr'.
Output
The above code shows the error "assignment of read-only location '*ptr'" and
"assignment of read-only variable 'ptr'". Therefore, we conclude that the constant
pointer to a constant can change neither address nor value, which is pointing by this
pointer.
void pointer in C
Till now, we have studied that the address assigned to a pointer should be of the
same type as specified in the pointer declaration. For example, if we declare the int
pointer, then this int pointer cannot point to the float variable or some other type of
variable, i.e., it can point to only int type variable. To overcome this problem, we use
a pointer to void. A pointer to void means a generic pointer that can point to any
data type. We can assign the address of any data type to the void pointer, and a void
pointer can be assigned to any type of the pointer without performing any explicit
typecasting.
Syntax of void pointer
1. void *pointer name;
Declaration of the void pointer is given below:
1. void *ptr;
In the above declaration, the void is the type of the pointer, and 'ptr' is the name of
the pointer.
Let us consider some examples:
Hello Java Program for Beginners
int i=9; // integer variable initialization.
int *p; // integer pointer declaration.
float *fp; // floating pointer declaration.
void *ptr; // void pointer declaration.
p=fp; // incorrect.
fp=&i; // incorrect
ptr=p; // correct
ptr=fp; // correct
ptr=&i; // correct
Size of the void pointer in C
The size of the void pointer in C is the same as the size of the pointer of character
type. According to C perception, the representation of a pointer to void is the same
as the pointer of character type. The size of the pointer will vary depending on the
platform that you are using.
Let's look at the below example:
1. #include <stdio.h>
2. int main()
3. {
4. void *ptr = NULL; //void pointer
5. int *p = NULL;// integer pointer
6. char *cp = NULL;//character pointer
7. float *fp = NULL;//float pointer
8. //size of void pointer
9. printf("size of void pointer = %d\n\n",sizeof(ptr));
10. //size of integer pointer
11. printf("size of integer pointer = %d\n\n",sizeof(p));
12. //size of character pointer
13. printf("size of character pointer = %d\n\n",sizeof(cp));
14. //size of float pointer
15. printf("size of float pointer = %d\n\n",sizeof(fp));
16. return 0;
17. }
Output
Advantages of void pointer
Following are the advantages of a void pointer:
o The malloc() and calloc() function return the void pointer, so these functions
can be used to allocate the memory of any data type.
1. #include <stdio.h>
2. #include<malloc.h>
3. int main()
4. {
5. int a=90;
6.
7. int *x = (int*)malloc(sizeof(int)) ;
8. x=&a;
9. printf("Value which is pointed by x pointer : %d",*x);
10. return 0;
11. }
Output
o The void pointer in C can also be used to implement the generic functions in
C.
Some important points related to void pointer are:
o Dereferencing a void pointer in C
The void pointer in C cannot be dereferenced directly. Let's see the below example.
1. #include <stdio.h>
2. int main()
3. {
4. int a=90;
5. void *ptr;
6. ptr=&a;
7. printf("Value which is pointed by ptr pointer : %d",*ptr);
8. return 0;
9. }
In the above code, *ptr is a void pointer which is pointing to the integer variable 'a'.
As we already know that the void pointer cannot be dereferenced, so the above code
will give the compile-time error because we are printing the value of the variable
pointed by the pointer 'ptr' directly.
Output
C dereference pointer
As we already know that "what is a pointer", a pointer is a variable that stores the
address of another variable. The dereference operator is also known as an indirection
operator, which is represented by (*). When indirection operator (*) is used with the
pointer variable, then it is known as dereferencing a pointer. When we dereference
a pointer, then the value of the variable pointed by this pointer will be returned.
Why we use dereferencing pointer?
Dereference a pointer is used because of the following reasons:
o It can be used to access or manipulate the data stored at the memory
location, which is pointed by the pointer.
o Any operation applied to the dereferenced pointer will directly affect the value
of the variable that it points to.
Let's observe the following steps to dereference a pointer.
o First, we declare the integer variable to which the pointer points.
1. int x =9;
o Now, we declare the integer pointer variable.
1. int *ptr;
o After the declaration of an integer pointer variable, we store the address of 'x'
variable to the pointer variable 'ptr'.
1. ptr=&x;
o We can change the value of 'x' variable by dereferencing a pointer 'ptr' as
given below:
1. *ptr =8;
The above line changes the value of 'x' variable from 9 to 8 because 'ptr' points to
the 'x' location and dereferencing of 'ptr', i.e., *ptr=8 will update the value of x.
Let's combine all the above steps:
1. #include <stdio.h>
2. int main()
3. {
4. int x=9;
5. int *ptr;
6. ptr=&x;
7. *ptr=8;
8. printf("value of x is : %d", x);
9. return 0;}
Output
malloc() function in C
The malloc() function allocates single block of requested memory.
Features of Java - Javatpoint
It doesn't initialize memory at execution time, so it has garbage value initially.
It returns NULL if memory is not sufficient.
The syntax of malloc() function is given below:
1. ptr=(cast-type*)malloc(byte-size)
Let's see the example of malloc() function.
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
calloc() function in C
The calloc() function allocates multiple block of requested memory.
It initially initialize all bytes to zero.
It returns NULL if memory is not sufficient.
The syntax of calloc() function is given below:
1. ptr=(cast-type*)calloc(number, byte-size)
Let's see the example of calloc() function.
1. #include<stdio.h>
2. #include<stdlib.h>
3. int main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. return 0;
22. }
Output
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by
realloc() function. In short, it changes the memory size.
Let's see the syntax of realloc() function.
1. ptr=realloc(ptr, new-size)
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling
free() function. Otherwise, it will consume memory until program exit.
Let's see the syntax of free() function.
1. free(ptr)
C Strings
The string can be defined as the one-dimensional array of characters terminated by a
null ('\0'). The character array or the string is used to manipulate text such as word or
sentences. Each character in the array occupies one byte of memory, and the last
character must always be 0. The termination character ('\0') is important in a string
since it is the only way to identify where the string ends. When we define a string as
char s[10], the character s[10] is implicitly initialized with the null in the memory.
There are two ways to declare a string in c language.
1. By char array
2. By string literal
Let's see the example of declaring string by char array in C language.
1. char ch[10]={'i', 'n', 'd', 'i', 'a', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given
below.
How to find Nth Highest Salary in SQL
0 1 2 3 4 5
i n d i a \0
While declaring string, size is not mandatory. So we can write the above code as
given below:
1. char ch[]={'i', 'n', 'd', 'i', 'a', '\0'};
We can also define the string by the string literal in C language. For example:
1. char ch[]="india";
In such case, '\0' will be appended at the end of the string by the compiler.
Difference between char array and string literal
There are two main differences between char array and literal.
o We need to add the null character '\0' at the end of the array by ourself
whereas, it is appended internally by the compiler in the case of the character
array.
o The string literal cannot be reassigned to another set of characters whereas,
we can reassign the characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is
used as a format specifier for the string in c language.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[6]= {'i', 'n', 'd', 'i', 'a', '\0'};
5. char ch2[6]="india";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }
Output
Char Array Value is: india
String Literal Value is: india
Traversing String
Traversing the string is one of the most important aspects in any of the
programming languages. We may need to manipulate a very large text which can be
done by traversing the text. Traversing string is somewhat different from the
traversing an integer array. We need to know the length of the array to traverse an
integer array, whereas we may use the null character in the case of string to identify
the end the string and terminate the loop.
Hence, there are two ways to traverse a string.
o By using the length of string
o By using the null character.
Let's discuss each one of them.
Using the length of string
Let's see an example of counting the number of vowels in a string.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "welcome";
5. int i = 0;
6. int count = 0;
7. while(i<11)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
The number of vowels 3
Using the null character
Let's see the same example of counting the number of vowels by using the null
character.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "india";
5. int i = 0;
6. int count = 0;
7. while(s[i] != NULL)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
Output
The number of vowels 3
Accepting string as the input
Till now, we have used scanf to accept the input from the user. However, it can also
be used in the case of strings but with a different scenario. Consider the below code
which stores the string while space is encountered.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[20];
5. printf("Enter the string?");
6. scanf("%s",s);
7. printf("You entered %s",s);
8. }
Output
Enter the string?india is the best
You entered india
It is clear from the output that, the above code will not work for space separated
strings. To make this code working for the space separated strings, the minor
changed required in the scanf function, i.e., instead of writing scanf("%s",s), we must
write: scanf("%[^\n]s",s) which instructs the compiler to store the string s while the
new line (\n) is encountered. Let's consider the following example to store the space-
separated strings.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[20];
5. printf("Enter the string?");
6. scanf("%[^\n]s",s);
7. printf("You entered %s",s);
8. }
Output
Enter the string?india is the best
You entered india is the best
Here we must also notice that we do not need to use address of (&) operator in scanf
to store a string since string s is an array of characters and the name of the array, i.e.,
s indicates the base address of the string (character array) therefore we need not use
& with it.
Some important points
However, there are the following points which must be noticed while entering the
strings by using scanf.
o The compiler doesn't perform bounds checking on the character array. Hence,
there can be a case where the length of the string can exceed the dimension
of the character array which may always overwrite some important data.
o Instead of using scanf, we may use gets() which is an inbuilt function defined
in a header file string.h. The gets() is capable of receiving only one string at a
time.
Pointers with strings
We have used pointers with the array, functions, and primitive data types so far.
However, pointers can be used to point to the strings. There are various advantages
of using pointers to point strings. Let us consider the following example to access the
string via the pointer.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "india";
5. char *p = s; // pointer p is pointing to string s.
6. printf("%s",p); // the string india is printed if we print p.
7. }
Output
india
As we know that string is an array of characters, the pointers can be used in the same
way they were used with arrays. In the above example, p is declared as a pointer to
the array of characters s. P affects similar to s since s is the base address of the string
and treated as a pointer internally. However, we can not change the content of s or
copy the content of s into another string directly. For this purpose, we need to use
the pointers to store the strings. In the following example, we have shown the use of
pointers to copy the content of a string into another.
1. #include<stdio.h>
2. void main ()
3. {
4. char *p = "hello india";
5. printf("String p: %s\n",p);
6. char *q;
7. printf("copying the content of p into q...\n");
8. q = p;
9. printf("String q: %s\n",q);
10. }
Output
String p: hello india
copying the content of p into q...
String q: hello india
Once a string is defined, it cannot be reassigned to another set of characters.
However, using pointers, we can assign the set of characters to the string. Consider
the following example.
1. #include<stdio.h>
2. void main ()
3. {
4. char *p = "hello india";
5. printf("Before assigning: %s\n",p);
6. p = "hello";
7. printf("After assigning: %s\n",p);
8. }
Output
Before assigning: hello india
After assigning: hello
1. #include<stdio.h>
2. void main()
3. {
4. char str[4];
5. printf("Enter the string? ");
6. fgets(str, 4, stdin);
7. printf("%s", str);
8. }
Output
Enter the string? india is the best website
indi
C puts() function
The puts() function is very much similar to printf() function. The puts() function is
used to print the string on the console which is previously read by using gets() or
scanf() function. The puts() function returns an integer value representing the
number of characters being printed on the console. Since, it prints an additional
newline character with the string, which moves the cursor to the new line on the
console, the integer value returned by puts() will always be equal to the number of
characters present in the string plus 1.
Declaration
1. int puts(char[])
Let's see an example to read a string using gets() and print it on the console using
puts().
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char name[50];
5. printf("Enter your name: ");
6. gets(name); //reads string from user
7. printf("Your name is: ");
8. puts(name); //displays string
9. return 0;
10. }
Output:
Enter your name: Kishore kumar
Your name is: Kishore kumar
C String Functions
There are many important string functions defined in "string.h" library.
C Math
C Programming allows us to perform mathematical operations through the functions
defined in <math.h> header file. The <math.h> header file contains various methods
for performing mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
C Math Functions
There are various methods in math.h header file. The commonly used functions of
math.h header file are given below.
2) floor(number) rounds down the given number. It returns the integer value
which is less than or equal to given number.
C Math Example
Let's see a simple example of math functions found in math.h header file.
1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }
Output:
HTML Tutorial
4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12
C Structure
Why use structure?
In C, there are cases where we need to store multiple attributes of an entity. It is not
necessary that an entity has all the information of one type only. It can have different
attributes of different data types. For example, an entity Student may have its name
(string), roll number (int), marks (float). To store such type of information regarding
an entity student, we have the following approaches:
o Construct individual arrays for storing names, roll numbers, and marks.
o Use a special data structure to store the collection of different data types.
Let's look at the first approach in detail.
1. #include<stdio.h>
2. void main ()
3. {
4. char names[2][10],dummy; // 2-dimensioanal character array names is used to store
the names of the students
5. int roll_numbers[2],i;
6. float marks[2];
7. for (i=0;i<3;i++)
8. {
9.
10. printf("Enter the name, roll number, and marks of the student %d",i+1);
11. scanf("%s %d %f",&names[i],&roll_numbers[i],&marks[i]);
12. scanf("%c",&dummy); // enter will be stored into dummy character at each iteratio
n
13. }
14. printf("Printing the Student details ...\n");
15. for (i=0;i<3;i++)
16. {
17. printf("%s %d %f\n",names[i],roll_numbers[i],marks[i]);
18. }
19. }
Output
Enter the name, roll number, and marks of the student 1Arun 90
91
Enter the name, roll number, and marks of the student 2Varun
91 56
Enter the name, roll number, and marks of the student 3Sham 89
69
What is Structure
Structure in c is a user-defined data type that enables us to store the collection of
different data types. Each element of a structure is called a member. Structures ca;
simulate the use of classes and templates as it can store various information
The ,struct keyword is used to define the structure. Let's see the syntax to define the
structure in c.
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
Let's see the example to define a structure for an entity employee in c.
1. struct employee
2. { int id;
3. char name[20];
4. float salary;
5. };
The following image shows the memory allocation of the structure employee that is
defined in the above example.
Here, struct is the keyword; employee is the name of the structure; id, name,
and salary are the members or fields of the structure. Let's understand it by the
diagram given below:
typedef in C
The typedef is a keyword used in C programming to provide some meaningful
names to the already existing variable in the C program. It behaves similarly as we
define the alias for the commands. In short, we can say that this keyword is used to
redefine the name of an already existing variable.
Syntax of typedef
1. typedef <existing_name> <alias_name>
In the above syntax, 'existing_name' is the name of an already existing variable
while 'alias name' is another name given to the existing variable.
For example, suppose we want to create a variable of type unsigned int, then it
becomes a tedious task if we want to declare multiple variables of this type. To
overcome the problem, we use a typedef keyword.
1. typedef unsigned int unit;
In the above statements, we have declared the unit variable of type unsigned int by
using a typedef keyword.
Now, we can create the variables of type unsigned int by writing the following
statement:
1. unit a, b;
instead of writing:
1. unsigned int a, b;
Till now, we have observed that the typedef keyword provides a nice shortcut by
providing an alternative name for an already existing variable. This keyword is useful
when we are dealing with the long data type especially, structure declarations.
Let's understand through a simple example.
1. #include <stdio.h>
2. int main()
3. {
4. typedef unsigned int unit;
5. unit i,j;
6. i=10;
7. j=20;
8. printf("Value of i is :%d",i);
9. printf("\nValue of j is :%d",j);
10. return 0;
11. }
Output
Value of i is :10
Value of j is :20
Using typedef with structures
Consider the below structure declaration:
1. struct student
2. {
3. char name[20];
4. int age;
5. };
6. struct student s1;
In the above structure declaration, we have created the variable of student type by
writing the following statement:
1. struct student s1;
The above statement shows the creation of a variable, i.e., s1, but the statement is
quite big. To avoid such a big statement, we use the typedef keyword to create the
variable of type student.
1. struct student
2. {
3. char name[20];
4. int age;
5. };
6. typedef struct student stud;
7. stud s1, s2;
In the above statement, we have declared the variable stud of type struct student.
Now, we can use the stud variable in a program to create the variables of type struct
student.
The above typedef can be written as:
1. typedef struct student
2. {
3. char name[20];
4. int age;
5. } stud;
6. stud s1,s2;
From the above declarations, we conclude that typedef keyword reduces the length
of the code and complexity of data types. It also helps in understanding the program.
Let's see another example where we typedef the structure declaration.
1. #include <stdio.h>
2. typedef struct student
3. {
4. char name[20];
5. int age;
6. }stud;
7. int main()
8. {
9. stud s1;
10. printf("Enter the details of student s1: ");
11. printf("\nEnter the name of the student:");
12. scanf("%s",&s1.name);
13. printf("\nEnter the age of student:");
14. scanf("%d",&s1.age);
15. printf("\n Name of the student is : %s", s1.name);
16. printf("\n Age of the student is : %d", s1.age);
17. return 0;
18. }
Output
Enter the details of student s1:
Enter the name of the student: Peter
Enter the age of student: 28
Name of the student is : Peter
Age of the student is : 28
Using typedef with pointers
We can also provide another name or alias name to the pointer variables with the
help of the typedef.
For example, we normally declare a pointer, as shown below:
1. int* ptr;
We can rename the above pointer variable as given below:
1. typedef int* ptr;
In the above statement, we have declared the variable of type int*. Now, we can
create the variable of type int* by simply using the 'ptr' variable as shown in the
below statement:
1. ptr p1, p2 ;
In the above statement, p1 and p2 are the variables of type 'ptr'.
C Array of Structures
Why use an array of structures?
Consider a case, where we need to store the data of 5 students. We can store it by
using the structure as given below.
1. #include<stdio.h>
2. struct student
3. {
4. char name[20];
5. int id;
6. float marks;
7. };
8. void main()
9. {
10. struct student s1,s2,s3;
11. int dummy;
12. printf("Enter the name, id, and marks of student 1 ");
13. scanf("%s %d %f",s1.name,&s1.id,&s1.marks);
14. scanf("%c",&dummy);
15. printf("Enter the name, id, and marks of student 2 ");
16. scanf("%s %d %f",s2.name,&s2.id,&s2.marks);
17. scanf("%c",&dummy);
18. printf("Enter the name, id, and marks of student 3 ");
19. scanf("%s %d %f",s3.name,&s3.id,&s3.marks);
20. scanf("%c",&dummy);
21. printf("Printing the details....\n");
22. printf("%s %d %f\n",s1.name,s1.id,s1.marks);
23. printf("%s %d %f\n",s2.name,s2.id,s2.marks);
24. printf("%s %d %f\n",s3.name,s3.id,s3.marks);
25. }
Output
Enter the name, id, and marks of student 1 James 90 90
Enter the name, id, and marks of student 2 Adoms 90 90
Enter the name, id, and marks of student 3 Nick 90 90
Printing the details....
James 90 90.000000
Adoms 90 90.000000
Nick 90 90.000000
In the above program, we have stored data of 3 students in the structure. However,
the complexity of the program will be increased if there are 20 students. In that case,
we will have to declare 20 different structure variables and store them one by one.
This will always be tough since we will have to declare a variable every time we add a
student. Remembering the name of all the variables is also a very tricky task.
However, c enables us to declare an array of structures by using which, we can avoid
declaring the different structure variables; instead we can make a collection
containing all the structures that store the information of different entities.
Array of Structures in C
An array of structres in C can be defined as the collection of multiple structures
variables where each variable contains information about different entities. The array
of structures in C are used to store information about multiple entities of different
data types. The array of structures is also known as the collection of structures.
Java Try Catch
Arun
Delhi
110001
1234567890
City: Delhi
Pincode: 110001
Phone: 1234567890
The structure can be nested in the following ways.
1. By separate structure
2. By Embedded structure
1) Separate structure
Here, we create two structures, but the dependent structure should be used inside
the main structure as a member. Consider the following example.
How to find Nth Highest Salary in SQL
1. struct Date
2. {
3. int dd;
4. int mm;
5. int yyyy;
6. };
7. struct Employee
8. {
9. int id;
10. char name[20];
11. struct Date doj;
12. }emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a
member in Employee structure. In this way, we can use Date structure in many
structures.
2) Embedded structure
The embedded structure enables us to declare the structure inside the structure.
Hence, it requires less line of codes but it can not be used in multiple data structures.
Consider the following example.
1. struct Employee
2. {
3. int id;
4. char name[20];
5. struct Date
6. {
7. int dd;
8. int mm;
9. int yyyy;
10. }doj;
11. }emp1;
Accessing Nested Structure
We can access the member of the nested structure by
Outer_Structure.Nested_Structure.member as given below:
1. e1.doj.dd
2. e1.doj.mm
3. e1.doj.yyyy
C Nested Structure example
Let's see a simple example of the nested structure in C language.
1. #include <stdio.h>
2. #include <string.h>
3. struct Employee
4. {
5. int id;
6. char name[20];
7. struct Date
8. {
9. int dd;
10. int mm;
11. int yyyy;
12. }doj;
13. }e1;
14. int main( )
15. {
16. //storing employee information
17. e1.id=101;
18. strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
19. e1.doj.dd=10;
20. e1.doj.mm=11;
21. e1.doj.yyyy=2014;
22.
23. //printing first employee information
24. printf( "employee id : %d\n", e1.id);
25. printf( "employee name : %s\n", e1.name);
26. printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.m
m,e1.doj.yyyy);
27. return 0;
28. }
Output:
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014
Passing structure to function
Just like other variables, a structure can also be passed to a function. We may pass
the structure members into the function or pass the structure variable at once.
Consider the following example to pass the structure variable employee to a function
display() which is used to display the details of an employee.
1. #include<stdio.h>
2. struct address
3. {
4. char city[20];
5. int pin;
6. char phone[14];
7. };
8. struct employee
9. {
10. char name[20];
11. struct address add;
12. };
13. void display(struct employee);
14. void main ()
15. {
16. struct employee emp;
17. printf("Enter employee information?\n");
18. scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
19. display(emp);
20. }
21. void display(struct employee emp)
22. {
23. printf("Printing the details....\n");
24. printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
25. }
Structure Padding in C
Structure padding is a concept in C that adds the one or more empty bytes between
the memory addresses to align the data in memory.
Let's first understand the structure padding in C through a simple scenario
which is given below:
Suppose we create a user-defined structure. When we create an object of this
structure, then the contiguous memory will be allocated to the structure members.
1. struct student
2. {
3. char a;
4. char b;
5. int c;
6. } stud1;
In the above example, we have created a structure of type student. We have
declared the object of this structure named as 'stud1'. After the creation of an object,
a contiguous block of memory is allocated to its structure members. First, the
memory will be allocated to the 'a' variable, then 'b' variable, and then 'c' variable.
C++ vs Java
As we know that structure occupies the contiguous block of memory as shown in the
above diagram, i.e., 1 byte for char a, 1 byte for char b, and 4 bytes for int c, then
what problem do we face in this case.
What's the problem?
The 4-bytes can be accessed at a time as we are considering the 32-bit architecture.
The problem is that in one CPU cycle, one byte of char a, one byte of char b, and 2
bytes of int c can be accessed. We will not face any problem while accessing
the char a and char b as both the variables can be accessed in one CPU cycle, but we
will face the problem when we access the int c variable as 2 CPU cycles are required
to access the value of the 'c' variable. In the first CPU cycle, the first two bytes are
accessed, and in the second cycle, the other two bytes are accessed.
Suppose we do not want to access the 'a' and 'b' variable, we only want to access the
variable 'c', which requires two cycles. The variable 'c' is of 4 bytes, so it can be
accessed in one cycle also, but in this scenario, it is utilizing 2 cycles. This is an
unnecessary wastage of CPU cycles. Due to this reason, the structure padding
concept was introduced to save the number of CPU cycles. The structure padding is
done automatically by the compiler. Now, we will see how structure padding is done.
How is structure padding done?
In order to achieve the structure padding, an empty row is created on the left, as
shown in the above diagram, and the two bytes which are occupied by the 'c'
variable on the left are shifted to the right. So, all the four bytes of 'c' variable are on
the right. Now, the 'c' variable can be accessed in a single CPU cycle. After structure
padding, the total memory occupied by the structure is 8 bytes (1 byte+1 byte+2
bytes+4 bytes), which is greater than the previous one. Although the memory is
wasted in this case, the variable can be accessed within a single cycle.
Let's create a simple program of structures.
1. #include <stdio.h>
2. struct student
3. {
4. char a;
5. char b;
6. int c;
7. };
8. int main()
9. {
10. struct student stud1; // variable declaration of the student type..
11. // Displaying the size of the structure student.
12. printf("The size of the student structure is %d", sizeof(stud1));
13. return 0;
14. }
In the above code, we have created a structure named 'student'. Inside
the main() method, we declare a variable of student type, i.e., stud1, and then we
calculate the size of the student by using the sizeof() operator. The output would
be 8 bytes due to the concept of structure padding, which we have already
discussed in the above.
Output
o Now, the memory will be allocated to the int b Since the int variable occupies
4 bytes, but on the left, only 3 bytes are available. The empty row will be
created on these 3 bytes, and the int variable would occupy the other 4 bytes
so that the integer variable can be accessed in a single CPU cycle.
o Now, the memory will be given to the char c At a time, CPU can access 1
word, which is equal to 4 bytes, so CPU will use 4 bytes to access a 'c' variable.
Therefore, the total memory required is 12 bytes (4 bytes +4 bytes +4 bytes),
i.e., 4 bytes required to access char a variable, 4 bytes required to access int
b variable, and other 4 bytes required to access a single character of ' c'
variable.
How to avoid the structure padding in C?
The structural padding is an in-built process that is automatically done by the
compiler. Sometimes it required to avoid the structure padding in C as it makes the
size of the structure greater than the size of the structure members.
We can avoid the structure padding in C in two ways:
o Using #pragma pack(1) directive
o Using attribute
Using #pragma pack(1) directive
1. #include <stdio.h>
2. #pragma pack(1)
3. struct base
4. {
5. int a;
6. char b;
7. double c;
8. };
9. int main()
10. {
11. struct base var; // variable declaration of type base
12. // Displaying the size of the structure base
13. printf("The size of the var is : %d", sizeof(var));
14. return 0;
15. }
In the above code, we have used the #pragma pack(1) directive to avoid the
structure padding. If we do not use this directive, then the output of the above
program would be 16 bytes. But the actual size of the structure members is 13 bytes,
so 3 bytes are wasted. To avoid the wastage of memory, we use the #pragma
pack(1) directive to provide the 1-byte packaging.
Output
o By using attribute
1. #include <stdio.h>
2.
3. struct base
4. {
5. int a;
6. char b;
7. double c;
8. }__attribute__((packed)); ;
9. int main()
10. {
11. struct base var; // variable declaration of type base
12. // Displaying the size of the structure base
13. printf("The size of the var is : %d", sizeof(var));
14.
15. return 0;
16. }
Output
Union in C
Union can be defined as a user-defined data type which is a collection of different
variables of different data types in the same memory location. The union can also be
defined as many members, but only one member can contain a value at a particular
point in time.
Union is a user-defined data type, but unlike structures, they share the same memory
location.
Let's understand this through an example.
1. struct abc
2. {
3. int a;
4. char b;
5. }
The above code is the user-defined structure that consists of two members, i.e., 'a' of
type int and 'b' of type character. When we check the addresses of 'a' and 'b', we
found that their addresses are different. Therefore, we conclude that the members in
the structure do not share the same memory location.
How to find Nth Highest Salary in SQL
When we define the union, then we found that union is defined in the same way as
the structure is defined but the difference is that union keyword is used for defining
the union data type, whereas the struct keyword is used for defining the structure.
The union contains the data members, i.e., 'a' and 'b', when we check the addresses
of both the variables then we found that both have the same addresses. It means
that the union members share the same memory location.
Let's have a look at the pictorial representation of the memory allocation.
The below figure shows the pictorial representation of the structure. The structure
has two members; i.e., one is of integer type, and the other one is of character type.
Since 1 block is equal to 1 byte; therefore, 'a' variable will be allocated 4 blocks of
memory while 'b' variable will be allocated 1 block of memory.
The below figure shows the pictorial representation of union members. Both the
variables are sharing the same memory location and having the same initial address.
In union, members will share the memory location. If we try to make changes in any
of the member then it will be reflected to the other member as well. Let's understand
this concept through an example.
1. union abc
2. {
3. int a;
4. char b;
5. }var;
6. int main()
7. {
8. var.a = 66;
9. printf("\n a = %d", var.a);
10. printf("\n b = %d", var.b);
11. }
In the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a variable of
union abc type. In the main() method, we assign the 66 to 'a' variable, so var.a will
print 66 on the screen. Since both 'a' and 'b' share the memory location, var.b will
print 'B' (ascii code of 66).
Deciding the size of the union
The size of the union is based on the size of the largest member of the union.
Let's understand through an example.
1. union abc{
2. int a;
3. char b;
4. float c;
5. double d;
6. };
7. int main()
8. {
9. printf("Size of union abc is %d", sizeof(union abc));
10. return 0;
11. }
As we know, the size of int is 4 bytes, size of char is 1 byte, size of float is 4 bytes, and
the size of double is 8 bytes. Since the double variable occupies the largest memory
among all the four variables, so total 8 bytes will be allocated in the memory.
Therefore, the output of the above program would be 8 bytes.
Accessing members of union using pointers
We can access the members of the union through pointers by using the (->) arrow
operator.
Let's understand through an example.
1. #include <stdio.h>
2. union abc
3. {
4. int a;
5. char b;
6. };
7. int main()
8. {
9. union abc *ptr; // pointer variable declaration
10. union abc var;
11. var.a= 90;
12. ptr = &var;
13. printf("The value of a is : %d", ptr->a);
14. return 0;
15. }
In the above code, we have created a pointer variable, i.e., *ptr, that stores the
address of var variable. Now, ptr can access the variable 'a' by using the (->)
operator. Hence the output of the above code would be 90.
Why do we need C unions?
Consider one example to understand the need for C unions. Let's consider a store
that has two items:
o Books
o Shirts
Store owners want to store the records of the above-mentioned two items along
with the relevant information. For example, Books include Title, Author, no of pages,
price, and Shirts include Color, design, size, and price. The 'price' property is common
in both items. The Store owner wants to store the properties, then how he/she will
store the records.
Initially, they decided to store the records in a structure as shown below:
1. struct store
2. {
3. double price;
4. char *title;
5. char *author;
6. int number_pages;
7. int color;
8. int size;
9. char *design;
10. };
The above structure consists of all the items that store owner wants to store. The
above structure is completely usable but the price is common property in both the
items and the rest of the items are individual. The properties like price, *title, *author,
and number_pages belong to Books while color, size, *design belongs to Shirt.
Let's see how can we access the members of the structure.
1. int main()
2. {
3. struct store book;
4. book.title = "C programming";
5. book.author = "Paulo Cohelo";
6. book.number_pages = 190;
7. book.price = 205;
8. printf("Size is : %ld bytes", sizeof(book));
9. return 0;
10. }
In the above code, we have created a variable of type store. We have assigned the
values to the variables, title, author, number_pages, price but the book variable does
not possess the properties such as size, color, and design. Hence, it's a wastage of
memory. The size of the above structure would be 44 bytes.
We can save lots of space if we use unions.
1. #include <stdio.h>
2. struct store
3. {
4. double price;
5. union
6. {
7. struct{
8. char *title;
9. char *author;
10. int number_pages;
11. } book;
12.
13. struct {
14. int color;
15. int size;
16. char *design;
17. } shirt;
18. }item;
19. };
20. int main()
21. {
22. struct store s;
23. s.item.book.title = "C programming";
24. s.item.book.author = "John";
25. s.item.book.number_pages = 189;
26. printf("Size is %ld", sizeof(s));
27. return 0;
28. }
In the above code, we have created a variable of type store. Since we used the unions
in the above code, so the largest memory occupied by the variable would be
considered for the memory allocation. The output of the above program is 32 bytes.
In the case of structures, we obtained 44 bytes, while in the case of unions, the size
obtained is 44 bytes. Hence, 44 bytes is greater than 32 bytes saving lots of memory
space.
File Handling in C
In programming, we may require some specific input data to be generated several
numbers of times. Sometimes, it is not enough to only display the data on the
console. The data to be displayed may be very large, and only a limited amount of
data can be displayed on the console, and since the memory is volatile, it is
impossible to recover the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on
the local file system through our C program. The following operations can be
performed on a file.
o Creation of the new file
o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file
Next
Stay
Mode Description
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. clrscr();
6.
7. fp=fopen("myfile2.txt","w");
8. fputs("hello c programming",fp);
9.
10. fclose(fp);
11. getch();
12. }
myfile2.txt
hello c programming
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to
write data into file at desired location.
Syntax:
1. int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR
and SEEK_END.
Example:
Java Try Catch
1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }
myfile.txt
This is sonoo jaiswal
C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful
if you have to use stream many times.
Syntax:
1. void rewind(FILE *stream)
Example:
File: file.txt
History of Java
1. this is a simple text
File: rewind.c
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("file.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12.
13. rewind(fp);//moves the file pointer at beginning of the file
14.
15. while((c=fgetc(fp))!=EOF){
16. printf("%c",c);
17. }
18.
19. fclose(fp);
20. getch();
21. }
Output:
this is a simple textthis is a simple text
As you can see, rewind() function moves the file pointer at beginning of the file that
is why "this is simple text" is printed 2 times. If you don't call rewind() function, "this
is simple text" will be printed only once.
C ftell() function
The ftell() function returns the current file position of the specified stream. We can
use ftell() function to get the total size of a file after moving file pointer at the end of
file. We can use SEEK_END constant to move the file pointer at the end of file.
Syntax:
1. long int ftell(FILE *stream)
Example:
File: ftell.c
HTML Tutorial
1. #include <stdio.h>
2. #include <conio.h>
3. void main (){
4. FILE *fp;
5. int length;
6. clrscr();
7. fp = fopen("file.txt", "r");
8. fseek(fp, 0, SEEK_END);
9.
10. length = ftell(fp);
11.
12. fclose(fp);
13. printf("Size of file: %d bytes", length);
14. getch();
15. }
Output:
Size of file: 21 bytes
C Preprocessor Directives
The C preprocessor is a micro processor that is used by compiler to transform your code
before compilation. It is called micro preprocessor because it allows us to add macros.
Note: Proprocessor direcives are executed before compilation.
C Predefined Macros
ANSI C defines many predefined macros that can be used in c program.
C #include
The #include preprocessor directive is used to paste code of given file into current
file. It is used include system-defined and user-defined header files. If included file is
not found, compiler renders error.
By the use of #include directive, we provide information to the preprocessor where
to look for the header files. There are two variants to use #include directive.
1. #include <filename>
2. #include "filename"
The #include <filename> tells the compiler to look for the directory where system
header files are held. In UNIX, it is \usr\include directory.
The #include "filename" tells the compiler to look in the current directory from
where program is running.
Prime Ministers of India | List of Prime Minister of India (1947-2020)
#include directive example
Let's see a simple example of #include directive. In this program, we are including
stdio.h file because printf() function is defined in this file.
1. #include<stdio.h>
2. int main(){
3. printf("Hello C");
4. return 0;
5. }
Output:
Hello C
#include notes:
Note 1: In #include directive, comments are not recognized. So in case of #include
<a//b>, a//b is treated as filename.
Note 2: In #include directive, backslash is considered as normal text not escape
sequence. So in case of #include <a\nb>, a\nb is treated as filename.
Note 3: You can use only comment after filename otherwise it will give error.
C #define
The #define preprocessor directive is used to define constant or micro substitution. It
can use any basic data type.
Syntax:
1. #define token value
Let's see an example of #define to define a constant.
1. #include <stdio.h>
2. #define PI 3.14
3. main() {
4. printf("%f",PI);
5. }
Output:
Java Try Catch
3.140000
Let's see an example of #define to create a macro.
1. #include <stdio.h>
2. #define MIN(a,b) ((a)<(b)?(a):(b))
3. void main() {
4. printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
5. }
Output:
Minimum between 10 and 20 is: 10
C Expressions
An expression is a formula in which operands are linked to each other by the use of
operators to compute a value. An operand can be a function reference, a variable, an
array element or a constant.
Let's see an example:
1. a-b;
In the above expression, minus character (-) is an operator, and a, and b are the two
operands.
There are four types of expressions exist in C:
o Arithmetic expressions
o Relational expressions
o Logical expressions
o Conditional expressions
Each type of expression takes certain types of operands and uses a specific set of
operators. Evaluation of a particular expression produces a specific value.
For example:
1. x = 9/2 + a-b;
The entire above line is a statement, not an expression. The portion after the equal is
an expression.
Arithmetic Expressions
An arithmetic expression is an expression that consists of operands and arithmetic
operators. An arithmetic expression computes a value of type int, float or double.
When an expression contains only integral operands, then it is known as pure integer
expression when it contains only real operands, it is known as pure real expression,
and when it contains both integral and real operands, it is known as mixed mode
expression.
Evaluation of Arithmetic Expressions
The expressions are evaluated by performing one operation at a time. The
precedence and associativity of operators decide the order of the evaluation of
individual operations.
When individual operations are performed, the following cases can be
happened:
o When both the operands are of type integer, then arithmetic will be
performed, and the result of the operation would be an integer value. For
example, 3/2 will yield 1 not 1.5 as the fractional part is ignored.
o When both the operands are of type float, then arithmetic will be performed,
and the result of the operation would be a real value. For example, 2.0/2.0 will
yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the
mixed arithmetic will be performed. In this case, the first operand is converted
into a real operand, and then arithmetic is performed to produce the real
value. For example, 6/2.0 will yield 3.0 as the first value of 6 is converted into
6.0 and then arithmetic is performed to produce 3.0.
Let's understand through an example.
6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)
Evaluation of expression Description of each operation
Relational Expressions
o A relational expression is an expression used to compare two operands.
o It is a condition which is used to decide whether the action should be taken or
not.
o In relational expressions, a numeric value cannot be compared with the string
value.
o The result of the relational expression can be either zero or non-zero value.
Here, the zero value is equivalent to a false and non-zero value is equivalent
to true.
Relational Description
Expression
a+b = = x+y It is used to check whether the expression "a+b" is equal to the
expression "x+y".
Logical Description
Expressions
( x > 4 ) && It is a test condition to check whether the x is greater than 4 and x
(x<6) is less than 6. The result of the condition is true only when both
the conditions are true.
! ( x > 10 ) && It is a test condition used to check whether x is not greater than
(y==2) 10 and y is equal to 2. The result of the condition is true if both
the conditions are true.
Conditional Expressions
o A conditional expression is an expression that returns 1 if the condition is true
otherwise 0.
o A conditional operator is also known as a ternary operator.
The Syntax of Conditional operator
Suppose exp1, exp2 and exp3 are three expressions.
exp1 ? exp2 : exp3
The above expression is a conditional expression which is evaluated on the basis of
the value of the exp1 expression. If the condition of the expression exp1 holds true,
then the final conditional expression is represented by exp2 otherwise represented
by exp3.
Let's understand through a simple example.
1. #include<stdio.h>
2. #include<string.h>
3. int main()
4. {
5. int age = 25;
6. char status;
7. status = (age>22) ? 'M': 'U';
8. if(status == 'M')
9. printf("Married");
10. else
11. printf("Unmarried");
12. return 0;
13. }
Output