C Full Note
C Full Note
4
5
6
8
About C Language
• Easy to learn
• Structured language
• It produces efficient programs
• It can handle low-level activities
• It can be compiled on a variety of computer platforms
Facts about C
• C was invented to write an operating system called UNIX.
• C is a successor of B language which was introduced around the early 1970s.
• The language was formalized in 1988 by the American National Standard
Institute (ANSI).
• The UNIX OS was totally written in C.
• Today C is the most widely used and popular System Programming Language.
• Most of the state-of-the-art software have been implemented using C.
• Today's most popular Linux OS and RDBMS MySQL have been written in C.
Why use C?
C was initially used for system development work, particularly the programs that make-up the
operating system. C was adopted as a system development language because it produces code
that runs nearly as fast as the code written in assembly language. Some examples of the use
of C might be −
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
Structure of a C program
1. Documentation section
2. Preprocessor section
3. Definition section
4. Global declaration
5. Main function
6. User defined functions
1. Documentation section
It includes the statement specified at the beginning of a program, such as a program's name,
date, description, and title. It is represented as:
//name of a program
Or
/*
Overview of the code
*/
Both methods work as the document section in a program. It provides an overview of the
program. Anything written inside will be considered a part of the documentation section and
will not interfere with the specified code.
2. Preprocessor section
The preprocessor section contains all the header files used in a program. It informs the system
to link the header files to the system libraries. It is given by:
1. #include<stdio.h>
2. #include<conio.h>
The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled. The #include<stdio.h> consists of the contents of the standard input output files,
which contains the definition of stdin, stdout, and stderr. Whenever the definitions stdin, stdout,
and stderr are used in a function, the statement #include<stdio.h> need to be used.
There are various header files available for different purposes. For example, # include
<math.h>. It is used for mathematic functions in a program.
3. Define section
The define section comprises of different constants declared using the define keyword. It is
given by:
#define a = 2
4. Global declaration
The global section comprises of all the global declarations in the program. It is given by:
char = 1 byte
float = 4 bytes
int = 4 bytes
5. Main function
main() is the first function to be executed by the computer. It is necessary for a code to include
the main(). Parenthesis () are used for passing parameters (if any) to a function.
main()
We can also use int or void with the main (). The void main() specifies that the program will
not return any value. The int main() specifies that the program can return integer type data.
int main()
Or
void main()
Main function is further categorized into local declarations, statements, and expressions.
Local declarations
The variable that is declared inside a given function or block refers to as local declarations.
void main()
{
int i = 2;
i++;
}
Statements
The statements refers to if, else, while, do, for, etc. used in a program within the main function.
Expressions
An expression is a type of formula where operands are linked with each other by the use of
operators. It is given by:
1. a - b;
2. a +b;
The user defined functions specified the functions specified as per the requirements of the user.
For example, color(), sum(), division(), etc.
TYPES
Machine language:
A low level first generation computer language, popular during early 1960s, which
uses abbreviations or mnemonic codes for operation. This symbolic instruction
language is called Assembly language.
The mnemonics are converted into binaries with the help of a translator known as
Assembler.
The program written using mnemonics is called Source Program or assembly
language program, the binary form of the source program equivalent is called
Object Program.
Assembler is used to convert assembly language into the machine language.
Assembly language programs are commonly used to write programs for electronic
controls using microprocessors e.g., compilers, operating systems, animation in
computer graphics and so on.
Instructions which are written using English language with symbols and digits are
called high level languages and is closer to our natural language.
The commonly used high level languages are FORTRAN, BASIC, COBOL,
PASCAL, PROLOG, C, C++, JAVA etc.
The complete instruction set written in one of these languages is called a high
level language program or computer program or source program.
In order to execute the instructions, the source program is translated into binary
form by a compiler or interpreter.
Compiler:
Interpreter:
An interpreter is a program which takes the source program line by line and converts
into machine code but execute each line by line as it is entered. Programming
languages BASIC, LISP, JAVA use interpreters.
A simple code that would print the words "Hello World"
#include <stdio.h>
#include <conio.h>
void main()
{
/* my first program in C */
printf("Hello, World! \n");
getch();
}
1. printf("format string",argument_list);
➢ scanf() function
The scanf() function is used for input. It reads the input data from the console.
1. scanf("format string",argument_list);
There are 2 ways to compile and run the c program, by menu and by shortcut.
By menu
Now click on the compile menu then compile sub menu to compile the c program.
Then click on the run menu then run sub menu to run the c program.
By shortcut
Press ctrl+f9 keys compile and run the program directly.
You can view the user screen any time by pressing the alt+f5 keys.
Compilation process in c
The compilation is a process of converting the source code into object code. It is done with the
help of the compiler. The compiler checks the source code for the syntactical or structural
errors, and if the source code is error-free, then it generates the object code.
The compilation process can be divided into four steps, i.e., Pre-processing, Compiling,
Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the
directive and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed into
an executable form:
o Preprocessor
o Compiler
o Assembler
o Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is given
an extension ".c". This source code is first passed to the preprocessor, and then the preprocessor
expands this code. After expanding the code, the expanded code is passed to the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of
the object file generated by the assembler is the same as the source file. The extension
of the object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the
source file is 'hello.c', then the name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are
pre-compiled, and the object code of these library files is stored with '.lib' (or '.a')
extension. The main working of the linker is to combine the object code of library files
with the object code of our program. It links the object code of these files to our
program. Therefore, we conclude that the job of the linker is to link the object code of
our program with the object code of the library files and other files. The output of the
linker is the executable file. The name of the executable file is the same as the source
file but differs only in their extensions. In DOS, the extension of the executable file is
'.exe', and in UNIX, the executable file can be named as 'a.out'. For example, if we are
using printf() function in a program, then the linker adds its associated code in an
output file.
In the above flow diagram, the following steps are taken to execute a program:
o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the
preprocessor converts the source code into expanded source code. The
extension of the expanded source code would be hello.i.
o The expanded source code is passed to the compiler, and the compiler converts
this expanded source code into assembly code. The extension of the assembly
code would be hello.s.
o This assembly code is then sent to the assembler, which converts the assembly
code into object code.
o After the creation of an object code, the linker creates the executable file. The
loader will then load the executable file for the execution.
1
3
4
Executable File
An executable file is a type of computer file that runs a program when it is opened. This means
it executes code or a series of instructions contained in the file. The two primary types of
executable files are 1) compiled programs and 2) scripts.
On Windows systems, compiled programs have an .EXE file extension and are often referred
to as "EXE files." On Macintosh computers, compiled programs have an .APP extension,
which is short for application.
Uncompiled executable files are often referred to as scripts. These files are saved in a plain
text format, rather than a binary format. In other words, you can open a script file and view the
code in a text editor. Since scripts do not contain executable machine code, they require
an interpreter to run. For example, a PHP file can execute code only when run through a PHP
interpreter. If a PHP interpreter is not available, the PHP script can only be opened as a text
file.
Since executable files run code when opened, you should not open unknown executable files,
especially ones received as email attachments. While compiled executable files are the most
dangerous, script files can run malicious code as well.
Windows file extensions: .EXE, .COM, .BAT, .VB, .VBS, .WSF, .PIF
Macintosh file extensions: .APP, .SCPT, .APPLESCRIPT
File extensions
A file extension is a three- or four-letter identifier found at the end of a file name and following
a period. These extensions tell you about the characteristics of a file and its use.
The most common executable file are files ending with the .exe file extension.
1. Function definitions
2. Data type definitions
3. Macros
Whenever we require the definition of a function, then we simply include that header file in which
function is declared. Header file is used to avoid writing large and complex code.
o System defined header file: The header file which is predefined is known as a system
defined header file.
o User-defined header file: The header file which is defined by the user is known as a
user-defined header file.
Both the user-defined and system-defined header file can be included in a program with the
help of using preprocessing directive (#). These preprocessor directives are used to instruct the
compiler to process these files before compilation. There are two forms of including header
file:
o #include<file>
o #include "file"
There is a difference between the header files given above. If the header file is defined within
the predefined source path, we can specify the header within the angular brackets. If the header
file is not defined within the predefined source path then we can specify the full path of the
header file within the double-quotes.
o #include<stdio.h>: It is used for performing input and output operations with the help
of using printf() and scanf() function.
o #include<string.h>: It is used for performing string related functionalities like strlen(),
strcmp(), etc.
o #include<iostream>: It is used to perform input and output operations with the help of
using cin and cout objects.
o #include<math.h>: This header file contains some predefined math functions that
perform mathematical operations, such as sqrt(), log2(), pow(), etc.
o #include<errno.h>: It performs the error handling related operations like errno(),
strerror(), perror(), etc.
o #include<time.h>: It is used to perform functions related to date()
and time() like setdate() and getdate().
➢ Preprocessor Directives
The preprocessor directives give instruction to the compiler to preprocess the information
before actual compilation starts.
All of these preprocessor directives begin with a ‘#’ (hash) symbol. The ‘#’ symbol indicates
that, whatever statement starts with #, is going to the preprocessor program, and preprocessor
program will execute this statement. Examples of some preprocessor directives
are: #include, #define, #ifndef etc.
➢ C Macros
A macro is a segment of code which is replaced by the value of macro. Macro is defined by
#define directive. There are two types of macros:
1. Object-like Macros
2. Function-like Macros
Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants. For example:
1. #define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
Function-like Macros
Example:
// Macro definition
#define LIMIT 5
int main()
{
// Print the value of macro defined
printf("The value of LIMIT is %d", LIMIT);
return 0;
}
Output:
The value of LIMIT is 5
Variables
A variable is a name of the memory location. It is used to store data. Its value can be changed,
and it can be reused many times.
The primary purpose of variables is to store data in memory for later use. If you declare a variable
in C, that means you are asking the operating system to reserve a piece of memory with that
variable name.
Variable Declaration
data type variable_name;
or
data type variable_name, variable_name, variable_name;
char letter='A';
double d;
/* actual initialization */
width = 10;
age = 26.5;
Variable Assignment
Example:
int width = 60;
A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and the
underscore character.
The first character must be a letter or underscore.
Blank spaces cannot be used in variable names.
Special characters like #, $ are not allowed.
C keywords cannot be used as variable names.
Variable names are case sensitive.
Values of the variables can be numeric or alphabetic.
Variable type can be char, int, float, double, or void.
#include<conio.h>
void main()
Program Output:
I am 33 years old.
Types of Variables
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
void function1()
{
int x=10;//local variable
}
Global Variable
A variable that is declared outside the function or block is called a global variable. Any function
can change the value of the global variable. It is available to all the functions.
void function1()
{
int x=10;//local variable
}
Static Variable
A variable that is declared with the static keyword is called static variable.
If you call this function many times, the local variable will print the same value for each function
call, e.g, 11,11,11 and so on. But the static variable will print the incremented value in each
function call, e.g. 11, 12, 13 and so on.
Identifiers
An identifier is a collection of alphanumeric characters that begins either with an alphabetical
character or an underscore, which are used to represent various programming elements such as variables,
functions, arrays, structures, unions, labels, etc. An identifier can be composed of letters such as
uppercase, lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an
underscore.
Constants
Constants are the fixed values that are used in a program, and its value remains the same during
the entire execution of the program.
1. const keyword
2. #define preprocessor
1) const keyword
Output:
2) #define preprocessor
#include<stdio.h>
#include<conio.h>
#define LIMIT 5
void main()
getch();
Primary Constants
1. Numeric Constants
o Integer Constants
o Real Constants
2. Character Constants
o Single Character Constants
o String Constants
o Backslash Character Constants
Integer Constant
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
15, -265, 0, 99818, +25, 045, 0X6
Real constant
The numbers containing fractional parts like 99.25 are called real or floating points constant.
It simply contains a single character enclosed within ' ' (a pair of single quote). It is to be noted
that the character '8' is not the same as 8.
Example:
These are a sequence of characters enclosed in double quotes, and they may include letters,
digits, special characters, and blank spaces. It is again to be noted that "G" and 'G' are different -
because "G" represents a string as it is enclosed within a pair of double quotes whereas 'G'
represents a single character.
Example:
C supports some character constants having a backslash in front of it. The lists of backslash
characters have a specific meaning which is known to the compiler. They are also termed as
"Escape Sequence".
For Example:
\a beep sound
\b backspace
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\0 null
Secondary Constant
Array
Pointer
Structure
Union
Enum
Data Types
A data type specifies the type of data that a variable can store such as integer, floating, character,
etc.
There are the following data types in C language.
The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.
The memory size of the basic data types may change according to 32 or 64-bit operating system.
Declaration
After taking suitable variable names, they need to be assigned with a data type. This is how the
data types are used along with variables:
Example:
int age;
char letter;
The following table provides the details of standard integer types with their storage sizes and
value ranges −
Type Storage size Value range
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or
type in bytes.
The following table provide the details of standard floating-point types with storage sizes
and value ranges and their precision.
Type Storage size Value range Precision
Union These allow storing various data types in the same memory location. Programmers can
define a union with different members, but only a single member can contain a value at a
given time.
Pointers Which are used to access the memory and deal with their addresses.
Arrays Arrays a kind of data structure that can store a fixed-size sequential collection of elements
of the same type.
Enum Enumeration is a special data type that consists of integral constants, and each of them is
assigned with a specific name. "enum" keyword is used to define the enumerated data type.
Module 2
OPERATORS AND EXPRESSIONS
The symbols which are used to perform logical and mathematical operations in a C program
are called C operators.
These C operators join individual constants and variables to form expressions.
Operators, functions, constants and variables are combined together to form expressions.
Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant
and A + B * 5 is an expression.
TYPES OF C OPERATORS:
An operator is a symbol that operates on a value or a variable. C language offers many types
of operators. They are,
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
1. Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division etc on numerical values.
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =
= 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
c = a; // c is 5
printf("c = %d\n", c);
c += a; // c is 10
printf("c = %d\n", c);
c -= a; // c is 5
printf("c = %d\n", c);
c *= a; // c is 25
printf("c = %d\n", c);
c /= a; // c is 5
printf("c = %d\n", c);
c %= a; // c = 0
printf("c = %d\n", c);
getch();
}
Output
c=5
c = 10
c=5
c = 25
c=5
c=0
3. 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.
== Equal to 5 == 3 is evaluated to 0
getch();
}
Output
5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1
4. Logical Operators
#include <stdio.h>
void main()
{
int a = 5, b = 5, c = 10, result;
getch();
}
Output
(a == b) && (c > b) is 1
(a == b) && (c < b) is 0
(a == b) || (c < b) is 1
(a != b) || (c < b) is 0
!(a != b) is 1
!(a == b) is 0
5. Bitwise Operators
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
C programming has two operators increment ++ and decrement -- to change the value of
an operand (constant or variable) by 1.
getch();
}
Output
++a = 11
--b = 99
++c = 11.500000
--d = 99.500000
Here, the operators ++ and -- are used as prefixes. These two operators can also be used
as postfixes like a++ and a--.
7. Other Operators
Comma Operator
Comma operators are used to link related expressions together. For example:
int a, c = 5, d;
The sizeof operator
The sizeof is a unary operator that returns the size of data (constants, variables, array,
structure, etc).
#include <stdio.h>
void main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
getch();
}
Output
8. Conditional Operator
The conditional operator is also known as a ternary operator. The conditional statements are the
decision-making statements which depends upon the output of the expression. It is represented by
two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is
also a decision-making statement.
o In the above syntax, the expression1 is a Boolean condition that can be either true or false
value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.
#include <stdio.h>
void main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditi
onal operator
getch();
}
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
The Format specifier is a string used in the formatted input and output functions. The format
string determines the format of the input and output. The format string always starts with a '%'
character.
Format Description
specifier
%d or %i It is used to print the signed integer value where signed integer means
that the variable can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer
means that the variable can hold only positive value.
Decision Making
Decision making structures require that the programmer specifies one or more conditions to
be evaluated or tested by the program, along with a statement or statements to be executed if
the condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Show below is the general form of a typical decision-making structure found in most of the
programming languages −
C programming language provides the following types of decision-making statements.
1 if statement
2 if...else statement
An if statement can be followed by an optional else statement, which executes
when the Boolean expression is false.
3 nested if statements
You can use one if or else if statement inside another if or else if statement(s).
4 switch statement
A switch statement allows a variable to be tested for equality against a list of
values.
1. if Statement
The if statement is used to check some given condition and perform some operations depending
upon the correctness of that condition. It is mostly used in the scenario where we need to
perform the different operations for the different conditions. The syntax of the if statement is
given below.
Syntax:
if(expression)
{
//code to be executed
}
Flowchart:
Example:
#include <stdio.h>
#include <conio.h>
void main () {
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 ) {
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
getch();
}
Output:
a is less than 20;
value of a is : 10
2. if-else Statement
The if-else statement is used to perform two operations for a single condition. The if-else
statement is an extension to the if statement using which, we can perform two different
operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness
of the condition. Here, we must notice that if and else block cannot be executed simultaneously.
The syntax of the if-else statement is given below.
Syntax:
if(expression)
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}
Flowchart:
Example to check whether a number is even or odd using if-else statement.
#include<stdio.h>
#include<stdio.h>
void main()
{
int number;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0)
{
printf("%d is even number",number);
}
else
{
printf("%d is odd number",number);
}
getch();
}
The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario
where there are multiple cases to be performed for different conditions. In if-else-if ladder
statement, if a condition is true then the statements defined in the if block will be executed,
otherwise if some other condition is true then the statements defined in the else-if block will
be executed, at the last if none of the condition is true then the statements defined in the else
block will be executed. There are multiple else-if blocks possible.
Syntax:
if(condition1){
Flowchart:
Example Program to calculate the grade of the student according to the specified
marks.
#include <stdio.h>
#include<conio.h>
void main()
{
int marks;
printf("Enter your marks?");
scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{
printf("Congrats ! you scored grade A ...");
}
else if (marks > 60 && marks <= 85)
{
printf("You scored grade B + ...");
}
else if (marks > 40 && marks <= 60)
{
printf("You scored grade B ...");
}
else if (marks > 30 && marks <= 40)
{
printf("You scored grade C ...");
}
else
{
printf("Sorry you are fail ...");
}
}
Output:
4. nested-if
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2) {
// Executes when condition2 is true
}
}
Flowchart :
Example:
#include <stdio.h>
#include <conio.h>
void main()
{
int dig1, dig2, dig3;
printf("Enter three numbers: ");
scanf("%d%d%d", &dig1, &dig2, &dig3);
if(dig1 > dig2)
{
if(dig1 > dig3)
{
printf("dig1 is the maximum");
}
else
{
printf("dig3 is the maximum");
}
}
else
{
if(dig2 > dig3)
{
printf("dig2 is the maximum");
}
else
{
printf("dig3 is the maximum");
}
}
getch();
}
5.Switch Statement
Syntax :
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break statement
found in the case, all the cases will be executed present after the matched case. It is known
as fall through the state of C switch statement.
Flowchart:
Functioning of switch case statement:
First, the integer expression specified in the switch statement is evaluated. This value is then
matched one by one with the constant values given in the different cases. If a match is found,
then all the statements specified in that case are executed along with the all the cases present
after that case including the default statement. No two cases can have similar values. If the
matched case contains a break statement, then all the cases present after that will be skipped,
and the control comes out of the switch. Otherwise, all the cases following the matched case
will be executed.
Example:
include <stdio.h>
include <conio.h>
void main()
{
char operator;
int num1,num2;
printf(“\n Enter the operator (+, -, *, /):”);
scanf(“%c”,&operator);
printf(“\n Enter the Two numbers:”);
scanf(“%d%d”,&num1,&num2);
switch (operator)
{
case ‘+’:
printf(“%d+%d=%d”,num1,num2,num1+num2);
break;
case ‘-‘:
printf(“%d-%d=%d”,num1,num2,num1-num2);
break;
case ‘*’:
printf(“%d*%d=%d”,num1,num2,num1*num2);
break;
case ‘/’:
printf(“%d / %d = %d”,num1,num2,num1/num2);
break;
default:
printf(“\n Enter a valid operator only”);
break;
getch();
}
CONTROL STATEMENTS
The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. There are three types of loops used in the C language.
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow
of the program so that instead of writing the same code again and again, we can repeat the same
code for a finite number of times. For example, if we need to print the first 10 natural numbers
then, instead of using the printf statement 10 times, we can print inside a loop which runs up
to 10 iterations.
Advantage of loops in C
2) Using loops, we do not need to write the same code again and again.
3) Using loops, we can traverse over the elements of data structures (array or linked lists).
Types of C Loops
1. do-while loop
The do-while loop continues until a given condition satisfies. It is also called post tested loop.
It is used when it is necessary to execute the loop at least once.
do{
//code to be executed
}while(condition);
Example
#include<stdio.h>
void main(){
int i=1;
do{
printf("%d \n",i);
i++;
}while(i<=10);
getch();
}
The do-while loop will run infinite times if we pass any non-zero value as the conditional
expression.
do{
//statement
}while(1);
2. while loop
The while loop in c is to be used in the scenario where we don't know the number of iterations
in advance. The block of statements is executed in the while loop until the condition specified
in the while loop is satisfied. It is also called a pre-tested loop.
while(condition){
//code to be executed
}
Flowchart of while loop in C
Example
#include<stdio.h>
void main(){
int i=1;
while(i<=10){
printf("%d \n",i);
i++;
}
getch();
}
o A conditional expression is used to check the condition. The statements defined inside
the while loop will repeatedly execute until the given condition fails.
o The condition will be true if it returns 0. The condition will be false if it returns any
non-zero number.
o In while loop, the condition expression is compulsory.
o Running a while loop without a body is possible.
o We can have more than one conditional expression in while loop.
o If the loop body contains only one statement, then the braces are optional.
If the expression passed in while loop results in any non-zero value then the loop will run the
infinite number of times.
while(1){
//statement
}
3. for loop
The for loop is used in the case where we need to execute some part of the code until the given
condition is satisfied. It is better to use for loop if the number of iteration is known in advance.
The syntax of for loop:
for(initialization;condition;incr/decr){
//code to be executed
}
Example
#include<stdio.h>
void main(){
int i;
for(i=1;i<=10;i++){
printf("%d \n",i);
}
getch();
}
Loop body
The braces {} are used to define the scope of the loop. However, if the loop contains only one
statement, then we don't need to use braces. A loop without a body is possible. The braces work
as a block separator, i.e., the value variable declared inside for loop is valid only for that block
and not outside.
#include<stdio.h>
void main ()
{
for(;;)
{
printf("welcome");
}
getch();
}
break statement
The break is a keyword in C which is used to bring the program control out of the loop. The
break statement is used inside loops or switch statement. The break statement breaks the loop
one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. The break statement in C can be used in the following two scenarios:
Syntax:
Example
#include<stdio.h>
void main ()
{
int i;
for(i = 0; i<10; i++)
{
printf("%d ",i);
if(i == 5)
break;
}
printf("came outside of loop i = %d",i);
getch();
}
Output
continue statement
The continue statement in C language is used to bring the program control to the beginning
of the loop. The continue statement skips some lines of code inside the loop and continues with
the next iteration. It is mainly used for a condition so that we can skip some code for a particular
condition.
Syntax:
//loop statements
continue;
//some lines of the code which is to be skipped
Example
#include<stdio.h>
int main(){
int i=1;//initializing a local variable
//starting a loop from 1 to 10
for(i=1;i<=10;i++){
if(i==5){//if value of i is equal to 5, it will continue the loop
continue;
}
printf("%d \n",i);
}//end of for loop
return 0;
}
Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.
Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc. It also has the capability to
store the collection of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed by using its index
number.
C array is beneficial if you have to store similar elements. For example, if we want to store
the marks of a student in 6 subjects, then we don't need to define different variables for the
marks in the different subject. Instead of that, we can define an array which can store the
marks in each subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required
to access the elements of the array.
Properties of Array
The array contains the following properties.
• Each element of an array is of same data type and carries the same size, i.e., int = 4
bytes.
• Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location.
• Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.
Advantages
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList.
Declaration of Array
data_type array_name[array_size];
Example
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
Initialization of Array
The simplest way to initialize an array is by using the index of each element. We can
initialize each element of the array by using the index.
Example
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
In such case, there is no requirement to define the size. So it may also be written as the
following code.
int marks[]={20,30,40,50,60};
Array example:
#include<stdio.h>
void main(){
int i=0;
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
getch();
data_type array_name[rows][columns];
Example:
int twodimen[4][3];
Initialization of 2D Array
In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D arrays. We
will have to define at least the second dimension of the array. The two-dimensional array can
be declared and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
#include<stdio.h>
void main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
}//end of j
}//end of i
getch();
}
Module 3
Concept of modular programming
The concept of modular programming originated in the 1960s to help users. Programmers
began to divide the more extensive programs into smaller parts. It is the most convenient
programming method.
Modular programming is the process of subdividing a computer program into separate sub-
programs. A module is a separate software component. It can often be used in a variety of
applications and functions with other components of the system.
• Some programs might have thousands or millions of lines and to manage such
programs it becomes quite difficult as there might be too many of syntax errors or
logical errors present in the program, so to manage such type of programs concept of
modular programming approached.
• Each sub-module contains something necessary to execute only one aspect of the
desired functionality.
All the object-oriented programming languages like C++, Java, etc., are modular
programming languages.
• Ease of Use :This approach allows simplicity, as rather than focusing on the entire
thousands and millions of lines code in one go we can access it in the form of
modules. This allows ease in debugging in the code.
• Reusability :It allows the user to reuse the functionality with a different interface
without typing the whole program again.
• There is a need for extra time and budget for a product in modular programming.
• It is a challenging task to combine all the modules.
• Careful documentation is required so that other program modules are not affected.
• Some modules may partly repeat the task performed by other modules. Hence,
Modular programs need more memory space and extra time for execution.
Functions
In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program.
Advantages of functions
• By using functions, we can avoid rewriting same logic/code again and again in a
program.
• We can call C functions any number of times in a program and from any place in a
program.
• We can track a large C program easily when it is divided into multiple functions.
Function Aspects
• Function declaration
A function must be declared globally in a c program to tell the compiler about the function
name, function parameters, and return type.
• Function call
Function can be called from anywhere in the program. The parameter list must not differ in
function calling and function declaration. We must pass the same number of parameters as it
is declared in the function declaration.
• Function definition
It contains the actual statements which are to be executed. It is the most important aspect to
which the control comes when the function is called. Here, we must notice that only one
value can be returned from the function.
The syntax of creating function is given below:
//code to be executed
Types of Functions
• User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
Return Value
A function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
void hello(){
printf("hello c");
If you want to return any value from the function, you need to use any data type such as int,
long, char, etc. The return type depends on the value to be returned from the function.
int get(){
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int. If you want to
return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type
of the method.
A function may or may not accept any argument. It may or may not return any value. Based
on these facts, There are four different aspects of function calls.
#include<stdio.h>
#include<conio.h>
void sum();
void main()
sum();
void sum()
int a,b;
scanf("%d %d",&a,&b);
#include<stdio.h>
void sum(int, int);
void main()
int a,b,result;
scanf("%d %d",&a,&b);
sum(a,b);
Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example,
printf is a library function used to print on the console. The library functions are created by
the designers of compilers. All C standard library functions are defined inside the different
header files saved with the extension .h. We need to include these header files in our program
to make use of the library functions defined in such header files. For example, To use the
library functions such as printf/scanf we need to include stdio.h in our program which is a
header file that contains all the library functions regarding standard input/output.
Example
int n = 10;
int *p=&n; // Variable p of type pointer is pointing to the address of the variable n of type integer.
Normal variable
Whenever we declare a variable in c, it takes some space in memory and each memory has a unique
address.
#include<stdio.h>
int main()
{
int n, *p;
n=10;
p=&n;
printf("\nValue : %d", n); // print value of n.
printf("\nAddress %p", p); //print address of n
printf("\nValue : %d", *p); // print value of n.
return 0;
}
Sample Output:
Value : 10
Address 0x7ffd90c6b3b4
Value: 10
Advantages of pointer
1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees,
etc. and used with arrays, structures, and functions.
3) It makes you able to access any memory location in the computer's memory.
Usage of pointer
In c language, we can dynamically allocate memory using malloc() and calloc() functions where
the pointer is used.
Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.
The Address of (&) and dereference (*) operators with the pointers
It is an "address of" operator which returns the address of any variable. The
statement &var1 represents the address of var1 variable. Since it can be used anywhere but with
the pointers, it is required to use for initializing the pointer with the address of another variable.
It is used for two purposes with the pointers 1) to declare a pointer, and 2) get the value of a
variable using a pointer.
Example:
#include <stdio.h>
int main(void)
{
//normal variable
int num = 100;
//pointer variable
int *ptr;
//pointer initialization
ptr = #
//printing the value
printf("value of num = %d\n", *ptr);
//printing the addresses
printf("Address of num: %x\n", &num);
printf("Address of ptr: %x\n", &ptr);
return 0;
}
Output:
value of num = 100
Address of num: 9505c134
Address of ptr: 9505c138
Example:
#include<stdio.h>
void main ()
int a = 10;
int *p;
int **pp;
printf("value stored at p: %d\n",*p); // value stoted at the address contained by p i.e. 10 will be
printed
printf("value stored at pp: %d\n",**pp); // value stored at the address contained by the pointer
stored at pp
Output:
address of a: d26a8734
address of p: d26a8738
value stored at p: 10
value stored at pp: 10
#include <stdio.h>
int main()
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a
and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters
do not change by changing the formal parameters in call by value, a = 10, b = 20
int temp;
temp = a;
a=b;
b=temp;
}
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Call by reference
o In call by reference, the address of the variable is passed into the function call as the actual
parameter.
o The value of the actual parameters can be modified by changing the formal parameters
since the address of the actual parameters is passed.
o In call by reference, the memory allocation is similar for both formal parameters and actual
parameters. All the operations in the function are performed on the value stored at the
address of the actual parameters, and the modified value gets stored at the same address.
#include <stdio.h>
int main()
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in
main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do
change in call by reference, a = 10, b = 20
int temp;
temp = *a;
*a=*b;
*b=temp;
Output:
Before swapping the values in main a = 10, b = 20
1 A copy of the value is passed into the function An address of value is passed into the function
2 Changes made inside the function is limited to Changes made inside the function validate
the function only. The values of the actual outside of the function also. The values of the
parameters do not change by changing the actual parameters do change by changing the
formal parameters. formal parameters.
3 Actual and formal arguments are created at the Actual and formal arguments are created at the
different memory location same memory location
Recursion
Recursion is the process which comes into existence when a function calls itself to work on a
smaller problem. Any function which calls itself is called recursive function, and such function
calls are called recursive calls. Recursion involves several numbers of recursive calls. However, it
is important to impose a termination condition of recursion.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be
defined in terms of similar subtasks. For Example, recursion may be applied to sorting, searching,
and traversal problems.
Generally, iterative solutions are more efficient than recursion since function call is always
overhead. Any problem that can be solved recursively, can also be solved iteratively. However,
some problems are best suited to be solved by the recursion, for example, tower of Hanoi,
Fibonacci series, factorial finding, etc.
#include <stdio.h>
void main()
int n,f;
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
int fact(int n)
if (n==0)
{
return 0;
else if ( n == 1)
return 1;
else
return n*fact(n-1);
Output
factorial = 120
Dynamic memory allocation
The concept of dynamic memory allocation in c language enables the C programmer to allocate
memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h
header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
tDifference between static memory allocation and dynamic memory allocation.he number whose
factori you want to calculate?5
fact
memory can't be increased while executing memory can be increased while executing
program. program.
1. malloc() function
ptr=(cast-type*)malloc(byte-size)
2. calloc() function
ptr=(cast-type*)calloc(number, byte-size)
3. realloc() function
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc()
function. In short, it changes the memory size.
ptr=realloc(ptr, new-size)
4. free() function
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
free(ptr)
orial = 120 nter the number whose factorial you want to calcula
Module 4
Strings
The string can be defined as the one-dimensional array of characters terminated by a null ('\0').
The character array or the string is used to manipulate text such as word or sentences. The
termination character ('\0') is important in a string since it is the only way to identify where the
string ends. When we define a string as char s[10], the character s[10] is implicitly initialized with
the null in the memory.
1. By char array
2. By string literal
While declaring string, size is not mandatory. So we can write the above code as given below:
We can also define the string by the string literal in C language. For example
char ch[]="hello";
In such case, '\0' will be appended at the end of the string by the compiler.
When the above code is compiled and executed, it produces the following result −
Greeting message: Hello
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
#include <stdio.h>
#include <string.h>
void main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type member N;
};
struct employee
{ int id;
char name[20];
float salary;
};
The following image shows the memory allocation of the structure employee that is defined in the
above example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure.
To declare the structure variable by struct keyword. It should be declared within the main function.
struct employee
{ int id;
char name[50];
float salary;
};
Now write given code inside the main() function.
struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the structure.
.
2nd way:
Another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
}e1; //declaring e1 variable for structure
void main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Ram");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
getch();
}
Output:
employee 1 id : 101
employee 1 name : Ram
Union
Union can be defined as a user-defined data type which is a collection of different variables of
different data types in the same memory location. The union can also be defined as many members,
but only one member can contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same memory location.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program.
union {
member definition;
member definition;
...
member definition;
At the end of the union's definition, before the final semicolon, you can specify one or more union
variables but it is optional. Here is the way you would define a union type named Data having
three members i, f, and str −
union Data {
int i;
float f;
char str[20];
} data;
Accessing Union Members
To access any member of a union, we use the member access operator (.). The
member access operator is coded as a period between the union variable name and the
union member that we wish to access. You would use the keyword union to define
variables of union type. The following example shows how to use unions in a program −
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
void main( ) {
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
Struct Union
The struct keyword is used to define a structure. The union keyword is used to define union.
When the variables are declared in a structure, the compiler When the variable is declared in the union, the compiler
allocates memory to each variable member. The size of a allocates memory to the largest size variable member. The
structure is equal or greater to the sum of the sizes of each data size of a union is equal to the size of its largest data member
member. size.
Each variable member occupied a unique memory space. Variables members share the memory space of the largest
size variable.
Changing the value of a member will not affect other variables Changing the value of one member will also affect other
members. variables members.
Each variable member will be assessed at a time. Only one variable member will be assessed at a time.
We can initialize multiple variables of a In union, only the first data member can be initialized.
structure at a time.
All variable members store some value at any point in the Exactly onlyonedatamember stores avalue at any particular
program. instance in the program.
The structure allows initializing multiple Union allows initializing only one variable member at
variable members atonce. once.
It is used to store different data type values. It is used for storing one at a time from different data
typevalues.
It allows accessing and retrieving any data member at a time. It allows accessing and retrieving any one data member
at a time.
File Handling in C
File Handling is the storing of data in a file using a program. In C programming language, the programs
store results, and other data of the program to a file using file handling in C.
File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program.
There are many functions in the C library to open, read, write, search and close the file.
We must open a file before it can be read, write, or update. The fopen() function is used to
The file name (string). If the file is stored at some specific location, then we must mention the path
at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext".
Mode Description
o It sets up a character pointer which points to the first character of the file.
#include<stdio.h>
void main( )
{
FILE *fp ;
char ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc ( fp ) ;
if ( ch == EOF )
break ;
printf("%c",ch) ;
}
fclose (fp ) ;
}
Closing File: fclose()
The fclose() function is used to close a file. The file must be closed after performing all the
The fscanf() function is used to read set of characters from file. It reads a word from the
Syntax:
Example:
#include <stdio.h>
void main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}