C Programming
C Programming
C programming is considered as the base for other programming languages, that is why it is
known as mother language.
1. Mother language
2. System programming language
3. Procedure-oriented programming language
1
4. Structured programming language
5. Mid-level programming language
1) C as a mother language
C language is considered as the mother language of all the modern programming languages
because most of the compilers, JVMs, Kernels, etc. are written in C language, and most of
the programming languages follow C syntax, for example, C++, Java, C#, etc.
3) C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural
language specifies a series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
In the C language, we break the program into parts using functions. It makes the program easier
to understand and modify.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy to
understand.
2
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 (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. Fast Speed
8. Pointers
9. Recursion (It provides code reusability for every function. Recursion enables us to
use the approach of backtracking.)
10. Extensible (can easily adopt new features.)
#include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .
int main() The main() function is the entry point of every program in c language.
return 0 The return 0 statement, returns execution status to the OS. The 0 value is used
for successful execution and 1 for unsuccessful execution.
What is a compilation?
The compilation is a process of converting the source code into object code or machine 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 or
machine code.
3
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
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
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
4
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'.
hello.c
#include <stdio.h>
int main()
{
printf("Hello javaTpoint");
return 0;
}
5
6
printf() and scanf() in C
printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.
Variables in C
A Variable is a name given that is assigned to a memory location, which is used to contain the
corresponding value in it.
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.
void function1(){
int x=10;//local variable
7
}
Global Variable
A variable that is declared outside the function or block is called a global variable. Any function
can change the value of the global variable. It is available to all the functions.
Static Variable
A variable that is declared with the static keyword is called static variable.
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)
8
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.
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.
Keywords in C
A keyword is a reserved word that has special meaning to compiler. You cannot use it as a
variable name, constant name, etc. There are only 32 reserved words (keywords) in the C
language.
C Identifiers
Identifier is the name give to a variable, function, structure, array etc. There is a total of 63
alphanumerical characters that represent the identifiers.
9
o The first character of an identifier should be either an alphabet or an underscore, and
then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.
Types of identifiers
o Internal identifier
o External identifier
Internal Identifier
If the identifier is not used in the external linkage, then it is known as an internal identifier.
The internal identifiers can be local variables.
External Identifier
If the identifier is used in the external linkage, then it is known as an external identifier. The
external identifiers can be function names, global variable
Keyword Identifier
It must be written in a lowercase letter. It can be written in both lowercase and uppercase
letters.
Its meaning is pre-defined in the c compiler. Its meaning is not defined in the c compiler.
It does not contain the underscore character. It can contain the underscore character.
10
C Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise, etc.
There are following types of operators to perform different types of operations in C language.
1. Arithmetic Operators
2. Relational Operators
3. Shift Operators
4. Logical Operators
5. Bitwise Operators
6. Ternary or Conditional Operators
7. Assignment Operator
8. Misc Operator
Comments in C
Comments in C language are used to provide information about lines of code. It is widely used
for documenting code. There are 2 types of comments in the C language.
11
C Format Specifier
The Format specifier is a string used in the formatted input and output functions. The format
string determines the format of the input and output. The format string always starts with a '%'
character.
Format Description
specifier
%d or %i It is used to print the signed integer value where signed integer means that the variable
can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer means that the
variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value always starts with
a 0 value.
%x It is used to print the hexadecimal unsigned integer where the hexadecimal integer
value always starts with a 0x value. In this, alphabetical characters are printed in small
letters such as a, b, c, etc.
%X It is used to print the hexadecimal unsigned integer, but %X prints the alphabetical
characters in uppercase such as A, B, C, etc.
%f It is used for printing the decimal floating-point values. By default, it prints the 6 values
after '.'.
%g It is used to print the decimal floating-point values, and it uses the fixed precision, i.e.,
the value after the decimal in input would be exactly the same as the value in the
output.
12
Minimum Field Width Specifier
Suppose we want to display an output that occupies a minimum number of spaces
on the screen. You can achieve this by displaying an integer number after the
percent sign of the format specifier.
int main()
{
int x=900;
printf("%8d", x);
printf("\n%-8d",x);
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.
13
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;
}
14
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.
1. const keyword
2. #define preprocessor
1) C const keyword
The const keyword is used to define constant in C programming.
#include<stdio.h>
int main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
Output:
If you try to change the the value of PI, it will render compile time error.
#include<stdio.h>
int main(){
const float PI=3.14;
PI=4.5;
15
printf("The value of PI is: %f",PI);
return 0;
}
Output:
C #define
The #define preprocessor directive is used to define constant or micro substitution.
It can use any basic data type.
Syntax:
#include <stdio.h>
#define PI 3.14
main() {
printf("%f",PI);
}
Output:
3.140000
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
16
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
1. Keywords in C
2. Identifiers in C
3. Strings in C
4. Operators in C
5. Constant in C
6. Special Characters in C
Strings in C
char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.
char a[] = "javatpoint"; // The compiler allocates the memory at the run time.
Special characters in C
Some special characters are used in C, and they have a special meaning which
cannot be used for another purpose.
o Square brackets [ ]: The opening and closing brackets represent the single
and multidimensional subscripts.
17
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in
the opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for
example, separating function parameters in a function call, separating the
variable when printing the value of more than one variable using a single
printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically
denotes that we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an
operator for multiplication.
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.
Syntax
bool variable_name;
In the above syntax, bool is the data type of the variable, and variable_name is the
name of the variable.
#include <stdio.h>
#include<stdbool.h>
int main()
18
{
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;
}
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.
19
variable during the first function call, then this modified value will be available
for the next function call also.
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.
Static variables are limited to the source file in which they are defined, i.e., they are
not accessible by the 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.
20
There are mainly five types of errors exist in C programming:
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.
For example:
#include <stdio.h>
int main()
{
a = 10;
printf("The value of a is : %d", a);
return 0;
21
}
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.
#include <stdio.h>
int main()
{
int a=2;
int b=2/0;
printf("The value of b is : %d", b);
return 0;
}
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.
#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 loop
22
{
sum=sum+k;
k++;
}
printf("The value of sum is %d", sum);
return 0;
}
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.
23
o Array index out of bound
int a[10];
a[10] = 34;
#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.
o Syntax errors
o Semantic errors
Runtime errors
The runtime errors are the errors that occur during the execution and after
compilation. The examples of runtime errors are division by zero, etc. These errors
are not easy to detect as the compiler does not point to these errors.
24
Let's look at the differences between compile-time and runtime:
Compile-time Runtime
The compile-time errors are the errors The runtime errors are the errors which
which are produced at the compile-time, are not generated by the compiler and
and they are detected by the compiler. produce an unpredictable result at the
execution time.
In this case, the compiler prevents the In this case, the compiler does not detect
code from execution if it detects an error the error, so it cannot prevent the code
in the program. from the execution.
It contains the syntax and semantic It contains the errors such as division by
errors such as missing semicolon at the zero, determining the square root of a
end of the statement. negative number.
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 ':'.
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // cond
itional operator
25
return 0;
}
#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;
}
For example,
26
As we can observe from the above result that bits of both the variables are
compared one by one. If the bit of both the variables is 1 then the output would be
1, otherwise 0.
#include <stdio.h>
int main()
{
int a=6, b=14; // variable declarations
printf("The output of the Bitwise AND operator a&b is %d",a&b);
return 0;
}
In the above code, we have created two variables, i.e., 'a' and 'b'. The values of 'a'
and 'b' are 6 and 14 respectively. The binary value of 'a' and 'b' are 0110 and 1110,
respectively. When we apply the AND operator between these two variables,
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,
27
a = 23;
b = 10;
The binary representation of the above two variables would be:
a = 0001 0111
b = 0000 1010
When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the
output would be:
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.
#include <stdio.h>
int main()
{
int a=23,b=10; // variable declarations
printf("The output of the Bitwise OR operator a|b is %d",a|b);
return 0;
}
28
Control Statements:
If-Else (Javatpoint)
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 possible 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.
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
3) The case value can be used only inside the switch statement.
29
4) The break statement in switch case is not must. It is optional. If there is no break
statement found in the case, all the cases will be executed present after the matched
case. It is known as fall through the state of C switch statement.
5) A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none of
the cases is true. No break is needed in the default case.
Let's try to understand it by the examples. We are assuming that there are following
variables.
int x,y,z;
char a,b;
float f;
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
30
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
31
Let's try to understand the fall through state of switch statement by the example
given below.
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equal to 10\n");
case 50:
printf("number is equal to 50\n");
case 100:
printf("number is equal to 100\n");
default:
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Output
enter a number:10
number is equal to 10
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
Output
enter a number:50
number is equal to 50
number is equal to 100
number is not equal to 10, 50 or 100
32
Advantage of loops in C
1) It provides code reusability.
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked
lists).
Types of C Loops
There are three types of loops in C language that is given below:
1. do while
2. while
3. for
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:
label:
//some part of the code;
goto label;
goto example
Let's see a simple example to use goto statement in C language.
33
#include <stdio.h>
int main()
{
int num,i=1;
printf("Enter the number whose table you want to print?");
scanf("%d",&num);
table:
printf("%d x %d = %d\n",num,i,num*i);
i++;
if(i<=10)
goto table;
}
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:
(type)value;
int f= 9/4;
printf("f : %d\n", f );//Output: 2
Function Aspects
There are three aspects of a C function.
34
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.
o Function definition It contains the actual statements which are to be
executed. It is the most important aspect to which the control comes when
the function is called. Here, we must notice that only one value can be
returned from the function.
Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files
such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the complexity
of a big program and optimizes the code.
Return Value
35
A C function may or may not return a value from the function. If you don't have to
return any value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the
function.
void hello(){
printf("hello c");
}
36
Call by value and Call by reference in C
There are two methods to pass the data into the function in C language, i.e., call by
value and call by reference.
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.
37
Let's try to understand the concept of call by value in c language by the example
given below:
#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}
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
38
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actua
l parameters do not change by changing the formal parameters in call by value, a =
10, b = 20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parame
ters, a = 20, b = 10
}
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 = 10, b = 20
Call by reference in C
o In call by reference, the address of the variable is passed into the function call
as the actual parameter.
o The value of the actual parameters can be modified by changing the formal
parameters since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function are
performed on the value stored at the address of the actual parameters, and
the modified value gets stored at the same address.
#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
39
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}
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
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
1 A copy of the value is passed into the An address of value is passed into the
function function
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
41
}
int main()
{
int arr[5]={45,67,34,78,90};
getarray(arr);
return 0;
}
#include <stdio.h>
void printarray(char *arr)
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%c ", arr[i]);
}
}
int main()
{
char arr[5]={'A','B','C','D','E'};
printarray(arr);
return 0;
}
42
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.
int n = 10;
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.
Pointer Example
An example of using pointers to print the address and value is given below.
43
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.
#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
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.
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 containe
d by p.
return 0;
}
Output
44
More Details:
https://www.tutorialspoint.com/cprogramming/c_pointers.htm
https://www.javatpoint.com/c-pointers
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static
memory allocation and dynamic memory allocation.
45
Now let's have a quick look at the methods used for dynamic memory allocation.
46
Difference between Structure and Union:
47