C Lecture Notes Topic Wise
C Lecture Notes Topic Wise
Introduction To C
In 1988, the American National Standards Institute (ANSI) had formalized the
C language.
C was invented to write UNIX operating system.
C is a successor of 'Basic Combined Programming Language' (BCPL)
called B language.
Linux OS, PHP, and MySQL are written in C.
C has been written in assembly language.
Database Systems
Language Interpreters
Compilers and Assemblers
Operating Systems
Network Drivers
Word Processors
Advantages of C
C is the building block for many other programming languages.
Programs written in C are highly portable.
Several standard functions are there (like in-built) that can be used to develop
programs.
C programs are collections of C library functions, and it's also easy to add
own functions to the C library.
The modular structure makes code debugging, maintenance and testing
easier.
Disadvantages of C
C does not provide Object Oriented Programming (OOP) concepts.
There are no concepts of Namespace in C.
C does not provide binding or wrapping up of data in a single unit.
C does not provide Constructor and Destructor.
Difficult to debug.
C allows a lot of freedom in writing code, and that is why you can put an
empty line or white space anywhere in the program. And because there is no
fixed place to start or end the line, so it is difficult to read and understand the
program.
C compilers can only identify errors and are incapable of handling exceptions
(run-time errors).
C provides no data protection.
It also doesn't feature reusability of source code extensively.
It does not provide strict data type checking (for example an integer value can
be passed for floating datatype).
C is imperative language and designed to compile in a relatively straightforward
manner which provides low-level access to the memory. With the gradual
Problem Solving through programming in C Page 2
PPS
increase in the popularity of the program, the language and its compiler have
become available on a wide range of platforms from embedded
microcontrollers to supercomputers.
With the introduction of K&R C language (which is a new edition of C published
in 1978 by Brian Kernighan and Denis Ritchie), several features have been
included in C language.
During the late 1980's, C was started to use for a wide variety of mainframe
computers, micro and mini computers which began to get famous. Gradually C
got its superset - i.e., C++ which has added features, but its developed from C
with all its initial concepts.
Compiler:
List Of C compilers:
Since there are various compilers available into the online market, here are the
lists of some of the frequently used ones:
CCS C Compiler
Turbo C
Minimalist GNU for Windows (MinGW)
Portable C Compiler
Clang C++
Digital Mars C++ Compiler
Intel C++
IBM C++
Visual C++ : Express Edition
Oracle C++
All of these above compilers for C are free to download, but there are some
other paid C compilers also available, or programmers can get it for trial
version:
Embarcadero C++
Edison Design Group C++
Green Hills C++
HP C++ for Unix
Intel C++ for Windows, Linux, and some embedded systems.
Microsoft C++
Paradigm C++
A C program involves the following sections:
/* Author: www.w3schools.in
Date: 2018-04-28
Description:
#include<stdio.h>
int main()
printf("Hello, World!\n");
return 0;
or in a different way
/* Author: www.w3schools.in
Date: 2013-11-15
Description:
#include<stdio.h>
#include<conio.h>
void main()
printf("Hello, World!\n");
return;
Program Output:
The above example has been used to print Hello, World! Text on the screen.
/* Comments */ Comments are a way of explaining what makes a program. The compiler
ignores comments and used by others to understand the code.
or
#include<stdio.h> stdio is standard for input / output, this allows us to use some commands
which includes a file called stdio.h.
or
main() The main() is the main function where program execution begins. Every
C program must contain only one main function.
or
This is the main function, which is the default entry point for every C
program and the void in front of it indicates that it does not return a
value.
Braces Two curly brackets "{...}" are used to group all statements.
or
Curly braces which shows how much the main() function has its scope.
or
The example discussed above illustrates how a simple C program looks like
and how the program segment works. A C program may contain one or more
sections which are figured above.
Declaration part
Execution part
The declaration part is used to declare all variables that will be used within the
program. There needs to be at least one statement in the executable part, and
these two parts are declared within the opening and closing curly braces of the
main(). The execution of the program begins at the opening brace '{' and ends
with the closing brace '}'. Also, it has to be noted that all the statements of
these two parts need to be terminated with a semi-colon.
The sub-program section deals with all user-defined functions that are called
from the main(). These user-defined functions are declared and usually defined
after the main() function.
C input/output functions:
Majority of the programs take data as input, and then after processing the
processed data is being displayed which is called information. In C
programming you can use scanf() and printf() predefined function to read and
print data.
#include<stdio.h>
void main()
{
int a,b,c;
printf("Please enter any two numbers: \n");
scanf("%d %d", &a, &b);
c = a + b;
printf("The addition of two number is: %d", c);
}
Output:
Please enter any two numbers:
12
3
The addition of two number is:15
The above program scanf() is used to take input from the user, and respectively printf() is
used to display output result on the screen.
Managing Input/Output:
I/O operations are useful for a program to interact with users. stdlib is the
standard C library for input-output operations. While dealing with input-output
operations in C, there are two important streams that play their role. These are:
Standard input or stdin is used for taking input from devices such as the
keyboard as a data stream. Standard output or stdout is used for giving output
to a device such as a monitor. For using I/O functionality, programmers must
include stdio header-file within the program.
Reading character in C:
The easiest and simplest of all I/O operations are taking a character as input by
reading that character from standard input (keyboard). getchar() function can
be used to read a single character. This function is alternate to scanf() function.
var_name = getchar();
#include<stdio.h>
void main()
{
char title;
title = getchar();
}
There is another function to do that task for files: getc which is used to accept a
character from standard input.
int getc(FILE *stream);
Writing Character in C:
Similar to getchar() there is another function which is used to write characters,
but one at a time.
Syntax:
putchar(var_name);
#include<stdio.h>
void main()
{
char result = 'P';
putchar(result);
putchar('\n');
}
Similarly, there is another function putc which is used for sending a single
character to the standard output.
int putc(int c, FILE *stream);
Formated Input:
It refers to an input data which has been arranged in a specific format. This is
possible in C using scanf(). We have already encountered this and familiar with
this function.
Syntax:
gets: The char *gets(char *str) reads a line from stdin and keeps the string
pointed to by the str and is terminated when the new line is read or EOF is
reached. The declaration of gets() function is:
syntax:
puts: The function - int puts(const char *str) is used to write a string to stdout,
but it does not include null characters. A new line character needs to be
appended to the output. The declaration is:
syntax:
C format specifiers:
There are mostly six types of format specifiers that are available in C.
Syntax:
printf("%d",<variable name>);
Syntax:
Syntax:
printf("%c",<variable name>);
Syntax:
printf("%s",<variable name>);
Syntax:
printf("%u",<variable name>);
Syntax:
printf("%ld",<variable name>);
Identifiers
Keywords
Constants
Strings
Operators
Special Symbols
Example:
int amount;
double totalbalance;
In the above example, amount and total balance are identifiers and int, and
double are keywords.
C Keywords:
can't use a keyword as an identifier in your C programs, its reserved words in C
library and used to perform an internal operation. The meaning and working of
these keywords are already known to the compiler.
C Keywords List
A list of 32 reserved keywords in c language is given below:
do if static while
#include<stdio.h>
main()
{
float a, b;
return 0;
}
In the above program, float and return are keywords. The float is used to
declare variables, and return is used to return an integer type value in
this program.
Constants are like a variable, except that their value never changes during
execution once defined.
Constant Definition in C
Syntax:
Example:
#include<stdio.h>
main()
int area;
area = SIDE*SIDE;
, SIDE, area);
Program Output:
or
Constant Types in C
Constants are categorized into two basic types, and each of these types has
own subtypes/categories. These are:
Primary Constants
1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants
Integer Constant
It's referring to a sequence of digits. Integers are of three types viz:
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6
Real constant
The numbers containing fractional parts like 99.25 are called real or floating
points constant.
Example:
String Constants
These are a sequence of characters enclosed in double quotes, and they may
include letters, digits, special characters, and blank spaces. It is again to be
noted that "G" and 'G' are different - because "G" represents a string as it is
enclosed within a pair of double quotes whereas 'G' represents a single
character.
Example:
For Example:
Constants Meaning
\a beep sound
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\\ backslash
\0 null
Secondary Constant
Array
Pointer
Structure
Union
Enum
C Operators:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operator
Bitwise Operators
Special Operators
Arithmetic Operators
Arithmetic Operators are used to performing mathematical calculations like
addition (+), subtraction (-), multiplication (*), division (/) and modulus (%).
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
#include <stdio.h>
void main()
Program Output:
Operator Description
++ Increment
−− Decrement
#include <stdio.h>
void main()
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
Program Output:
5 4
4 3
3 2
2 1
1 0
Relational Operators
Relational operators are used to compare two quantities or values.
Operator Description
== Is equal to
!= Is not equal to
Logical Operators
C provides three logical operators when we test more than one condition to
make decisions. These are: && (meaning logical AND), || (meaning logical OR)
and ! (meaning logical NOT).
Operator Description
&& And operator. It performs a logical conjunction of two expressions. (if both expressions
evaluate to True, result is True. If either expression evaluates to False, the result is Fals
|| Or operator. It performs a logical disjunction on two expressions. (if either or both expre
evaluate to True, the result is True)
Bitwise Operators
C provides a special operator for bit operation between two variables.
Operator Description
| Binary OR Operator
Assignment Operators
Assignment operators applied to assign the result of an expression to a
variable. C has a collection of shorthand assignment operators.
Operator Description
= Assign
Conditional Operator
C offers a ternary operator which is the conditional operator (?: in combination)
to construct conditional expressions.
Operator Description
?: Conditional Expression
Special Operators
C supports some special operators
Operator Description
* Pointer to a variable.
#include <stdio.h>
void main()
Program Output:
C Data Types:
void As the name suggests it holds no value and is generally used for specifying th
of function or what it returns. If the function has a void type, it means that the f
will not return any value.
_Bool
_Complex
_Imaginary
Example:
int age;
char letter;
Arrays Arrays are sequences of data items having homogeneous values. They
have adjacent memory locations to store values.
Pointers These are powerful C features which are used to access the memory
and deal with their addresses.
Union These allow storing various data types in the same memory location.
Programmers can define a union with different members, but only a
single member can contain a value at given time. It is used for
#include <stdio.h>
int main()
Example:
#include <stdio.h>
#include <limits.h>
int main()
return 0;
Program Output:
C Variables:
The primary purpose of variables is to store data in memory for later use.
Unlike constants which do not change during the program execution, variables
value may change during execution. If you declare a variable in C, that means
you are asking to the operating system for reserve a piece of memory with that
variable name.
Variable Definition in C
Syntax:
type variable_name;
or
Example:
int width, height=5;
char letter='A';
double d;
age = 26.5;
Variable Assignment
Variable assignment is a process of assigning a value to a variable.
Example:
int width = 60;
void main()
Program Output:
I am 33 years old.
Storage Classes:
Storage Classes are associated with variables for describing the features of
any variable or function in C program. These storage classes deal with features
such as scope, lifetime and visibility which helps programmers to define a
particular variable during program's runtime. These storage classes are
preceded by the data type which they had to modify.
auto
register
static
extern
Syntax:
is same as:
The above example has a variable name roll with auto as a storage class. This
storage class can only be implemented with the local variables.
Syntax:
Example:
// loop body
Example:
Example:
#include <stdio.h>
int val;
main()
val = 10;
funcExtern();
Another example:
Example:
#include <stdio.h>
extern int val; // now the variable val can be accessed and used from
anywhere
void funcExtern()
C Preprocessors:
The preprocessor is a program invoked by the compiler that modifies the
source code before the actual composition takes place.
To use any preprocessor directives, first, we have to prefix them with pound
symbol #.
Compiler control division #line Set line number, Abort compilation, Set compiler
#error option
#pragma
C Preprocessors Examples
Syntax:
#include <stdio.h>
#define LIMIT 10
int main()
int counter;
printf("%d\n",counter);
return 0;
#include <stdio.h>
#include "header.h"
#include <stdio.h> tell the compiler to add stdio.h file from System Libraries to
the current source file, and #include "header.h" tells compiler to get header.h
from the local directory.
#undef LIMIT
#define LIMIT 20
This tells the compiler to undefine existing LIMIT and set it as 20.
#ifndef LIMIT
#define LIMIT 50
#endif
This tells the compiler to define LIMIT, only if LIMIT isn't already defined.
#ifdef LIMIT
C Header Files:
C language is famous for its different libraries and the predefined functions pre-
written within it. These make programmer's effort a lot easier. In this tutorial,
you will be learning about C header files and how these header files can be
included in your C program and how it works within your C language.
Header files are helping file of your C program which holds the definitions of
various functions and their associated variables that needs to be imported into
your C program with the help of pre-processor #includestatement. All the
header file have a '.h' an extension that contains C function declaration and
macro definitions. In other words, the header files can be requested using the
preprocessor directive#include. The default header file that comes with the C
compiler is the stdio.h.
Including a header file means that using the content of header file in your
source program. A straightforward practice while programming in C or C++
programs is that you can keep every macro, global variables, constants, and
other function prototypes in the header files. The basic syntax of using these
header files is:
Syntax:
#include <file>
or
#include "file"
This kind of file inclusion is implemented for including system oriented header
files. This technique (with angular braces) searches for your file-name in the
standard list of system directories or within the compiler's directory of header
files. Whereas, the second kind of header file is used for user defined header
files or other external files for your program. This technique is used to search
for the file(s) within the directory that contains the current file.
Example:
then, you have a main C source program which seems something like this:
Example:
#include<stdio.h>
int x;
#include "karl.h"
int main ()
printf("Program done");
return 0;
So, the compiler will see the entire C program and token stream as:
Example:
#include<stdio.h>
int x;
int main ()
printf("Program done");
return 0;
Syntax:
#ifndef HEADER_FILE_NAME
#define HEADER_FILE_NAME
#endif
Again, sometimes it's essential for selecting several diverse header files based
on some requirement to be incorporated into your program. For this also
multiple conditional preprocessors can be used like this:
Syntax:
#if FIRST_SYSTEM
#include "sys.h"
#elif SEC_SYSTEM
#include "sys2.h"
#elif THRID_SYSTEM
....
#endif
C Type Casting:
Type Casting in C is used to convert a variable from one data type to another
data type, and after type casting compiler treats the variable as of the new data
type.
Syntax:
(type_name) expression
main ()
int a;
a = 15/6;
printf("%d",a);
Program Output:
In the above C program, 15/6 alone will produce integer
value as 2.
main ()
float a;
a = (float) 15/6;
printf("%f",a);
Program Output:
After type cast is done before division to retain float
value 2.500000.
C Conditional Statements:
C conditional statements allow you to make a decision, based upon the result
of a condition. These statements are called as Decision Making
Statements or Conditional Statements.
So far, we have seen that all set of statements in a C program gets executed
sequentially in the order in which they are written and appear. This occurs
when there is no jump based statements or repetitions of certain calculations.
But some situations may arise where we may have to change the order of
execution of statements depending on some specific conditions. This involves
a kind of decision making from a set of calculations. It is to be noted that C
language assumes any non-zero or non-null value as true and if zero or null,
treated as false.
This type of structure requires that the programmers indicate several conditions
for evaluation within a program. The statement(s) will get executed only if the
condition becomes true and optionally, alternative statement or set of
statements will get executed if the condition becomes false.
Conditional Statements in C
If statement
o if statement
o if-else statement
o Nested if-else statement
o else if-statement
goto statement
switch statement
Conditional Operator
C If statements:
Simple if Statement
if-else Statement
Nested if-else Statement
else-if Ladder
Syntax:
if(test_expression)
statement 1;
statement 2;
...
#include<stdio.h>
main()
if (b & gt; a) {
printf("b is greater");
Program Output:
Example:
#include<stdio.h>
main()
int number;
number = -number;
grtch();
Program Output:
If-Else Statements:
If else statements in C is also used to control the program flow based on some
condition, only the difference is: it's used to execute some statement code
block if the expression is evaluated to true, otherwise executes else statement
code block.
Syntax:
if(test_expression)
else
#include<stdio.h>
main()
int a, b;
if (a & gt; b) {
printf("\n a is greater");
} else {
printf("\n b is greater");
Program Output:
Example:
#include<stdio.h>
main() {
int num;
scanf("%d", num);
else
Program Output:
Syntax:
if(test_expression one)
if(test_expression two) {
else
#include<stdio.h>
main()
int x=20,y=30;
if(x==20)
if(y==30)
Output:
Else-if statements:
Syntax:
if(test_expression)
else if(test_expression n)
else
#include<stdio.h>
main()
int a, b;
if (a & gt; b)
else
Program Output:
Goto statements:
Syntax:
goto label;
A label is an identifier required for goto statement to a place where the branch
is to be made. A label is a valid variable name which is followed by a colon and
is put immediately before the statement where the control needs to be
jumped/transferred unconditionally.
Syntax:
goto label;
Problem Solving through programming in C Page 56
PPS
- - -- - -
- - - - - - - -
label:
statement - X;
or
label:
- - -- - -
- - - - - - - -
goto label;
#include<stdio.h>
void main()
int age;
g: //label name
s: //label name
scanf("%d", &age);
if(age>=18)
else
getch();
Switch statements:
C switch statement is used when you have multiple possibilities for the if
statement.
Syntax:
switch(variable)
case 1:
break;
case n:
break;
default:
break;
After the end of each block it is necessary to insert a break statement because
if the programmers do not use the break statement, all consecutive blocks of
codes will get executed from every case onwards after matching the case
block.
#include<stdio.h>
main()
int a;
scanf("%d",&a);
switch(a)
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default :
break;
Program Output:
When none of the cases is evaluated to true, the default case will be executed,
and break statement is not required for default statement.
Loops:
A computer is the most suitable machine to perform repetitive tasks and can
tirelessly do a task tens of thousands of times. Every programming language
has the feature to instruct to do such repetitive tasks with the help of certain
form of statements. The process of repeatedly executing a collection of
statement is called looping. The statements get executed many numbers of
times based on the condition. But if the condition is given in such logic that the
repetition continues any number of times with no fixed condition to stop looping
those statements, then this type of looping is called infinite looping.
while loops
do while loops
Problem Solving through programming in C Page 61
PPS
for loops
All are slightly different and provides loops for different situations.
While loops:
C while loops statement allows to repeatedly run the same block of code until a
condition is met.
while loop is a most basic loop in C programming. while loop has one control condition,
and executes as long the condition is true. The condition of the loop is tested before the
body of the loop is executed, hence it is called an entry-controlled loop.
Syntax:
While (condition)
statement(s);
Incrementation;
#include<stdio.h>
int main ()
n++;
return 0;
Program Output:
Do while loops:
C do while loops are very similar to the while loops, but it always executes the
code block at least once and furthermore as long as the condition remains true.
This is an exit-controlled loop.
Syntax:
do
statement(s);
}while( condition );
#include<stdio.h>
int main ()
/* do loops execution */ do
n = n + 1;
return 0;
Program Output:
For loops:
C for loops is very similar to a while loops in that it continues to process a block
of code until a statement becomes false, and everything is defined in a single
line. The for loop is also entry-controlled loop.
Syntax:
statement(s);
#include<stdio.h>
int main ()
return 0;
Program Output:
Functions:
Parts of Function
1. Function Prototype (function declaration)
2. Function Definition
3. Function Call
1. Function Prototype
Syntax:
Example:
int addition();
2. Function Definition
Syntax:
Example:
int addition()
3. Calling a function in C
#include<stdio.h>
int main()
return 0;
return num1+num2;
Program Output:
Function arguments:
Type Description
Call by Value
Example:
#include<stdio.h>
int main()
int num2 = 5;
return 0;
return a + b;
Program Output:
The addition of two numbers is: 15
Call by Reference
Example:
#include<stdio.h>
int main()
int num2 = 5;
return 0;
return *a + *b;
Program Output:
The addition of two numbers is: 15
Library functions:
The C library functions are provided by the system and stored in the library.
The C library function is also called an inbuilt function in C programming.
To use Inbuilt Function in C, you must include their respective header files,
which contain prototypes and data definitions of the function.
#include<ctype.h>
#include<math.h>
void main()
printf("%d\n", abs(i));
printf("%f\n", sin(rad));
printf("%f\n", cos(rad));
printf("%f\n", exp(e));
printf("%d\n", log(d));
Program Output:
Variable scope:
A scope is a region of the program, and the scope of variables refers to the
area of the program where the variables can be accessed after its declaration.
In C each and every variable defined in a scope. You can define scope as the
section or region of a program where a variable has its existence; moreover,
that variable cannot be used or accessed beyond that region.
Position Type
Local Variables
Variables that are declared within the function block and can be used only
within the function is called local variables.
Example:
#include <stdio.h>
int main ()
y = 30;
z = x + y;
return 0;
Global Variables
Variables that are declared outside of a function block and can be accessed
inside the function is called global variables.
Global Scope
Global variables are defined outside a function or any specific block, in most of
the case, on the top of the C program. These variables hold their values all
through the end of the program and are accessible within any of the functions
defined in your program.
Any function can access variables defined within the global scope, i.e., its
availability stays for the entire program after being declared.
Example:
#include <stdio.h>
int main ()
y = 30;
z = x + y;
return 0;
int 0
char '\0'
float 0
double 0
pointer NULL
Example:
#include<stdio.h>
#include"swap.h"
void main()
int a=20;
int b=30;
swap (&a,&b);
printf ("b=%d\n",b);
Swap method is defined in swap.h file, which is used to swap two numbers by
using a temporary variable.
Example:
void swap (int* a, int* b)
{ int tmp;
tmp = *a;
*a = *b;
*b = tmp;
Note:
Recursion:
What is Recursion
Recursion can be defined as the technique of replicating or doing again an
activity in a self-similar way calling itself again and again, and the process
continues till specific condition reaches. In the world of programming, when
your program lets you call that specific function from inside that function, then
this concept of calling the function from itself can be termed as recursion, and
the function in which makes this possible is called recursive function.
Example Syntax:
void rec_prog(void) {
int main(void) {
rec_prog();
return 0;
C program allows you to do such calling of function within another function, i.e.,
recursion. But when you implement this recursion concept, you have to be
cautious in defining an exit or terminating condition from this recursive function,
or else it will continue to an infinite loop, so make sure that the condition is set
within your program.
Factorial Program
Example:
#include<stdio.h>
#include<conio.h>
int fact(int f) {
if (f & lt; = 1) {
printf("Calculated Factorial");
return 1;
int main(void) {
int f = 12;
clrscr();
getch();
return 0;
Fibonacci Program
Example:
#include<stdio.h>
#include<conio.h>
int fibo(int g) {
if (g == 0) {
return 0;
if (g == 1) {
return 1;
int main(void) {
int g;
clrscr();
getch();
return 0;
Arrays:
For example, if you want to store ten numbers then instead of defining ten
variables, it's easy to define an array of 10 lengths.
Define an Array in C
Syntax:
This is called a one-dimensional array. An array type can be any valid C data
types, and array size must be an integer constant greater than zero.
Example:
double amount[5];
Initialize an Array in C
Arrays can be initialized at declaration time:
int age[5]={22,25,30,32,35};
int myArray[5];
int n = 0;
for(n=0;n<sizeof(myArray);n++)
myArray[n] = n;
int myArray[5];
int n = 0;
for(n=0;n<sizeof(myArray);n++)
myArray[n] = n;
Strings:
Strings Declaration in C
There are two ways to declare a string in C programming:
Example:
char name[6];
Through pointers.
char *name;
Strings Initialization in C
Example:
'};
or
Example:
#include<stdio.h>
int main ()
#include<stdio.h>
int main ()
printf("Tutorials%s\n", name );
return 0;
'};
printf("Tutorials%s\n", name );
return 0;
}
Program Output:
TutorialsCloud
C Pointers:
A pointer is a variable in C, and pointers value is the address of a memory
location.
Pointer Definition in C
Syntax:
type *variable_name;
Example:
int *width;
char *letter;
int main ()
return 0;
Memory Management:
C language provides many functions that come in header files to deal with the
allocation and management of memories. In this tutorial, you will find brief
information about managing memory in your program using some functions
and their respective header files.
C language provides many functions that come in header files to deal with the
allocation and management of memories. In this tutorial, you will find brief
information about managing memory in your program using some functions
and their respective header files.
Management of Memory
Almost all computer languages can handle system memory. All the variables
used in your program occupies a precise memory space along with the
program itself, which needs some memory for storing itself (i.e., its own
program). Therefore, managing memory utmost care is one of the major tasks
a programmer must keep in mind while writing codes.
There are two types used for allocating memory. These are:
malloc, calloc, or realloc are the three functions used to manipulate memory.
These commonly used functions are available through the stdlib library so you
must include this library to use them.
malloc, calloc, or realloc are the three functions used to manipulate memory.
These commonly used functions are available through the stdlib library so you
must include this library to use them.
Function Syntax
malloc function
malloc function is used to allocate space in memory during the execution of
the program.
malloc function does not initialize the memory allocated during execution. It
carries garbage value.
malloc function returns null pointer if it couldn't able to allocate requested
amount of memory.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
char *mem_alloc;
if(mem_alloc== NULL )
else
strcpy( mem_alloc,"w3schools.in");
free(mem_alloc);
Program Output:
calloc function
calloc () function and malloc () function is similar. But calloc () allocates
memory for zero-initializes. However, malloc () does not.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
char *mem_alloc;
else
strcpy( mem_alloc,"w3schools.in");
free(mem_alloc);
Program Output:
realloc function
realloc function modifies the allocated memory size by malloc and calloc
functions to new size.
If enough space doesn't exist in the memory of current block to extend, a new
block is allocated for the full size of reallocation, then copies the existing data
to the new block and then frees the old block.
free function
free function frees the allocated memory by malloc (), calloc (), realloc ()
functions.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
char *mem_alloc;
else
strcpy( mem_alloc,"w3schools.in");
mem_alloc=realloc(mem_alloc,100*sizeof(char));
else
free(mem_alloc);
Program Output:
Structures:
Defining a Structure in C
Syntax:
struct structureName
//member definitions
};
Example:
struct Courses
char WebSite[50];
char Subject[50];
int Price;
};
#include<string.h>
struct Courses
char WebSite[50];
char Subject[50];
int Price;
};
void main( )
struct Courses C;
//Initialization
C.Price = 0;
Program Output:
WebSite : w3schools.in
Unions:
Defining a Union in C
Syntax:
union unionName
//member definitions
};
Example:
union Courses
char WebSite[50];
char Subject[50];
int Price;
};
#include<string.h>
union Courses
char WebSite[50];
char Subject[50];
int Price;
};
void main( )
union Courses C;
C.Price = 0;
Program Output:
WebSite : w3schools.in
Typedef:
C is such a dominant language of its time and now, that even you can name
those primary data type of your own and can create your own named data type
by blending data type and its qualifier.
C is such a dominant language of its time and now, that even you can name
those primary data type of your own and can create your own named data type
by blending data type and its qualifier.
or to use within programs. The typical format for implementing this typedef
keyword is:
Syntax:
Example:
Example:
slong g, d;
will allow you to create two variables name 'g' and 'd' which will be of type
signed long and this quality of signed long is getting detected from
the slong(typedef), which already defined the meaning of slongin your
program.
Syntax:
typedef struct
{ type first_member;
type sec_member;
type thrid_member;
} nameOfType;
Here nameOfType correspond to the definition of structure allied with it. Now,
this nameOfType can be implemented by declaring a variable of this structure
type.
Example:
#include<stdio.h>
#include<string.h>
{ char p_name[50];
int p_sal;
} prof;
void main(void)
prof pf;
int* a;
The binding of pointer (*) is done to the right here. With this kind of statement
declaration, you are in fact declaring an as a pointer of type int (integer).
pntr g, h, i;
File Handling:
C can handle files as Stream-oriented data (Text) files, and System oriented
data (Binary) files.
Stream-oriented The data is stored in the same manner as it appears on the screen. The I/O
data files operations like buffering, data conversions, etc. take place automatically.
System-oriented System-oriented data files are more closely associated with the OS and data s
data files in memory without converting into text format.
C File Operations
Five major operations can be performed on file are:
Function Uses/Purpose
Fopen:
Syntax:
FILE *fopen( const char * filePath, const char * mode );
Parameters
filePath: The first argument is a pointer to a string containing the name of the
file to be opened.
mode: The second argument is an access mode.
Mode Description
w Opens a text file for writing if the file doesn't exist then a new file is created.
a Opens a text file for appending(writing at the end of existing file) and create the file if it doe
exist.
w+ Open for reading and writing and create the file if it does not exist. If the file exists then ma
blank.
a+ Open for reading and appending and create the file if it does not exist. The reading will star
the beginning, but writing can only be appended.
Return Value
C fopen function returns NULL in case of a failure and returns a FILE stream
pointer on success.
Example:
#include<stdio.h>
int main()
FILE *fp;
fp = fopen("fileName.txt","w");
return 0;
Fclose:
fclose() function is C library function and it's used to releases the memory
stream, opened by fopen()function.
Syntax:
Return Value
C fclose returns EOF in case of failure and returns 0 on success.
Example:
#include<stdio.h>
int main()
FILE *fp;
fp = fopen("fileName.txt","w");
fclose(fp);
return 0;
Getc:
getc() function is C library function, and it's used to read a character from a file
that has been opened in read mode by fopen() function.
Syntax:
int getc( FILE * stream );
Return Value
getc() function returns next requested object from the stream on success.
Character values are returned as an unsigned char cast to an int or EOF on
end of file or error.
The function feof() and ferror() to distinguish between end-of-file and error
must be used.
Example:
#include<stdio.h>
int main()
int ch = getc(fp);
ch = getc(fp);
if (feof(fp))
else
fclose(fp);
getchar();
return 0;
Putc:
putc() function is C library function, and it's used to write a character to the
file. This function is used for writing a single character in a stream along with
that it moves forward the indicator's position.
putc() function is C library function, and it's used to write a character to the
file. This function is used for writing a single character in a stream along with
that it moves forward the indicator's position.
Syntax:
int putc( int c, FILE * stream );
Example:
int main (void)
FILE * fileName;
char ch;
fileName = fopen("anything.txt","wt");
fclose (fileName);
return 0;
Getw:
C getw function is used to read an integer from a file that has been opened in
read mode. It is a file handling function, which is used for reading integer
values.
Syntax:
int getw( FILE * stream );
putw:
Syntax:
int putw( int c, FILE * stream );
Example:
int main (void)
{ FILE *fileName;
putw(i, fileName);
putw(j, fileName);
putw(k, fileName);
fclose(fileName);
while(getw(fileName)! = EOF)
n= getw(fileName);
fclose(fp);
return 0;
Fprintf:
C fprintf function pass arguments according to the specified format to the file
indicated by the stream. This function is implemented in file related programs
for writing formatted data in any file.
Syntax:
int fprintf(FILE *stream, const char *format, ...)
Example:
int main (void)
FILE *fileName;
fileName = fopen("anything.txt","r");
fclose(fileName);
return(0);
Fscanf:
C fscanf function reads formatted input from a file. This function is implemented
in file related programs for reading formatted data from any file that is specified
in the program.
Syntax:
int fscanf(FILE *stream, const char *format, ...)
Its return the number of variables that are assigned values, or EOF if no
assignments could be made.
Example:
int main()
int yr;
FILE* fileName;
rewind(fileName);
printf("----------------------------------------------- \n");
fclose(fileName);
return (0);
Fgets:
C fgets function is implemented in file related programs for reading strings from
any particular file. It gets the strings 1 line each time.
Syntax:
char *fgets(char *str, int n, FILE *stream)
Example:
void main(void)
FILE* fileName;
char ch[100];
fclose(fileName);
Fputs:
C fputs function is implemented in file related programs for writing string to any
particular file.
Syntax:
int fputs(const char *str, FILE *stream)
Example:
void main(void)
{ FILE* fileName;
fclose(fileName);
Feof:
C feof function is used to determine if the end of the file (stream), specified has
been reached or not. This function keeps on searching the end of file (eof) in
your file program.
Syntax:
int feof(FILE *stream)
Example:
while (!feof(fileName)) {
printf("%s", strr);
fclose(fileName)
C feof function returns true in case end of file is reached, otherwise it's return
false.
C makes it possible to pass values from the command line at execution time in
your program. In this chapter, you will learn about the use of command-line
argument in C.
The main() function is the most significant function of C and C++ languages.
This main() is typically defined having a return type of integer and having no
parameters; something like this:
Example:
int main()
So you can program the main() is such a way that it can essentially accept two
arguments where the first argument denotes the number of command line
arguments whereas the second argument denotes the full list of every
command line arguments. This is how you can code your command line
argument within the parenthesis of main():
Example:
In the above statement, the command line arguments have been handled via
main() function, and you have set the arguments where
You must make sure that in your command line argument, argv[0] stores the
name of your program, similarly argv[1] gets the pointer to the 1st command
line argument that has been supplied by the user, and *argv[n]denotes the last
argument of the list.
#include <stdio.h>
if( argc == 2 )
else
Output: