Learn C Programming
Learn C Programming
PROGRAMMING
CH Srilaxmi
Author Profile:
Alphabets ...................................................................................................................................................................................... 22
Digits ............................................................................................................................................................................................ 22
C Keywords ..............................................................................................................................................................................22
C Identifiers .............................................................................................................................................................................23
Variables ..................................................................................................................................................................................23
Constants/Literals: A constant is a value or an identifier whose value cannot be altered in a program. For example: 1, 2.5,
"C programming is easy", etc. .................................................................................................................................................24
2. Floating-point constants............................................................................................................................................................ 25
5. String constants......................................................................................................................................................................... 26
Conditional Compilation..........................................................................................................................................................38
C if statement ...........................................................................................................................................................................52
do...while loop...........................................................................................................................................................................61
Example: switch Statement// Program to create a simple calculator// Performs addition, subtraction, multiplication or division
depending the input from user ...................................................................................................................................................... 69
User-defined functions.................................................................................................................................................................. 74
Example #1: Two Dimensional Array to store and display values ............................................................................................... 95
Example #2: Sum of two matrices using Two dimensional arrays ............................................................................................... 97
Example: Program to find the sum of six numbers with arrays and pointers ............................................................................. 104
C malloc() ...............................................................................................................................................................................107
C free() ...................................................................................................................................................................................108
C realloc() ...............................................................................................................................................................................110
1. Referencing pointer to another address to access the memory_Consider an example to access structure's member through
pointer. ........................................................................................................................................................................................ 116
2. Accessing structure member through pointer using dynamic memory allocation .................................................................. 117
Types of Files..........................................................................................................................................................................125
Stacks .....................................................................................................................................................................................170
A program is a set of instructions that tell the computer to do various things; sometimes the instruction it has
to perform depends on what happened when it performed a previous instruction. This section gives an
overview of the two main ways in which you can give these instructions, or “commands” as they are usually
called. One way uses an interpreter, the other a compiler. As human languages are too difficult for a
computer to understand in an unambiguous way, commands are usually written in one or other languages
specially designed for the purpose.
Interpreters
With an interpreter, the language comes as an environment, where you type in commands at a prompt and
the environment executes them for you. For more complicated programs, you can type the commands into a
file and get the interpreter to load the file and execute the commands in it. If anything goes wrong, many
interpreters will drop you into a debugger to help you track down the problem.
The advantage of this is that you can see the results of your commands immediately, and mistakes can be
corrected readily. The biggest disadvantage comes when you want to share your programs with someone.
They must have the same interpreter, or you must have some way of giving it to them, and they need to
understand how to use it. Also users may not appreciate being thrown into a debugger if they press the
wrong key! From a performance point of view, interpreters can use up a lot of memory, and generally do not
generate code as efficiently as compilers.
In my opinion, interpreted languages are the best way to start if you have not done any programming before.
This kind of environment is typically found with languages like Lisp, Smalltalk, Perl and Basic. It could also
be argued that the UNIX® shell (sh, csh) is itself an interpreter, and many people do in fact write shell
“scripts” to help with various “housekeeping” tasks on their machine. Indeed, part of the original UNIX®
philosophy was to provide lots of small utility programs that could be linked together in shell scripts to
perform useful tasks.
Here is a list of interpreters that are available from the FreeBSD Ports Collection, with a brief discussion of
some of the more popular interpreted languages.
Instructions on how to get and install applications from the Ports Collection can be found in the Ports section
of the handbook.
BASIC
Short for Beginner's All-purpose Symbolic Instruction Code. Developed in the 1950s for teaching
University students to program and provided with every self-respecting personal computer in the 1980s,
BASIC has been the first programming language for many programmers. It is also the foundation for Visual
Basic. The Bywater Basic Interpreter can be found in the Ports Collection as lang/bwbasic and the Phil
Cockroft's Basic Interpreter (formerly Rabbit Basic) is available as lang/pbasic.
Lisp
Lisp is an extremely powerful and sophisticated language, but can be rather large and unwieldy.
Various implementations of Lisp that can run on UNIX® systems are available in the Ports Collection
for FreeBSD. GNU Common Lisp can be found as lang/gcl. CLISP by Bruno Haible and Michael Stoll is
available as lang/clisp. For CMUCL, which includes a highly-optimizing compiler too, or simpler Lisp
implementations like SLisp, which implements most of the Common Lisp constructs in a few hundred lines
of C code, lang/cmucl and lang/slisp are available respectively.
Perl
Very popular with system administrators for writing scripts; also often used on World Wide Web
servers for writing CGI scripts.
Perl is available in the Ports Collection as lang/perl5.16 for all FreeBSD releases.
Scheme
A dialect of Lisp that is rather more compact and cleaner than Common Lisp. Popular in Universities as
it is simple enough to teach to undergraduates as a first language, while it has a high enough level of
abstraction to be used in research work.
Scheme is available from the Ports Collection as lang/elk for the Elk Scheme Interpreter. The MIT
Scheme Interpreter can be found in lang/mit-scheme and the SCM Scheme Interpreter in lang/scm.
Icon
Icon is a high-level language with extensive facilities for processing strings and structures. The version
of Icon for FreeBSD can be found in the Ports Collection as lang/icon.
Logo
Logo is a language that is easy to learn, and has been used as an introductory programming language in
various courses. It is an excellent tool to work with when teaching programming to smaller age groups, as it
makes creation of elaborate geometric shapes an easy task.
The latest version of Logo for FreeBSD is available from the Ports Collection in lang/logo.
Python
Python is an Object-Oriented, interpreted language. Its advocates argue that it is one of the best
languages to start programming with, since it is relatively easy to start with, but is not limited in comparison
to other popular interpreted languages that are used for the development of large, complex applications (Perl
and Tcl are two other languages that are popular for such tasks).
The latest version of Python is available from the Ports Collection in lang/python.
Ruby
Narsimha Reddy Engineering College NRCM
Ruby is an interpreter, pure object-oriented programming language. It has become widely popular
because of its easy to understand syntax, flexibility when writing code, and the ability to easily develop and
maintain large, complex programs.
Tcl and Tk
Tcl is an embeddable, interpreted language, that has become widely used and became popular mostly
because of its portability to many platforms. It can be used both for quickly writing small, prototype
applications, or (when combined with Tk, a GUI toolkit) fully-fledged, featureful programs.
Various versions of Tcl are available as ports for FreeBSD. The latest version, Tcl 8.5, can be found in
lang/tcl85.
Compilers
Compilers are rather different. First of all, you write your code in a file (or files) using an editor. You then
run the compiler and see if it accepts your program. If it did not compile, grit your teeth and go back to the
editor; if it did compile and gave you a program, you can run it either at a shell command prompt or in a
debugger to see if it works properly. [1]
Obviously, this is not quite as direct as using an interpreter. However it allows you to do a lot of things
which are very difficult or even impossible with an interpreter, such as writing code which interacts closely
with the operating system—or even writing your own operating system! It is also useful if you need to write
very efficient code, as the compiler can take its time and optimize the code, which would not be acceptable
in an interpreter. Moreover, distributing a program written for a compiler is usually more straightforward
than one written for an interpreter—you can just give them a copy of the executable, assuming they have the
same operating system as you.
As the edit-compile-run-debug cycle is rather tedious when using separate programs, many commercial
compiler makers have produced Integrated Development Environments (IDEs for short). FreeBSD does not
include an IDE in the base system, but devel/kdevelop is available in the Ports Collection and many use
Emacs for this purpose. Using Emacs as an IDE is discussed in Section 2.7, “Using Emacs as a
Development Environment”.
Software:
Organized information in the form of operating systems, utilities, programs, and applications that enable
computers to work.
Software consists of carefully-organized instructions and code written by programmers in any of various
special computer languages. Software is divided commonly into two main categories:
(1) System software: controls the basic (and invisible to the user) functions of a computer and comes
usually preinstalled with the machine. See also BIOS and Operating System.
(2) Application software: handles multitudes of common and specialized tasks a user wants to perform,
such as accounting, communicating, data processing, word processing.
Narsimha Reddy Engineering College NRCM
Compiler: Translating from source code to machine code executing directly.
Coded language used by programmers to write instructions that a computer can understand to do what the
programmer (or the computer user) wants.
The first programming language for a computer was Plankalkül, developed by Konrad Zuse for the Z3
between 1943 and 1945. However, it was not implemented until 1998.
Short Code, which was proposed by John Mauchly in 1949, is considered to be the first high-level
programming language.
However, because it had to be translated into machine code before it could be executed, it had relatively
slow processing speeds.
Learn C Programming
✓ Before getting started with C programming, lets get familiarized with the language first.
✓ C is a general-purpose programming language used for wide range of applications from Operating
systems like Windows and iOS to software that is used for creating 3D movies.
✓ C programming is highly efficient. That’s the main reason why it’s very popular despite being more
than 40 years old.
✓ Standard C programs are portable. The source code written in one system works in another operating
system without any change.
✓ As mentioned, it’s a good language to start learning programming. If you know C programming, you
will not just understand how your program works, but will also be able to create a mental picture on
how a computer works.
History of C programming
The PDP-11 version of Unix system was written in assembly language. Assembly languages are low-level
programming languages that are specific to a particular computer architecture. They are hard to write and
understand.
The developers of Unix Operating system (including Dennis Ritchie and Stephen C. Johnson) decided to
rewrite the system in B language. However, B couldn’t suffice some of the features of PDP-11, which led to
the development of C.
In 1972, the development of C started on the PDP-11 Unix system. A large part of Unix was then rewritten
in C. By 1973, C was powerful enough to be used in Unix Kernel. Dennis Ritchie and Stephen C. Johnson
made further changes to the language for several years to make it portable in Unix Operating system.
In 1978, the first book of C programming, The C Programming Language, was published. The first edition
of the book provided programmers informal specification of the language. Written by Brian Kernighan and
Dennis Ritchie, this book is popular among C programmers as "K&R".
ANSI C
With the rapid growth of C language for several years, it was time for language to get it standardized.
C89. The first standard of C was published by American National Standards Institute (ANSI) in 1989. This
version is commonly popular as C89.
C11. The C11 standard has new features like type generic macros, atomic operations, anonymous structures
that doesn’t exist in C99.
All these three standards are also known by the name of ANSI C.
“Standard C programs are portable”. This means, the programs that follow ANSI C standard are portable
among operating systems.
If you are new to programming, it’s advisable to follow the standard (ANSI C in case of C programming)
that is accepted everywhere. It will help you learn the language the way it was intended.
If only it were possible to answer this question with a simple “yes” or “no”. Unfortunately, it’s not an
easy question to answer and varies from person to person.
Personally speaking, I love C programming. It is a good language to start your programming journey if you
are a newbie. Even if you are an experienced programmer, I recommend you to learn it at some point; it will
certainly help.
If you don’t know C, you don’t know what you are doing as a programmer. Sure, your application works
fine and all. But, if you can’t say why while (*s++ = *p++); copies a string, you’re programming on a
superstition. ( Joel Spolsky’s words, not mine ).
If you know C, you will not only know how your program works but, you will be able to create a
mental model on how a computer works (including memory management and allocation). You will learn to
appreciate the freedom that C provides unlike Python and Java.
Understanding C allows you to write programs that you never thought were possible before (or at the
very least, you will have a broader understanding of computer architecture and programming as a whole).
Almost all high-level programming languages like Java, Python, JavaScript etc. can interface with C
programming. Also, it’s a good language to express common ideas in programming. Doesn’t matter if the
person you are talking with doesn’t know C, you can still convey your idea in a way they can understand.
At first, you may overlook the fact that C is an important language. If you need to develop a mobile app,
you need Java (for Android), Swift and Objective C (for iOS). And there are dozens of languages like C#,
PHP, ASP.net, Ruby, Python for building web application. Then, where is C programming?
Some of the larger open source projects where C programming is used are Linux Kernel, Python
Interpreter, SQLite Database.
Another language that’s commonly used for large open source project is C++. If you know C and C++,
you can contribute to large open source projects that impacts hundreds of millions of people.
To be honest, this statement may not be true all the time. However, knowing how computer works and
manage memory gives you insight on how to write efficient code in other programming languages.
A lot of popular programming languages are based on C (and C++, considered superset of C
programming with OOP features). If you know C, you will get a head start learning C++.
Languages like C# and Java are related to C and C++. Also, the syntax of JavaScript and PHP is similar
to C.
If you know C and C++ programming, you will not have any problem switching to another language.
You can create awesome softwares without knowing C programming at all. Jeff Atwood, one of the creators
of Stackoverflow.com, apparently doesn’t know C and Stack Overflow is a really good web application.
If you are busy and don’t want to invest time on something that doesn’t have direct effect on your
day-to-day work, C programming is not for you.
Also, if you are a newbie and want to start learning programming with an easier language (C is not the
easiest of language to learn), you can start with Python.
For newbie:
For many, C programming is the best language to start learning programming. However, if you want to start
with an easier language which is clean and easier to grasp, go for Python.
It’s not absolutely essential but there are perks of learning C programming.
Don’t leave your current project immediately (I know you won’t) to learn C. You can learn it when you have
free time and want to expand your programming skills.
I believe, it’s not necessary to learn C immediately. However, you should learn C eventually.
There are numerous compilers and text editors you can use to run C programming. These compilers and text
editors may differ from system to system.You will find the easiest way to run C programming on your
computer (Windows, Mac OS X or Linux) in this section.
To run C Programming in Windows, download a software called Code::Blocks. Then, write C code, save the
file with .c extension and execute the code.
To make this procedure even easier, follow this step by step guide.
Under Windows XP / Vista / 7 / 8.x / 10 section, click the link with mingw-setup (highlighted row)
either from Sourceforge.net or FossHub.
Open the Code::Blocks Setup file and follow the instructions (Next > I agree > Next > Install); you
don’t need to change anything. This installs the Code::Blocks with gnu gcc compiler, which is the best
compiler to start with for beginners.
Now, open Code::Blocks and go to File > New > Empty file (Shortcut: Ctrl + Shift + N)
Write the C code and save the file with .c extension. To save the file, go to File > Save (Shortcut: Ctrl + S).
Important: The filename should end with a .c extension, like: hello.c, your-program-name.c
To run the program, go to Build > Build and Run (Shortcut: F9). This will build the executable file and
run it.
If your program doesn’t run and if you see error message "can't find compiler executable in your search
path(GNU GCC compiler)", go to Settings > Compiler > Toolchain executables and click Auto-detect. This
should solve the issue in most cases.
“Hello, World!” is a simple program that displays “Hello, World!” on the screen. Since, it’s a very simple
program, it is used to illustrate the basic syntax of any programming language.
This program is often used to introduce programming language to a beginner. So, let’s get started.
#include <stdio.h>
printf("Hello, World!\n");
return 0;
C programming is small and cannot do much by itself. You need to use libraries that are necessary to run the
program. The stdio.h is a header file and C compiler knows the location of that file. To use the file, you need
to include it in your program using #include preprocessor.
In this program, we have used printf() function which displays the text inside the quotation mark. Since
printf() is defined in stdio.h, you need to include stdio.h.
In C programming, the code execution begins from the start of main() function (doesn’t matter if main()
isn’t located at the beginning).
The code inside the curly braces { } is the body of main() function. The main() function is mandatory in
every C program.
int main() {
}
The printf() is a library function that sends formatted output to the screen (displays the string inside the
quotation mark). Notice the semicolon at the end of the statement.
Remember, you need to include stdio.h file in your program for this to work.
The return statement return 0; inside the main() function ends the program. This statement isn’t mandatory.
However, it’s considered good programming practice to use it.
Key notes to take away
✓ All C program starts from the main() function and it’s mandatory.
✓ You can use the required header file that’s necessary in the program.
✓ For example: To use sqrt() function to calculate square root and pow() function to find power of a
number, you need to include math.h header file in your program.
✓ C is case-sensitive; the use of uppercase letter and lowercase letter have different meanings.
✓ The C program ends when the program encounters the return statement inside the main() function.
However, return statement inside the main function is not mandatory.
✓ The statement in a C program ends with a semicolon.
✓ Good programming practice are the informal rules which can improve quality and decrease
development time of the software.
✓ Some of the programming practices mentioned here are valid in all programming languages whereas
some are valid only for C programming.
✓ The number of spaces you use in the program doesn’t matter in C. However, that doesn’t mean you
should use different number of spaces at different places. Also, use proper indentation so that the code is
easier to understand.
int count;
float squareRoot = 10.0;
printf(“Square root = %f”, squareRoot);
int count;
float squareRoot = 10.0;
printf(“Square root = %f”, squareRoot);
The goal here is to write code that your fellow programmers can understand.
int a, b;
Here, a and b are two variables and I have no idea what they do. Instead you can choose name like:
Both conventions: using _ to separate words and using capital letter after first word is popular. However,
don’t use both in one program; choose one and be consistent with it.
You can use comments in your program to explain what you are trying to achieve in your program. This
helps your fellow programmer to understand the code.
// My first C program
#include <stdio.h>
int main()
return 0;
“Commenting your code is like cleaning your bathroom - you never want to do it, but it really does
create a more pleasant experience for you and your guests.”
— Ryan Campbell
Reserved words in C programming that are part of the syntax. Also, you will learn about identifiers and
proper way to name a variable.
Character set
Narsimha Reddy Engineering College NRCM
Character set is a set of alphabets, letters and some special characters that are valid in C language.
Alphabets
Uppercase: A B C ................................... X Y Z
Lowercase: a b c ...................................... x y z
Digits
0123456789
Special Characters
( ) ; $ :
% [ ] # ?
^ ! * / |
- \ ~ +
blank space, new line, horizontal tab, carriage return and form feed
C Keywords
Keywords are predefined, reserved words used in programming that have special meanings to the compiler.
Keywords are part of the syntax and they cannot be used as an identifier. For example:
int money;
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all keywords
allowed in ANSI C.
Keywords in C Language
do if static while
Along with these keywords, C supports other numerous keywords depending upon the compiler..
C Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc.
Identifier must be unique. They are created to give unique name to a entity to identify it during the execution
of the program. For example:
int money;
double accountBalance;
Also remember, identifier names must be different from keywords. You cannot use int as an identifier
because int is a keyword.
1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
2. The first letter of an identifier should be either a letter or an underscore. However, it is discouraged
to start an identifier name with an underscore.
3. There is no rule on length of an identifier. However, the first 31 characters of identifiers
are discriminated by the compiler.
Variables
Here, playerScore is a variable of integer type. The variable is assigned value: 95.
In C programming, you have to declare a variable before you can use it.
1. A variable name can have letters (both uppercase and lowercase letters), digits and underscore only.
2. The first letter of a variable should be either a letter or an underscore. However, it is discouraged to
start variable name with an underscore. It is because variable name that starts with an underscore can
conflict with system name and may cause error.
3. There is no rule on how long a variable can be. However, only the first 31 characters of a variable are
checked by the compiler. So, the first 31 letters of two variables in a program should be different.
C is a strongly typed language. What this means it that, the type of a variable cannot be changed.
Constants/Literals: A constant is a value or an identifier whose value cannot be altered in a program. For
example: 1, 2.5, "C programming is easy", etc.
Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.
1. Integer constants
An integer constant is a numeric constant (associated with number) without any fractional or exponential
part. There are three types of integer constants in C programming:
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.
Narsimha Reddy Engineering College NRCM
2. Floating-point constants
A floating point constant is a numeric constant that has either a fractional form or an exponent form. For
example:
-2.0
0.0000234
-0.22E-5
3. Character constants
A character constant is a constant which uses single quotation around characters. For example: 'a', 'l', 'm', 'F'
4. Escape Sequences
Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C
programming. For example: newline(enter), tab, question mark etc. In order to use these characters, escape
sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way the characters
are interpreted by the compiler.
Escape Sequences
Escape Sequences Character
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
\0 Null character
5. String constants
String constants are the constants which are enclosed in a pair of double-quote marks. For example:
6. Enumeration constants
Here, color is a variable and yellow, green, black and white are the enumeration constants having value 0, 1,
2 and 3 respectively.
In C programming, variables or memory locations should be declared before it can be used. Similarly, a
function also needs to be declared before use.
Data types simply refers to the type and size of data associated with variables and functions.
Data types in C
✓ Integer types
✓ Floating type
✓ Character type
✓ Arrays
✓ Pointers
✓ Enumeration
Integers are whole numbers that can have both positive and negative values but no decimal values. Example:
0, -5, 10
In C programming, keyword int is used for declaring integer variable. For example:
int id;
The size of int is either 2 bytes(In older PC's) or 4 bytes. If you consider an integer having size of 4
byte( equal to 32 bits), it can take 232 distinct states as: -231,-231+1, ...,-2, -1, 0, 1, 2, ..., 231-2, 231-1
Similarly, int of 2 bytes, it can take 216 distinct states from -215 to 215-1. If you try to store larger number
than 231-1, i.e,+2147483647 and smaller number than -231, i.e, -2147483648, program will not run
correctly.
Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc. You can declare a floating point
variable in C by using either float or double keyword. For example:
float accountBalance;
double bookPrice;
The size of float (single precision float data type) is 4 bytes. And the size of double (double precision float
data type) is 8 bytes. Floating point variables has a precision of 6 digits whereas the precision of double is
14 digits.
Keyword char is used for declaring character type variables. For example:
C Qualifiers
Qualifiers alters the meaning of base data types to yield a new data type.
Size qualifiers
Size qualifiers alters the size of a basic type. There are two size qualifiers, long and short. For example:
long double i;
The size of double is 8 bytes. However, when long keyword is used, that variable becomes 10 bytes.
There is another keyword short which can be used if you previously know the value of a variable will
always be a small number.
Sign qualifiers
Integers and floating point variables can hold both negative and positive values. However, if a variable
needs to hold positive value only, unsigned data types are used. For example:
There is another qualifier signed which can hold both negative and positive only. However, it is not
necessary to define variable signed since a variable is signed by default.
An integer variable of 4 bytes can hold data from -231 to 231-1. However, if the variable is defined as
unsigned, it can hold data from 0 to 232-1.
It is important to note that, sign qualifiers can be applied to int and char types only.
Constant qualifiers
A variable should be declared volatile whenever its value can be changed by some external sources outside
the program. Keyword volatile is used for creating volatile variables.
C programming has several in-built library functions to perform input and output tasks.
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scanf() function reads formatted input from standard input (keyboard) whereas the printf() function
sends formatted output to the standard output (screen).
Output:C Programming
How this program works?
• All valid C program must contain the main() function. The code execution begins from the start of
main() function.
• The printf() is a library function to send formatted output to the screen. The printf() function is
declared in "stdio.h" header file.
• Here, stdio.h is a header file (standard input output header file) and #include is a preprocessor
directive to paste the code from the header file when necessary. When the compiler encounters
printf() function and doesn't find stdio.h header file, compiler shows error.
• The return 0; statement is the "Exit status" of the program. In simple terms, program ends.
Example #2: C Integer Output
#include <stdio.h>int main(){
int testInteger = 5;
printf("Number = %d", testInteger);
return 0;}
Output
Number = 5
Inside the quotation of printf() function, there is a format string "%d" (for integer). If the format string
matches the argument (testInteger in this case), it is displayed on the screen.
Output
Enter an integer: 4
Narsimha Reddy Engineering College NRCM
Number = 4
The scanf() function reads formatted input from the keyboard. When user enters an integer, it is stored in
variable testInteger.
Note the '&' sign before testInteger; &testInteger gets the address of testInteger and the value is stored in
that address.
Output
Enter a number: 23.45
Value = 23.450000
The format string "%f" is used to read and display formatted in case of floats.
Output
Enter a character: g
You entered g.
When a character is entered in the above program, the character itself is not stored. Instead, a numeric
value(ASCII value) is stored.
And when we displayed that value using "%c" text format, the entered character is displayed.
Output
Enter a character: g
You entered g.
ASCII value of g is 103.
The ASCII value of character 'g' is 103. When, 'g' is entered, 103 is stored in variable var1 instead of g.
You can display a character if you know ASCII code of that character. This is shown by following example.
Output
Character having ASCII value 69 is E.
// Tries to print number right justified to 3 digits but the number is not right adjusted because there are
only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);
Output
4 digit integer right justified to 6 column: 9876
4 digit integer right justified to 3 column: 9876
Floating point number rounded to 2 digits: 987.65
Floating point number rounded to 0 digits: 988
Floating point number in exponential form: 9.876543e+02
C programming has several in-built library functions to perform input and output tasks.
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
The scanf() function reads formatted input from standard input (keyboard) whereas the printf() function
sends formatted output to the standard output (screen).
Output
C Programming
• All valid C program must contain the main() function. The code execution begins from the start of
main() function.
• The printf() is a library function to send formatted output to the screen. The printf() function is
declared in "stdio.h" header file.
• Here, stdio.h is a header file (standard input output header file) and #include is a preprocessor
directive to paste the code from the header file when necessary. When the compiler encounters
printf() function and doesn't find stdio.h header file, compiler shows error.
• The return 0; statement is the "Exit status" of the program. In simple terms, program ends.
Output
Number = 5
Inside the quotation of printf() function, there is a format string "%d" (for integer). If the format string
matches the argument (testInteger in this case), it is displayed on the screen.
Output
Enter an integer: 4
Number = 4
The scanf() function reads formatted input from the keyboard. When user enters an integer, it is stored in
variable testInteger.
Note the '&' sign before testInteger; &testInteger gets the address of testInteger and the value is stored in
that address.
Output
Enter a number: 23.45
Value = 23.450000
The format string "%f" is used to read and display formatted in case of floats.
Output
Enter a character: g
You entered g.
When a character is entered in the above program, the character itself is not stored. Instead, a numeric
value(ASCII value) is stored.
And when we displayed that value using "%c" text format, the entered character is displayed.
You can display a character if you know ASCII code of that character. This is shown by following example.
Output
Narsimha Reddy Engineering College NRCM
Character having ASCII value 69 is E.
// Tries to print number right justified to 3 digits but the number is not right adjusted because there are
only 4 numbers
printf("4 digit integer right justified to 3 column: %3d\n", integer);
Output
4 digit integer right justified to 6 column: 9876
4 digit integer right justified to 3 column: 9876
Floating point number rounded to 2 digits: 987.65
Floating point number rounded to 0 digits: 988
Floating point number in exponential form: 9.876543e+02
The #include preprocessor is used to include header files to a C program. For example,
#include <stdio.h>
Here, "stdio.h" is a header file. The #include preprocessor directive replaces the above line with the contents
of stdio.h header file which contains function and macro definitions.
That's the reason why you need to use #include <stdio.h> before you can use functions like scanf() and
printf().
You can also create your own header file containing function declaration and include it in your program
using this preprocessor directive.
#include "my_header.h"
A macro is a fragment of code that is given a name. You can use that fragment of code in your program by
using the name. For example,
int main(){
scanf("%d", &radius);
area = PI*radius*radius;
printf("Area=%.2f",area);
return 0;}
You can also define macros that works like a function call, known as function-like macros. For example,
int main()
int radius;
float area;
scanf("%d", &radius);
area = circleArea(radius);
return 0;
Narsimha Reddy Engineering College NRCM
}
Conditional Compilation
In C programming, you can instruct preprocessor whether to include certain chuck of code or not. To do so,
conditional directives can be used.
It's similar like a if statement. However, there is a big difference you need to understand.
The if statement is tested during the execution time to check whether a block of code should be executed or
not whereas, the conditionals is used to include (or skip) certain chucks of code in your program before
execution.
Uses of Conditional
To use conditional, #ifdef, #if, #defined, #else and #elseif directives are used.
#ifdef Directive
#ifdef MACRO
conditional codes
#endif
Here, the conditional codes are included in the program only if MACRO is defined.
#if expression
conditional codes
#endif
#if expression
#else
conditional if expression is 0
#endif
You can also add nested conditional to your #if...#else using #elif
#if expression
#elif expression1
#elif expression2
... .. ...
else
#endif
#defined
The special operator #defined is used to test whether certain macro is defined or not. It's often used with #if
directive.
conditional codes
Predefined Macros
There are some predefined macros which are readily for use in C programming.
Output
In this article, you'll learn about the standard library functions in C. More specifically, what are they,
different library functions in C and how to use them in your program.
C Standard library functions or simply C Library functions are inbuilt functions in C programming.
The prototype and data definitions of the functions are present in their respective header files, and must be
included in your program to access them.
For example: If you want to use printf() function, the header file <stdio.h> should be included.
There are many library functions available in C programming to help you write a good and efficient program.
But, why should you use it?
Below are the 4 most important advantages of using standary library functions.
1. They work
One of the most important reasons you should use library functions is simply because they work.
These functions have gone through multiple rigorous testing and are easy to use.
Since, the functions are "standard library" functions, a dedicated group of developers constantly make them
better.
In the process, they are able to create the most efficient code optimized for maximum performance.
Since the general functions like printing to a screen, calculating the square root, and many more are already
written. You shouldn't worry about creating them once again.
It saves valuable time and your code may not always be the most efficient.
With ever changing real world needs, your application is expected to work every time, everywhere.
And, these library functions help you in that they do the same thing on every computer.
However, in C programming you can find the square root by just using sqrt() function which is defined
under header file "math.h"
printf("Enter a number: );
root = sqrt(num);
return 0;}
Enter a number: 12
C Header Files
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction and multiplication on
numerical values (constants and variables).
* multiplication
/ division
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
printf("a/b = %d \n",c);
c=a%b;
return 0;}
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
The operators +, - and * computes addition, subtraction and multiplication respectively as you might have
expected.
It is because both variables a and b are integers. Hence, the output is also an integer. The compiler neglects
the term after decimal point and shows answer 2 instead of 2.25.
The modulo operator % computes the remainder. When a = 9 is divided by b = 4, the remainder is 1. The %
operator can only be used with integers.
C programming has two operators increment ++ and decrement -- to change the value of an operand
(constant or variable) by 1.
Narsimha Reddy Engineering College NRCM
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators
are unary operators, meaning they only operate on a single operand.
return 0;}
Output
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
Here, the operators ++ and -- are used as prefix. These two operators can also be used as postfix like a++
and a--. Visit this page to learn more on how increment and decrement operators work when used as postfix.
C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common assignment operator is
=
Narsimha Reddy Engineering College NRCM
Exampl
Operator Same as
e
= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
int a = 5, c;
c = a;
c += a; // c = c+a
c -= a; // c = c-a
c *= a; // c = c*a
c /= a; // c = c/a
return 0;}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
C Relational Operators
A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the
relation is false, it returns value 0.
Relational operators are used in decision making and loops.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0
Example #4: Relational Operators
// C Program to demonstrate the working of arithmetic operators#include <stdio.h>int main(){
int a = 5, b = 5, c = 10;
printf("%d == %d = %d \n", a, b, a == b); // true
printf("%d == %d = %d \n", a, c, a == c); // false
printf("%d > %d = %d \n", a, b, a > b); //false
printf("%d > %d = %d \n", a, c, a > c); //false
Narsimha Reddy Engineering College NRCM
printf("%d < %d = %d \n", a, b, a < b); //false
printf("%d < %d = %d \n", a, c, a < c); //true
printf("%d != %d = %d \n", a, b, a != b); //false
printf("%d != %d = %d \n", a, c, a != c); //true
printf("%d >= %d = %d \n", a, b, a >= b); //true
printf("%d >= %d = %d \n", a, c, a >= c); //false
printf("%d <= %d = %d \n", a, b, a <= b); //true
printf("%d <= %d = %d \n", a, c, a <= c); //true
return 0;}
Output
5 == 5 = 1
5 == 10 = 0
5>5=0
5 > 10 = 0
5<5=0
5 < 10 = 1
5 != 5 = 0
5 != 10 = 1
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1
C Logical Operators
An expression containing logical operator returns either 0 or 1 depending upon whether expression results
true or false. Logical operators are commonly used in decision making in C programming.
return 0;}
Output
(a = b) || (c < b) equals to 1
!(a != b) equals to 1
!(a == b) equals to 0
Bitwise Operators
During computation, mathematical operations like: addition, subtraction, addition and division are converted
to bit-level which makes processing faster and saves power.
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof is an unary operator which returns the size of data (constant, variables, array, structure etc).
int a, e[10];
float b;
double c;
char d;
return 0;}
Output
• The first expression conditionalExpression is evaluated at first. This expression evaluates to 1 if it's
and evaluates to 0 if it's false.
char February;
int days;
printf("If this year is leap year, enter 1. If not enter any integer: ");
scanf("%c",&February);
return 0;}
Output
Other operators such as & (reference operator), * (dereference operator) and -> (member selection) operator
will be discussed in C pointers.
Decision making is used to specify the order in which statements are executed. In this tutorial, you will learn
to create decisions using different forms of if...else statement.
C if statement
if (testExpression)
{
// statements
}
If test expression is evaluated to true (nonzero), statements inside the body of if is executed.
To learn more on when test expression is evaluated to nonzero (true) and 0 (false), check out relational and
logical operators.
Flowchart of if statement
// Program to display a number if user enters negative number// If user enters positive number, that number
won't be displayed
int number;
scanf("%d", &number);
if (number < 0)
return 0;}
Narsimha Reddy Engineering College NRCM
Output 1
Enter an integer: -2
When user enters -2, the test expression (number < 0) becomes true. Hence, You entered -2 is displayed on
the screen.
Output 2
Enter an integer: 5
When user enters 5, the test expression (number < 0) becomes false and the statement inside the body of if is
skipped.
C if...else statement
The if...else statement executes some code if the test expression is true (nonzero) and some other code if the
test expression is false (0).
Syntax of if...else
if (testExpression) {
else {
If test expression is true, codes inside the body of if statement is executed and, codes inside the body of else
statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes inside the body of if
statement is skipped.
int number;
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
else
return 0;
Output
Enter an integer: 7
7 is an odd integer.
The if...else statement executes two different codes depending upon whether the test expression is true or
false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute different codes
for more than two conditions.
if (testExpression1)
else if(testExpression2)
else if (testExpression 3)
else
}
Example #3: C Nested if...else statement
// Program to relate two integers using =, > or <
if(number1 == number2)
printf("Result: %d = %d",number1,number2);
else
return 0;}
Result: 12 < 23
Loops are used in programming to repeat a specific block of code. After reading this tutorial, you will learn
to create a for loop in C programming.
Loops are used in programming to repeat a specific block until some end condition is met. There are three
loops in C programming:
1. for loop
2. while loop
3. do...while loop
// codes
Then, the test expression is evaluated. If the test expression is false (0), for loop is terminated. But if the test
expression is true (nonzero), codes inside the body of for loop is executed and the update expression is
updated.
The for loop is commonly used when the number of iterations is known.
// Program to calculate the sum of first n natural numbers// Positive integers 1,2,3...n are known as natural
numbers
scanf("%d", &num);
sum += count;
return 0;}
Output
Sum = 55
The value entered by the user is stored in variable num. Suppose, the user entered 10.
The count is initialized to 1 and the test expression is evaluated. Since, the test expression count <= num (1
less than or equal to 10) is true, the body of for loop is executed and the value of sum will equal to 1.
Then, the update statement ++count is executed and count will equal to 2. Again, the test expression is
evaluated. Since, 2 is also less than 10, the test expression is evaluated to true and the body of for loop is
executed. Now, the sum will equal 3.
This process goes on and the sum is calculated until the count reaches 11.
When the count is 11, the test expression is evaluated to 0 (false) as 11 is not less than or equal to 10.
Therefore, the loop terminates and next, the total sum is printed.
Loops are used in programming to repeat a specific block until some end condition is met. There are three
loops in C programming:
1. for loop
2. while loop
3. do...while loop
while loop
while (testExpression)
//codes
where, testExpression checks the condition is true or false before each loop.
If the test expression is true (nonzero), codes inside the body of while loop is evaluated. The test expression
is evaluated again. The process goes on until the test expression is false.
#include <stdio.h>
int main()
{
Narsimha Reddy Engineering College NRCM
int number;
scanf("%d",&number);
factorial = 1;
--number;
return 0;
Output
Enter an integer: 5
Factorial = 120.
do...while loop
The do..while loop is similar to the while loop with one important difference. The body of do...while loop is
executed once, before checking the test expression. Hence, the do...while loop is executed at least once.
do
// codes
}
Narsimha Reddy Engineering College NRCM
while (testExpression);
The code block (loop body) inside the braces is executed once.
Then, the test expression is evaluated. If the test expression is true, the loop body is executed again. This
process goes on until the test expression is evaluated to 0 (false).
When the test expression is false (nonzero), the do...while loop is terminated.
#include <stdio.h>
int main()
do
scanf("%lf", &number);
sum += number;
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
Output
Narsimha Reddy Engineering College NRCM
Enter a number: 1.5
Enter a number: 0
Sum = 4.70
It is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without
checking the test expression.
break Statement
The break statement terminates the loop (for, while and do...while loop) immediately when it is encountered.
The break statement is used with decision making statement such as if...else.
break;
// Program to calculate the sum of maximum of 10 numbers// Calculates sum until user enters positive
number
int i;
scanf("%lf",&number);
break;
printf("Sum = %.2lf",sum);
return 0;}
Output
Enter a n4: -3
Sum = 10.30
This program calculates the sum of maximum of 10 numbers. It's because, when the user enters negative
number, the break statement is executed and loop is terminated.
continue Statement
The continue statement skips some statements inside the loop. The continue statement is used with decision
making statement such as if...else.
continue;
int i;
scanf("%lf",&number);
continue;
printf("Sum = %.2lf",sum);
return 0;}
Output
Enter a n10: 12
Sum = 59.70
In the program, when the user enters positive number, the sum is calculated using sum += number;
statement.
When the user enters negative number, the continue statement is executed and skips the negative number
from calculation.
C switch...case Statement
The if..else..if ladder allows you to execute a block code among many alternatives. If you are checking on
the value of a single variable in if...else...if, it is better to use switch statement.
The switch statement is often faster than nested if...else (not always). Also, the syntax of switch statement is
cleaner and easy to understand.
Syntax of switch...case
switch (n)
case constant1:
break;
case constant2:
break;
default:
When a case constant is found that matches the switch expression, control of the program passes to the block
of code associated with that case.
In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute the block
of code associate with the case statement until the end of switch block, or until the break statement is
encountered.
The break statement is used to prevent the code running into the next case.
Example: switch Statement// Program to create a simple calculator// Performs addition, subtraction,
multiplication or division depending the input from user
# include <stdio.h>
int main() {
char operator;
double firstNumber,secondNumber;
scanf("%c", &operator);
switch(operator)
break;
case '-':
break;
case '*':
break;
case '/':
break;
default:
return 0;}
Output
12.4
If break statement is not used, all cases after the correct case is executed.
C goto Statement
goto label;
... .. ...
... .. ...
... .. ...
label:
statement;
The label is an identifier. When goto statement is encountered, control of the program jumps to label: and
starts executing the code.
// Program to calculate the sum and average of maximum of 5 numbers// If user enters negative number, the
sum and average of previously entered positive number is displayed
# include <stdio.h>
int main(){
int i;
scanf("%lf",&number);
goto jump;
jump:
average=sum/(i-1);
return 0;}
Output
1. Enter a number: 3
Sum = 16.60
The use of goto statement may lead to code that is buggy and hard to follow. For example:
one:
test += i;
goto two;
two:
if (test > 5) {
goto three;
... .. ...Also, goto statement allows you to do bad stuff such as jump out of scope.
That being said, goto statement can be useful sometimes. For example: to break from nested loops.
C Programming Functions
Suppose, a program related to graphics needs to create a circle and color it depending upon the radius and
color from the user. You can create two functions to solve this problem:
Dividing complex problem into small components makes program easy to understand and use.
Depending on whether a function is defined by the user or already included in C compilers, there are two
types of functions in C programming
The standard library functions are built-in functions in C programming to handle tasks such as mathematical
computations, I/O processing, string handling etc.
These functions are defined in the header file. When you include the header file, these functions are
available for use. For example:
The printf() is a standard library function to send formatted output to the screen (display output on the
screen). This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such as scanf(), fprintf(), getchar() etc.
Once you include "stdio.h" in your program, all these functions are available for use.
User-defined functions
As mentioned earlier, C allow programmers to define functions. Such functions created by the user are
called user-defined functions.
Depending upon the complexity and requirement of the program, you can create as many user-defined
functions as you want.
#include <stdio.h>
void functionName()
... .. ...
... .. ...
int main()
... .. ...
... .. ...
functionName();
Narsimha Reddy Engineering College NRCM
... .. ...
... .. ...
When the compiler encounters functionName(); inside the main function, control of the program jumps to
void functionName()
And, the compiler starts executing the codes inside the user-defined function.
The control of the program jumps to statement next to functionName(); once all the codes inside the
function definition are executed.
This is just an overview on user-defined function. Visit these pages to learn more on:
C allows you to define functions according to your need. These functions are known as user-defined
functions. For example:
Suppose, you need to create a circle and color it depending upon the radius and color. You can create two
functions to solve this problem:
• createCircle() function
• color() function
Here is a example to add two integers. To perform this task, a user-defined function addNumbers() is
defined.
#include <stdio.h>
int main(){
int n1,n2,sum;
scanf("%d %d",&n1,&n2);
printf("sum = %d",sum);
return 0;}
int result;
result = a+b;
Function prototype
A function prototype is simply the declaration of a function that specifies function's name, parameters and
return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used in the program.
In the above example, int addNumbers(int a, int b); is the function prototype which provides following
information to the compiler:
The function prototype is not needed if the user-defined function is defined before the main() function.
Calling a function
In the above example, function call is made using addNumbers(n1,n2); statement inside the main().
Function definition
Function definition contains the block of code to perform a specific task i.e. in this case, adding two
numbers and returning it.
When a function is called, the control of the program is transferred to the function definition. And, the
compiler starts executing the codes inside the body of a function.
Narsimha Reddy Engineering College NRCM
Passing arguments to a function
In programming, argument refers to the variable passed to the function. In the above example, two variables
n1 and n2 are passed during function call.
The parameters a and b accepts the passed arguments in the function definition. These arguments are called
formal parameters of the function.
The type of arguments passed to a function and the formal parameters must match, otherwise the compiler
throws error.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float
type.A function can also be called without passing an argument.
Return Statement
The return statement terminates the execution of a function and returns a value to the calling function. The
program control is transferred to the calling function after return statement.
In the above example, the value of variable result is returned to the variable sum in the main() function.
return (expression);
For example,
return a;
return (a+b);
The type of value returned from the function and the return type specified in function prototype and function
definition must match.
For better understanding of arguments and return value from the function, user-defined functions can be
categorized as:
#include <stdio.h>
void checkPrimeNumber();
int main(){
return 0;}
// return type of the function is void becuase no value is returned from the functionvoid
checkPrimeNumber(){
int n, i, flag=0;
scanf("%d",&n);
if(n%i == 0)
flag = 1;
if (flag == 1)
else
The checkPrimeNumber() function takes input from the user, checks whether it is a prime number or not and
displays it on the screen.
The return type of the function is void. Hence, no value is returned from the function.
int main(){
int n, i, flag = 0;
n = getInteger();
if(n%i==0){
flag = 1;
break;
if (flag == 1)
else
return 0;}
Narsimha Reddy Engineering College NRCM
// getInteger() function returns integer entered by the userint getInteger(){
int n;
scanf("%d",&n);
return n;}
The empty parentheses in n = getInteger(); statement indicates that no argument is passed to the function.
And, the value returned from the function is assigned to n.
Here, the getInteger() function takes input from the user and returns it. The code to check whether a number
is prime or not is inside the main() function.
int main(){
int n;
scanf("%d",&n);
checkPrimeAndDisplay(n);
return 0;}
// void indicates that no value is returned from the functionvoid checkPrimeAndDisplay(int n){
int i, flag = 0;
if(n%i == 0){
Narsimha Reddy Engineering College NRCM
flag = 1;
break;
if(flag == 1)
else
Here, the checkPrimeAndDisplay() function checks whether the argument passed is a prime number or not
and displays the appropriate message.
int main(){
int n, flag;
scanf("%d",&n);
flag = checkPrimeNumber(n);
if(flag==1)
else
int i;
if(n%i == 0)
return 1;
return 0;}
The input from the user is passed to checkPrimeNumber() function.The checkPrimeNumber() function
checks whether the passed argument is prime or not. If the passed argument is a prime number, the function
returns 0. If the passed argument is a non-prime number, the function returns 1. The return value is assigned
to flag variable.
Well, it depends on the problem you are trying to solve. In case of this problem, the last approach is better.
A function should perform a specific task. The checkPrimeNumber() function doesn't take input from the
user nor it displays the appropriate message. It only checks whether a number is prime or not, which makes
code modular, easy to understand and debug.
C Programming Recursion
A function that calls itself is known as a recursive function. And, this technique is known as recursion.
void recurse()
... .. ...
recurse();
Narsimha Reddy Engineering College NRCM
... .. ...
int main()
... .. ...
recurse();
... .. ...
To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes
the recursive call and other doesn't.
int main(){
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);}
if (num!=0)
else
return num;}
Output
Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of num is 3 initially. During next function call, 2 is passed to the sum() function. This
process continues until num is equal to 0.
When num is equal to 0, the if condition fails and the else part is executed returning the sum of integers to
the main() function.
Recursion makes program elegant and cleaner. All algorithms can be defined recursively which makes it
easier to visualize and prove.聽
If the speed of the program is vital then, you should avoid using recursion. Recursions use more memory
and are generally slow. Instead, you can use loop.
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope and lifetime of a variable.
1. automatic
2. external
Narsimha Reddy Engineering College NRCM
3. static
4. register
Local Variable
The variables declared inside the function are automatic or local variables.
The local variables exist only inside the function in which it is declared. When the function exits, the local
variables are destroyed.
int main() {
int n; // n is a local variable to main() function
... .. ...
}
void func() {
int n1; // n1 is local to func() function
}
In the above code, n1 is destroyed when func() exits. Likewise, n gets destroyed when main() exits.
Global Variable
Variables that are declared outside of all functions are known as external variables. External or global
variables are accessible to any function.
Example #1: External Variable
#include <stdio.h>void display();
int n = 5; // global variable
int main(){
++n; // variable n is not declared in the main() function
display();
return 0;}
void display(){
++n; // variable n is not declared in the display() function
printf("n = %d", n);}
Output
n=7
Suppose, a global variable is declared in file1. If you try to use that variable in a different file file2, the
compiler will complain. To solve this problem, keyword extern is used in file2 to indicate that the external
variable is declared in another file.
Register Variable
The register keyword is used to declare register variables. Register variables were supposed to be faster than
local variables.
However, modern compilers are very good at code optimization and there is a rare chance that using register
variables will make your program faster.聽
Narsimha Reddy Engineering College NRCM
Unless you are working on embedded system where you know how to optimize code for the given
application, there is no use of register variables.
Static Variable
static int i;
The value of a static variable persists until the end of the program.
int main(){
display();
display();}void display(){
static int c = 0;
printf("%d ",c);
c += 5;}
Output
0 5
During the first function call, the value of c is equal to 0. Then, it's value is increased by 5.
During the second function call, variable c is not initialized to 0 again. It's because c is a static variable. So,
5 is displayed on the screen.
C Programming Arrays
An array is a collection of data that holds fixed number of values of same type. For example: if you want to
store marks of 100 students, you can create an array for it.
float marks[100];
The size and type of arrays cannot be changed after its declaration.
1. One-dimensional arrays
2. Multidimensional arrays (will be discussed in next chapter)
data_type array_name[array_size];
For example,
float mark[5];
Here, we declared an array, mark, of floating-point type and size 5. Meaning, it can hold 5 floating-point
values.
Suppose you declared an array mark as above. The first element is mark[0], second element is mark[1] and
so on.
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
mark[3] = 9;
// take input from the user and insert in third elementscanf("%d", &mark[2]);
scanf("%d", &mark[i]);
printf("%d", mark[0]);
printf("%d", mark[i-1]);
Example: C Arrays
printf("Enter n: ");
scanf("%d", &n);
scanf("%d", &marks[i]);
sum += marks[i];
Narsimha Reddy Engineering College NRCM
}
average = sum/n;
return 0;
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
int testArray[10];
If you try to access array elements outside of its bound, let's say testArray[12], the compiler may not show
any error. However, this may cause unexpected output (undefined behavior).
In this section, you will learn to work with multidimensional arrays (two dimensional and three dimensional
array).In C programming, you can create array of an array known as multidimensional array. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as table
with 3 row and each row has 4 column.
float y[2][4][3];
You can think this example as: Each 2 elements have 4 elements, which makes 8 elements and each 8
elements can have 3 elements. Hence, the total number of elements is 24.
Above code are three different ways to initialize a two dimensional arrays.
You can initialize a three dimensional array in a similar way like a two dimensional array. Here's an
example,
int test[2][3][4] = {
};
int main(){
int temperature[CITY][WEEK];
scanf("%d", &temperature[i][j]);
return 0;}
Output
City 1, Day 1: 33
City 1, Day 2: 34
City 1, Day 3: 35
Narsimha Reddy Engineering College NRCM
City 1, Day 4: 33
City 1, Day 5: 32
City 1, Day 6: 31
City 1, Day 7: 30
City 2, Day 1: 23
City 2, Day 2: 22
City 2, Day 3: 21
City 2, Day 4: 24
City 2, Day 5: 22
City 2, Day 6: 25
City 2, Day 7: 26
Displaying values:
City 1, Day 1 = 33
City 1, Day 2 = 34
City 1, Day 3 = 35
City 1, Day 4 = 33
City 1, Day 5 = 32
City 1, Day 6 = 31
City 1, Day 7 = 30
City 2, Day 1 = 23
City 2, Day 2 = 22
City 2, Day 3 = 21
City 2, Day 4 = 24
City 2, Day 5 = 22
City 2, Day 6 = 25
City 2, Day 7 = 26
int i, j;
scanf("%f", &a[i][j]);
scanf("%f", &b[i][j]);
printf("\nSum Of Matrix:");
printf("%.1f\t", c[i][j]);
if(j==1)
printf("\n");
}return 0;}
Ouput
Enter elements of 1st matrix
Enter a11: 2;
Enter a22: 2;
Enter b12: 0;
Sum Of Matrix:
2.2 0.5
-0.9 25.0
int i, j, k, test[2][3][2];
scanf("%d", &test[i][j][k]);
printf("\nDisplaying values:\n");
return 0;}
Output
Enter 12 values:
1
10
11
Displaying Values:
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
Single element of an array can be passed in similar manner as passing variable to a function.
printf("%d", age);}
int main(){
int ageArray[] = { 2, 3, 4 };
return 0;}
Output
While passing arrays as arguments to the function, only the name of the array is passed (,i.e, starting address
of memory area is passed as argument).
C program to pass an array containing age of person to a function. This function should find average
age and display the average age in main function.
int main(){
return 0;}
int i;
sum += age[i];
return avg;}
Output
Average age=27.08
To pass two-dimensional array to a function as an argument, starting address of memory area reserved is
passed as in one dimensional array
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
scanf("%d", &num[i][j]);
displayNumbers(num);
return 0;}
int i, j;
printf("Displaying:\n");
printf("%d\n", num[i][j]);}
Output
Enter 4 numbers:
Displaying:
Arrays are closely related to pointers in C programming but the important difference between them is that, a
pointer variable takes different addresses as value whereas, in case of array it is fixed.
char charArr[4];
int i;
return 0;}
Notice, that there is an equal difference (difference of 1 byte) between any two consecutive elements of
array charArr.
But, since pointers just point at the location of another variable, it can store any address.
Consider an array:
In C programming, name of the array always points to address of the first element of an array.
In the above example,聽 arr and &arr[0]聽 points to the address of the first element.
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
Similarly,
In C, you can declare an array and can use pointer to alter the data of an array.
Example: Program to find the sum of six numbers with arrays and pointers
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
scanf("%d",(classes + i));
return 0;}
Output
Enter 6 numbers:
Sum = 21
When a pointer is passed as an argument to a function, address of the memory location is passed instead of
the value.
This is because, pointer stores the location of the memory, and not the value.
/* C Program to swap two numbers using pointers and function. */#include <stdio.h>void swap(int *n1, int
*n2);
int main(){
return 0;}
int temp;
temp = *n1;
*n1 = *n2;
*n2 = temp;}
Output
Number1 = 10
Number2 = 5
The address of memory location num1 and num2 are passed to the function swap and the pointers *n1 and
*n2 accept those values.
So, now the pointer n1 and n2 points to the address of num1 and num2 respectively.
When, the value of pointers are changed, the value in the pointed memory location also changes
correspondingly.
Hence, changes made to *n1 and *n2 are reflected in num1 and num2 in the main function.
In C, the exact size of array is unknown until compile time, i.e., the time when a compiler compiles your
code into a computer understandable language. So, sometimes the size of the array can be insufficient or
more than required.
Dynamic memory allocation allows your program to obtain more memory space while running, or to release
it if it's not required.
In simple terms, Dynamic memory allocation allows you to manually handle memory space for your
program.
Although, C language inherently does not have any technique to allocate memory dynamically, there are 4
library functions under "stdlib.h" for dynamic memory allocation.
Allocates requested size of bytes and returns a pointer first byte of allocated
malloc()
space
Allocates space for an array elements, initializes to zero and then returns a
calloc()
pointer to memory
C malloc()
The function malloc() reserves a block of memory of specified size and return a pointer of type void which
can be casted into pointer of any form.
Syntax of malloc()
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.
C calloc()
The only difference between malloc() and calloc() is that, malloc() allocates single block of memory
whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
This statement will allocate contiguous space in memory for an array of n elements. For example:
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You
must explicitly use free() to release the space.
syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Write a C program to find sum of n elements entered by user. To perform this program, allocate
memory dynamically using malloc() function.
int main(){
scanf("%d", &num);
if(ptr == NULL)
exit(0);
free(ptr);
return 0;}
Write a C program to find sum of n elements entered by user. To perform this program, allocate
memory dynamically using calloc() function.
int main(){
scanf("%d", &num);
if(ptr == NULL)
exit(0);
free(ptr);
return 0;}
C realloc()
If the previously allocated memory is insufficient or more than required, you can change the previously
allocated memory size using realloc().
Syntax of realloc()
ptr = realloc(ptr, newsize);
Here, ptr is reallocated with size of newsize.
Example #3: Using realloc()
#include <stdio.h>#include <stdlib.h>
int main(){
scanf("%d", &n1);
printf("%u\t",ptr + i);
scanf("%d", &n2);
return 0;}
C Programming Structure
Structure is a collection of variables of different types under a single name.
For example: You want to store some information about a person: his/her name, citizenship number and
salary. You can easily create different variables name, citNo, salary to store these information separately.
Narsimha Reddy Engineering College NRCM
However, in the future, you would want to store information about multiple persons. Now, you'd need to
create different variables for each information per person: name1, citNo1, salary1, name2, citNo2, salary2
You can easily visualize how big and messy the code would look. Also, since no relation between the
variables (information) would exist, it's going to be a daunting task.
A better approach will be to have a collection of all related information under a single name Person, and use
it for every person. Now, the code looks much cleaner, readable and efficient as well.
This collection of all related information under a single name Person is a structure.
Structure Definition in C
Keyword struct is used for creating a structure.
Syntax of structure
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeber;
};
Note: Don't forget the semicolon };聽 in the ending line.
We can create the structure for a person as mentioned above as:
struct person
{
char name[50];
int citNo;
float salary;
};
This declaration above creates the derived data type struct person.
Structure variable declaration
When a structure is defined, it creates a user-defined type but, no storage or memory is allocated.
For the above structure of a person, variable can be declared as:
struct person
{
char name[50];
int citNo;
float salary;
};
int main()
Narsimha Reddy Engineering College NRCM
{
struct person person1, person2, person3[20];
return 0;
}
struct person
char name[50];
int citNo;
float salary;
In both cases, two variables person1, person2 and an array person3 having 20 elements of type struct
person are created.
There are two types of operators used for accessing members of a structure.
1. Member operator(.)
2. Structure pointer operator(->)
structure_variable_name.member_name
Suppose, we want to access salary for variable person2. Then, it can be accessed as:
person2.salary
Example of structure
Write a C program to add two distances entered by user. Measurement of distance should be in inch
and feet. (Note: 12 inches = 1 foot)
int feet;
int main(){
scanf("%d", &dist1.feet);
scanf("%f", &dist1.inch);
printf("2nd distance\n");
scanf("%d", &dist2.feet);
scanf("%f", &dist2.inch);
++sum.feet;
return 0;}
Output
1st distance
Enter feet: 12
2nd distance
Enter feet: 2
Writing struct structure_name variable_name; to declare a structure variable isn't intuitive as to what it
signifies, and takes some considerable amount of development time.
So, developers generally use typedef to name the structure as a whole. For example:
int imag;
float real;
} comp;
int main()
}
Narsimha Reddy Engineering College NRCM
Here, typedef keyword is used in creating a type comp 聽(which is of type as struct complex).
Then, two structure variables comp1 and comp2 are created by this comp type.
struct complex
int imag_value;
float real_value;
};
struct number
int real;
} num1, num2;
Suppose, you want to access imag_value for num2 structure variable then, following structure member is
used.
num2.comp.imag_value
1. Passing by value
2. Passing by reference
struct name {
member1;
member2;
};
int main(){
int age;
float weight;};
int main(){
Narsimha Reddy Engineering College NRCM
struct person *personPtr, person1;
scanf("%d",&(*personPtr).age);
scanf("%f",&(*personPtr).weight);
printf("Displaying: ");
printf("%d%f",(*personPtr).age,(*personPtr).weight);
return 0;}
In this example, the pointer variable of type struct person is referenced to the address of person1. Then, only
the structure member through pointer can can accessed.
float weight;
char name[30];};
int main(){
int i, num;
scanf("%d", &num);
// Above statement allocates the memory for n structures with pointer personPtr pointing to base address
printf("Displaying Infromation:\n");
return 0;}
Output
Adam
3.2
Eve
2.3
Displaying Information:
Adam 2 3.20
Eve 6 2.30
In this article, you'll find relevant examples to pass structures as an argument to a function, and use them in
your program.
If structure is passed by value, changes made to the structure variable inside the function definition does not
reflect in the originally passed structure variable.
C program to create a structure student, containing name and roll and display the information.
#include <stdio.h>struct student{
char name[50];
int roll;};
void display(struct student stu);// function prototype should be below to the structure declaration otherwise
compiler shows error
int main(){
scanf("%s", &stud.name);
scanf("%d", &stud.roll);
printf("Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);}
Output
Output
Roll: 149
The memory address of a structure variable is passed to function while passing it by reference.
If structure is passed by reference, changes made to the structure variable inside function definition reflects
in the originally passed structure variable.
C program to add two distances (feet-inch system) and display the result without the return
statement.
int feet;
float inch;};void add(struct distance d1,struct distance d2, struct distance *d3);
int main(){
printf("First distance\n");
scanf("%d", &dist1.feet);
scanf("%f", &dist1.inch);
printf("Second distance\n");
scanf("%d", &dist2.feet);
scanf("%f", &dist2.inch);
//passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by
reference
return 0;}void add(struct distance d1,struct distance d2, struct distance *d3) {
d3->inch -= 12;
++d3->feet;
}}
Output
First distance
Enter feet: 12
Second distance
Enter feet: 5
In this program, structure variables dist1 and dist2 are passed by value to the add function (because value of
dist1 and dist2 does not need to be displayed in main function).But, dist3 is passed by reference ,i.e, address
of dist3(&dist3) is passed as an argument.
Due to this, the structure pointer variable d3 inside the add function points to the address of dist3 from the
calling main function. So, any change made to the d3 variable is seen in dist3 variable in main function.
C Programming Unions
Unions are quite similar to structures in C. Like structures, unions are also derived types.
union car
char name[50];
int price;
};
Defining a union is as easy as replacing the keyword struct with the keyword union.
char name[50];
int price;
OR
union car
char name[50];
int price;
};
int main()
return 0;
In both cases, union variables car1, car2 and union pointer variable car3 of type union car is created.
In the above example, suppose you want to access price for union variable car1, it can be accessed as:
car1.price
Likewise, if you want to access price for the union pointer variable car3, it can be accessed as:
(*car3).price
or;
car3->price
//defining a union
char name[32];
float salary;
struct structJob{
char name[32];
float salary;
int main(){
return 0;}
Output
size of union = 32
size of structure = 40
As seen in the above example, there is a difference in memory allocation between union and structure.
The amount of memory required to store a structure variable is the sum of memory size of all members.
But, the memory required to store a union variable is the memory required for the largest element of an
union.
In the case of structure, all of its members can be accessed at any time.
But, in the case of union, only one of its members can be accessed at a time and all other members will
contain garbage values.
char name[32];
float salary;
int main(){
printf("Enter name:\n");
scanf("%s", &job1.name);
scanf("%f", &job1.salary);
return 0;}
Output
Enter name
Hillary
Enter salary
1234.23
Narsimha Reddy Engineering College NRCM
Displaying
Name: f%Bary
Salary: 1234.2
Note: You may get different garbage value for the name.
Initially in the program,聽 Hillary is stored in job1.name and all other members of job1, i.e. salary,
workerNo, will contain garbage values.
But, when user enters the value of salary, 1234.23 will be stored in job1.salary and other members, i.e. name,
workerNo, will now contain garbage values.
Thus in the output, salary is printed accurately but, name displays some random string.
There are a large number of functions to handle file I/O (Input Output) in C. In this tutorial, you will learn to
handle standard I/O in C using fprintf(), fscanf(), fread(), fwrite(), fseek.and more.
• When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if
the program terminates.
• If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the file
using few commands in C.
• You can easily move your data from one computer to another without any changes.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
1. Text files
Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit or
delete the contents.
Narsimha Reddy Engineering College NRCM
They take minimum effort to maintain, are easily readable, and provide least security and takes bigger
storage space.
2. Binary files
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security than text files.
File Operations
In C, you can perform four major operations on the file, either text or binary:
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
• Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first function
creates a new file named newprogram.txt and opens it for writing as per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
• Now let's suppose the second binary file oldprogram.bin exists in the location E:\cprogram. The
second function opens the existing file for reading in binary mode 'rb'.
The reading mode only allows you to read the file, you cannot write into the file.
r Open for reading. If the file does not exist, fopen() returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten. If the file does
w Open for writing.
not exist, it will be created.
If the file exists, its contents are overwritten. If the file does
wb Open for writing in binary mode.
not exist, it will be created.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten. If the file does
w+ Open for both reading and writing.
not exist, it will be created.
Open for both reading and writing in If the file exists, its contents are overwritten. If the file does
wb+
binary mode. not exist, it will be created.
Closing a File
The file (both text and binary) should be closed after reading/writing.
They are just the file versions of printf() and scanf(). The only difference is that, fprint and fscanf expects a
pointer to the structure FILE.
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
printf("Error!");
exit(1);
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;}
This program takes a number from user and stores in the file program.txt.
After you compile and run this program, you can see a text file program.txt created in C drive of your
computer. When you open the file, you can see the integer you entered.
int num;
FILE *fptr;
exit(1);
fscanf(fptr,"%d", &num);
fclose(fptr);
return 0;}
This program reads the integer present in the program.txt file and prints it onto the screen.
If you succesfully created the file from Example 1, running this program will get you the integer you
entered.
Other functions like fgetchar(), fputc() etc. can be used in similar way.
Functions fread() and fwrite() are used for reading from and writing to a file on the disk respectively in case
of binary files.
To write into a binary file, you need to use the function fwrite(). The functions takes four arguments:
Address of data to be written in disk, Size of data to be written in disk, number of such type of data and
pointer to the file where you want to write.
fwrite(address_data,size_data,numbers_data,pointer_to_file);
Narsimha Reddy Engineering College NRCM
Example 3: Writing to a binary file using fwrite()
#include <stdio.h>
struct threeNum{
int main(){
int n;
FILE *fptr;
exit(1);
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fclose(fptr);
return 0;}
Now, inside the for loop, we store the value into the file using fwrite.
The first parameter takes the address of num and the second parameter takes the size of the structure
threeNum.
Since, we're only inserting one instance of num, the third parameter is 1. And, the last parameter *fptr points
to the file we're storing the data.
fread(address_data,size_data,numbers_data,pointer_to_file);
#include <stdio.h>
struct threeNum{
int main(){
int n;
FILE *fptr;
exit(1);
fclose(fptr);
return 0;}
In this program, you read the same file program.bin and loop through the records one by one.
In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into the
structure num.
If you have many records inside a file and need to access a record at a specific position, you need to loop
through all the records before it to get the record.
This will waste a lot of memory and operation time. An easier way to get to the required data can be
achieved using fseek().
As the name suggests, fseek() seeks the cursor to the given record in the file.
Syntax of fseek()
The first parameter stream is the pointer to the file. The second parameter is the position of the record to be
found, and the third parameter specifies the location where the offset starts.
Whence Meaning
SEKK_CUR Starts the offset from the current location of the cursor in the file.
Example of fseek()
struct threeNum{
int main(){
int n;
FILE *fptr;
exit(1);
fclose(fptr);
return 0;}
This program will start reading the records from the file program.bin in the reverse order (last to first) and
prints it.
In this article, you will learn to work with enumeration (enum). Also, you will learn where enums are
commonly used in C programming.
An enumeration is a user-defined data type that consists of integral constants. To define an enumeration,
keyword enum is used.
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during
declaration (if necessary).
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};
When you create an enumerated type, only blueprint for the variable is created. Here's how you can create
variables of enum type.
false, true
} check;
#include <stdio.h>
int main(){
today = wednesday;
printf("Day %d",today+1);
return 0;}
Output: Day 4
Enum variable takes only one value out of many possible values. Example to demonstrate it,
#include <stdio.h>
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3} card;
int main() {
card = club;
return 0;}
Output
You can accomplish the same task using structures. However, working with enums gives you efficiency
along with flexibility.
enum designFlags {
ITALICS = 1,
BOLD = 2,
UNDERLINE = 4} button;
Suppose you are designing a button for Windows application. You can set flags ITALICS, BOLD and
UNDERLINE to work with text.
There is a reason why all the integral constants are power of 2 in above pseudocode.
// In binary
ITALICS = 00000001
BOLD = 00000010
UNDERLINE = 00000100
Since, the integral constants are power of 2, you can combine two or more flags at once without overlapping
using bitwise OR | operator. This allows you to choose two or more flags at once. For example,
Example program:
#include <stdio.h>
enum designFlags {
BOLD = 1,
ITALICS = 2,
UNDERLINE = 4};
int main() {
// 00000001
// | 00000100
// 00000101
printf("%d", myDesign);
return 0;}
Output
When the output is 5, you always know that bold and underline is used.
Here, we have added italics to our design. Note, only code for italics is written inside if statement.
You can accomplish almost anything in C programming without using enumerations. However, they can be
pretty handy in certain situations. That's what differentiates good programmers from great programmers.
language recognizes that strings are terminated by null character and is a different class of array by letting us
input and output the array as a unit. To array out many of the string manipulations,C library supports a large
number of string handling functions that can be used such as:
strlen():
#include <stdio.h>
#include <string.h>
int main()
char a[20]="Program";
char b[20]={'P','r','o','g','r','a','m','\0'};
char c[20];
gets(c);
return 0;
Output
Length of string a = 7
Length of string b = 7
Length of string c = 6
2.strcpy():
The strcpy() function copies the string pointed by source (including the null character) to the character array
destination.
Example: C strcpy()
Narsimha Reddy Engineering College NRCM
#include <stdio.h>
#include <string.h>
int main()
char str2[10];
char str3[10];
strcpy(str2, str1);
strcpy(str3, "well");
puts(str2);
puts(str3);
return 0;
Output
awesome
well
/* strncpy example */
#include <stdio.h>
#include <string.h>
int main ()
char str2[40];
char str3[40];
puts (str1);
puts (str2);
puts (str3);
return 0;
Output:
To be or not to be
To be or not to be
To be
strcat():
#include <stdio.h>
#include <string.h>
int main()
strcat(str1,str2);//str1=str1+str2;
puts(str1);
puts(str2);
return 0;
Output
hello i am sarfaraz
/* strncat example */
#include <stdio.h>
#include <string.h>
int main ()
char str1[20];
char str2[20];
strcpy (str1,"hello");
puts (str1);
return 0;
Output:
hellogood af
strlwr():
#include<string.h>
int main()
printf("%s\n",strlwr (str));
return 0;
Output:
#include<stdio.h>
#include<string.h>
int main()
printf("%s\n",strupr (str));
return 0;
Output:
I AM SARFARAZ
#include<stdio.h>
#include<string.h>
int main()
return 0;
Output:
strcmp( ) function in C compares two given strings and returns zero if they are same.
•If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value. Syntax
for strcmp( ) function is given below.
#include <stdio.h>
#include <string.h>
int main( )
int i, j, k ;
return 0;
Output:
0 -1 1
Narsimha Reddy Engineering College NRCM
strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function is not case sensitive. i.e, “A”
and “a” are treated as same characters. Where as, strcmp() function treats “A” and “a” as different
characters.
#include <stdio.h>
#include <string.h>
int main( )
int i, j, k ;
return 0;
Output:
0 -1 1
strchr():
strchr( ) function returns pointer to the first occurrence of the character in a given string. Syntax for strchr( )
function is given below
#include <stdio.h>
#include <string.h>
int main ()
char *p;
p = strchr (string,'i');
Narsimha Reddy Engineering College NRCM
printf ("Character i is found at position %d\n",p-string+1);
return 0;
Output:
First occurrence of character “i” in “This is a string for testing” is “is is a string for testing”
#include <stdio.h>
#include <string.h>
int main ()
char *p;
int k = 1;
p = strchr (string,'i');
while (p!=NULL)
"\"\n",string, p);
p=strchr(p+1,'i');
k++;
return 0;
Output:
Occurrence of character “i” in “This is a string for testing” is “is is a string for testing”
Occurrence of character “i” in “This is a string for testing” is “is a string for testing”
Occurrence of character “i” in “This is a string for testing” is “ing for testing”
strrchr();
#include <stdio.h>
#include <string.h>
int main ()
char *p;
p = strchr (string,'l');
strstr():
strstr( ) function returns pointer to the first occurrence of the string in a given string.
include <stdio.h>
#include <string.h>
int main ()
char *p;
p = strstr (string,"test");
if(p)
printf("string found\n" );
return 0;
Output:
string found
First occurrence of string “test” in “This is a test string for testing” is “test string for testing”
#include <stdio.h>
#include <string.h>
int main()
char *p2;
p2 = strdup(p1);
return 0;
Output:
note :strdup allocates memory for the new string on the heap, while using strcpy (or its safer strncpy varient)
I can copy a string to a pre allocated memory on either the heap or the stack. char *strdup(char *pszSrch) ;
strdup will allocate storage the size of the original string
C – strset() function
#include<stdio.h>
#include<string.h>
int main()
return 0;
Output:
C – strnset() function
strnset( ) function is non standard function which may not available in standard library in C.
#include<stdio.h>
#include<string.h>
int main()
return 0;
Output:
C – strtok() function
#include <string.h>
int main ()
char *p;
p = strtok (string,",:");
printf ("%s\n",p);
return 0;
Output:
Test
string1
Test
string2
Test
string3
Data Structure is a way of collecting and organising data in such a way that we can perform operations on
these data in an effective way. Data Structures is about rendering data elements in terms of some
relationship, for better organization and storage. For example, we have data player's name "Virat" and age
26. Here "Virat" is of String data type and 26 is of integer data type.
• Linked List
• Tree
• Graph
• Stack, Queue etc.
All these data structures allow us to perform different operations on data. We select these data structures
based on which type of operation is required. We will look into these data structures in more details in our
later lessons.
What is Algorithm ?
An algorithm is a finite set of instructions or logic, written in order, to accomplish a certain predefined task.
Algorithm is not the complete code or program, it is just the core logic(solution) of a problem, which can be
expressed either as an informal high level description as pseudocode or using a flowchart.
An algorithm is said to be efficient and fast, if it takes less time to execute and consumes less memory space.
The performance of an algorithm is measured on the basis of following properties :
1. Time Complexity
Narsimha Reddy Engineering College NRCM
2. Space Complexity
Space Complexity
Its the amount of memory space required by the algorithm, during the course of its execution. Space
complexity must be taken seriously for multi-user systems and in situations where limited memory is
available.
An algorithm generally requires space for following components :
• Instruction Space : Its the space required to store the executable version of the program. This space
is fixed, but varies depending upon the number of lines of code in the program.
• Data Space : Its the space required to store all the constants and variables value.
• Environment Space : Its the space required to store the environment information needed to resume
the suspended function.
Time Complexity
Time Complexity is a way to represent the amount of time needed by the program to run to completion. We
will study this in detail.
Time complexity of an algorithm signifies the total time required by the program to run to completion. The
time complexity of algorithms is most commonly expressed using the big O notation.
Time Complexity is most commonly estimated by counting the number of elementary functions performed
by the algorithm. And since the algorithm's performance may vary with different types of input data, hence
for an algorithm we usually use the worst-case Time complexity of an algorithm because that is the
maximum time taken for any input size.
Introduction to Sorting
Sorting is nothing but storage of data in sorted order, it can be in ascending or descending order. The term
Sorting comes into picture with the term Searching. There are so many things in our real life that we need to
search, like a particular record in database, roll numbers in merit list, a particular telephone number, any
particular page in a book etc.
Sorting arranges data in a sequence which makes searching easier. Every record which is going to be sorted
will contain one key. Based on the key the record will be sorted. For example, suppose we have a record of
students, every such record will have the following data:
• Roll No.
• Name
• Age
• Class
Narsimha Reddy Engineering College NRCM
Here Student roll no. can be taken as key for sorting the records in ascending or descending order. Now
suppose we have to search a Student with roll no. 15, we don't need to search the complete record we will
simply search between the Students with roll no. 10 to 20.
Sorting Efficiency
There are many techniques for sorting. Implementation of particular sorting technique depends upon
situation. Sorting techniques mainly depends on two parameters. First parameter is the execution time of
program, which means time taken for execution of program. Second is the space, which means space taken
by the program.
1. Bubble Sort
2. Insertion Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort
6. Heap Sort
Bubble Sorting
Bubble Sort is an algorithm which is used to sort N elements that are given in a memory for eg: an Array
withN number of elements. Bubble Sort compares all the element one by one and sort them based on their
values.
It is called Bubble sort, because with each iteration the smaller element in the list bubbles up towards the
first place, just like a water bubble rises up to the water surface.
Sorting takes place by stepping through all the data items one-by-one in pairs and comparing adjacent data
items and swapping each pair that is out of order.
(n-1)+(n-2)+(n-3)+.....+3+2+1
Sum = n(n-1)/2
i.e O(n2)
Hence the complexity of Bubble Sort is O(n2).
The main advantage of Bubble Sort is the simplicity of the algorithm.Space complexity for Bubble Sort
is O(1), because only single additional memory space is required for temp variable
Best-case Time Complexity will be O(n), it is when the list is already sorted.
Insertion Sorting
It is a simple Sorting algorithm which sorts the array by shifting elements one by one. Following are some of
the important characteristics of Insertion Sort.
In the first pass, the smallest element found is 1, so it is placed at the first position, then leaving first element,
smallest element is searched from the rest of the elements, 3 is the smallest, so it is then placed at the second
position. Then we leave 1 nad 3, from the rest of the elements, we search for the smallest and put it at third
position and keep doing this, until array is sorted.
Quick Sort, as the name suggests, sorts any list very quickly. Quick sort is not stable search, but it is very
fast and requires very less aditional space. It is based on the rule of Divide and Conquer(also
called partition-exchange sort). This algorithm divides the list into three main parts :
In the list of elements, mentioned in below example, we have taken 25 as pivot. So after the first pass, the
list will be changed like this.
6 8 17 14 25 63 37 52
Hnece after the first pass, pivot will be set at its position, with all the elements smaller to it on its left and all
the elements larger than it on the right. Now 6 8 17 14 and 63 37 52 are considered as two separate lists, and
same logic is applied on them, and we keep doing this until the complete list is sorted.
How Quick Sorting Works
Merge Sort follows the rule of Divide and Conquer. But it doesn't divides the list into two halves. In merge
sort the unsorted list is divided into N sublists, each having one element, because a list of one element is
considered sorted. Then, it repeatedly merge these sublists, to produce new sorted sublists, and at lasts one
sorted list is produced.
Merge Sort is quite fast, and has a time complexity of O(n log n). It is also a stable sort, which means the
"equal" elements are ordered in the same order in the sorted list.
Like we can see in the above example, merge sort first breaks the unsorted list into sorted sublists, and then
keep merging these sublists, to finlly get the complete sorted list.
while(i <= q)
{
b[k++] = a[i++];
}
while(j <= r)
• Time complexity of Merge Sort is O(n Log n) in all 3 cases (worst, average and best) as merge sort
always divides the array in two halves and take linear time to merge two halves.
• It requires equal amount of additional space as the unsorted list. Hence its not at all recommended for
searching large unsorted lists.
• It is the best Sorting technique for sorting Linked Lists.
Heap Sort is one of the best sorting methods being in-place and with no quadratic worst-case scenarios.
Heap sort algorithm is divided into two basic parts :
What is a Heap ?
Heap is a special tree-based data structure, that satisfies the following special heap properties :
1. Shape Property : Heap data structure is always a Complete Binary Tree, which means all levels of
the tree are fully filled.
void main()
{
int a[10], i, size;
cout <<"Enter size of list"; // less than 10, because max size of array is 10
cin >> size;
cout <<"Enter"<< size <<"elements";
for( i=0; i < size; i++)
{
cin >> a[i];
}
heapsort(a, size);
getch();
}
• Heap sort is not a Stable sort, and requires a constant space for sorting a list.
• Heap Sort is very fast and is widely used for sorting.
Binary Search
Binary Search is applied on the sorted array or list. In binary search, we first compare the value with the
elements in the middle position of the array. If the value is matched, then we return the value. If the value is
less than the middle element, then it must lie in the lower half of the array and if it's greater than the element
then it must lie in the upper half of the array. We repeat this procedure on the lower (or upper) half of the
array. Binary Search is useful when there are large numbers of elements in an array.
Stacks
Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data structure that allows
adding and removing elements in a particular order. Every time an element is added, it goes on the top of the
stack, the only element that can be removed is the element that was at the top of the stack, just like a pile of
objects.
Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to stack - letter by letter -
and then pop letters from the stack.
There are other uses also like : Parsing, Expression Conversion(Infix to Postfix, Postfix to Prefix etc) and
many more.
Implementation of Stack
Stack can be easily implemented using an Array or a Linked List. Arrays are quick, but are limited in size
and Linked List requires overhead to allocate, link, unlink, and deallocate, but is not limited in size. Here we
will implement Stack using array.
Class Stack
{
int top;
public:
int a[10]; //Maximum size of Stack
Stack()
Narsimha Reddy Engineering College NRCM
{
top = -1;
}
};
void Stack::push(int x)
{
if( top >= 10)
{
cout <<"Stack Overflow";
}
else
{
a[++top] = x;
cout <<"Element Inserted";
}
}
int Stack::pop()
{
if(top < 0)
{
cout <<"Stack Underflow";
return 0;
}
else
{
int d = a[--top];
return d;
}
}
void Stack::isEmpty()
{
if(top < 0)
{
cout <<"Stack is empty";
-1 Stack is Empty
Analysis of Stacks
Below mentioned are the time complexities for various operations that can be performed on the Stack data
structure.
Queue is also an abstract data type or a linear data structure, in which the first element is inserted from one
end called REAR(also called tail), and the deletion of exisiting element takes place from the other end
called as FRONT(also called head). This makes queue as FIFO data structure, which means that element
inserted first will also be removed first.
The process to add an element into queue is called Enqueue and the process of removal of an element from
queue is called Dequeue.
1. Like Stack, Queue is also an ordered list of elements of similar data types.
2. Queue is a FIFO( First in First Out ) structure.
3. Once a new element is inserted into the Queue, all the elements inserted before the new element in
the queue must be removed, to remove the new element.
4. peek( ) function is oftenly used to return the value of first element without dequeuing it.
Applications of Queue
Queue, as the name suggests is used whenever we need to have any group of objects in an order in which the
first one coming in, also gets out first while the others wait for there turn, like in the following scenarios :
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life, Call Center phone systems will use Queues, to hold people calling them in an order, until
a service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order as they
arrive, First come first served.
Implementation of Queue
Queue can be implemented using an Array, Stack or Linked List. The easiest way of implementing a queue
is by using an Array. Initially the head(FRONT) and the tail(REAR) of the queue points at the first index of
the array (starting the index of array from 0). As we add elements to the queue, the tail keeps on moving
ahead, always pointing to the position where the next element will be inserted, while the head remains at the
first index.
public:
• Enqueue : O(1)
• Dequeue : O(1)
• Size : O(1)
A Queue is defined by its property of FIFO, which means First in First Out, i.e the element which is added
first is taken out first. Hence we can implement a Queue using Stack for storage instead of array.
For performing enqueue we require only one stack as we can directly push data into stack, but to
performdequeue we will require two Stacks, because we need to follow queue's FIFO property and if we
directly popany data element out of Stack, it will follow LIFO approach(Last in First Out).
int dequeue();
}
We know that, Stack is a data structure, in which data can be added using push() method and data can be
deleted using pop() method. To learn about Stack, follow the link : Stack Data Structure
As our Queue has Stack for data storage in place of arrays, hence we will be adding data to Stack, which can
be done using the push() method, hence :
void Queue :: enqueue(int x) {
S1.push(x);
}
while(!S2.isEmpty()) {
x = S2.pop();
S1.push(x);
}
Linked List is a linear data structure and it is very common data structure which consists of group of nodes
in a sequence which is divided in two parts. Each node consists of its own data and the address of the next
node and forms a chain. Linked Lists are used to create trees and graphs.
• They are a dynamic in nature which allocates the memory when required.
• Insertion and deletion operations can be easily implemented.
• Stacks and queues can be easily executed.
• Linked List reduces the access time.
• Singly Linked List : Singly linked lists contain nodes which have a data part as well as an address
part i.e. next, which points to the next node in sequence of nodes. The operations we can perform on
singly linked lists are insertion, deletion and traversal.
• Circular Linked List : In the circular linked list the last node of the list contains the address of the
first node and forms a circular chain.
Before inserting the node in the list we will create a class Node. Like shown below :
LinkedList() {
head = NULL;
}
}
1. If the Linked List is empty then we simply, add the new Node as the Head of the Linked List.
2. If the Linked List is not empty then we find the last node, and make it' next to the new Node, hence
making the new node the last Node.
• If the Node to be deleted is the first node, then simply set the Next pointer of the Head to point to the
next element from the Node to be deleted.
• If the Node is in the middle somewhere, then find the Node before it, and make the Node before it
point to the Node next to it.
Now you know a lot about how to handle List, how to traverse it, how to search an element. You can
yourself try to write new methods around the List.
If you are still figuring out, how to call all these methods, then below is how your main() method will look
like. As we have followed OOP standards, we will create the objects of LinkedList class to initialize our
List and then we will create objects of Node class whenever we want to add any new node to the List.
int main() {
LinkedList L;
//We will ask value from user, read the value and add the value to our Node
int x;
cout <<"Please enter an integer value : ";
cin >> x;
Node *n1;
//Creating a new node with data as x
n1 = new Node(x);
//Adding the node to the list
L.addAtFront(n1);
}
Similarly you can call any of the functions of the LinkedList class, add as many Nodes you want to your
List.
Circular Linked List is little more complicated linked data structure. In the circular linked list we can insert
elements anywhere in the list whereas in the array we cannot insert element anywhere in the list because it is
in the contiguous memory. In the circular linked list the previous element stores the address of the next
element and the last element stores the address of the starting element. The elements points to each other in a
circular way which forms a circular chain. The circular linked list has a dynamic size which means the
memory can be allocated when it is required.
• The real life application where the circular linked list is used is our Personal Computers, where
multiple applications are running. All the running applications are kept in a circular linked list and the OS
gives a fixed time slot to all for running. The Operating System keeps on iterating over the linked list
until all the applications are completed.
Narsimha Reddy Engineering College NRCM
• Another example can be Multiplayer games. All the Players are kept in a Circular Linked List and
the pointer keeps on moving forward as a player's chance ends.
• Circular Linked List can also be used to create Circular Queue. In a Queue we have to keep two
pointers, FRONT and REAR in memory all the time, where as in Circular Linked List, only one pointer
is required.
node() {
data = 0;
next = NULL;
}
node(int x) {
data = x;
next = NULL;
}
}
class CircularLinkedList {
public:
node *head;
//declaring the functions
CircularLinkedList() {
head = NULL;
}
}
Insertion at the Beginning
Steps to insert a Node at beginning :
1. If the Linked List is empty then we simply, add the new Node as the Head of the Linked List.
2. If the Linked List is not empty then we find the last node, and make it' next to the new Node, and
make the next of the Newly added Node point to the Head of the List.
• If the Node to be deleted is the first node, then simply set the Next pointer of the Head to point to the
next element from the Node to be deleted. And update the next pointer of the Last Node as well.
• If the Node is in the middle somewhere, then find the Node before it, and make the Node before it
point to the Node next to it.
• If the Node is at the end, then remove it and make the new last node point to the head.