Professional Documents
Culture Documents
Complete Note C Programming
Complete Note C Programming
Computer based problem solving is a systematic process of designing, implementing and using programming tools
during the problem solving stage. This method enables the computer system to be more intuitive with human logic
than machine logic. Final outcome of this process is software tools which is dedicated to solve the problem under
consideration. Software is just a collection of computer programs and programs are a set of instructions which
guides computer’s hardware. These instructions need to be well specified for solving the problem. After its creation,
the software should be error free and well documented. Software development is the process of creating such
software, which satisfies end user’s requirements and needs.
The following six steps must be followed to solve a pr oblem using computer.
Problem Analysis
Coding
Program Documentation
Problem Analysis
Problem: -Problem is defined as the difference between an existing situation and a desired situation.
-If a problem is solved by using machine called computer, then such process is called Problem Solving using
Computer.
-Before solving any problem you must first try to solve it manually. Unless you have a clear understanding of
problem and the steps that should be followed to reach the solution you cannot solve the problem using machine. So,
first try to get clear idea about the problem.
Characteristics of Algorithm
1)Each and every instruction should be precise and unambiguous (clear)
2)Each instruction should be such that it can be performed in a finite time
3)One or more instruction should not be repeated infinitely. This ensures that the algorithm will ultimately terminate
4)After performing the instructions, that is after the algorithm terminates, the desired results must be obtained.
Problem : The attendance sheet of your class is given to you. Only those students with attendance of 70% or above
are qualified to att end final examination (for them print ‘Q’ ) else print ‘NQ’. Write an algorithm to check whether
a student is Qualified or not [Assume Total days of class as ‘TotalClass’]
Hint: Assume the total days a student is present as ‘TotalPresent’ Calculate the PresentPercentage of student :
(TotalPresent / TotalClass)*100% If (PresentPercentage >= 70 ) print ‘Q’ else print ‘NQ’
Solution Step1: Start
Step2: Get the attendance of a student as ‘TotalPresent’
Step3: Calculate the ‘PresentPercentage’ as (TotalPresent/TotalClass) * 100%
Step4: If (PresentPercentage >= 70% ) print ‘Q’ Else print ‘NQ’
Step5: Stop
Problem: Write an algorithm to check whether a number entered by user is odd or even [075 Ashwin]
[Hint: If the number is divisible by 2 then its even else it is odd]
Importance of Algorithm:
a)Gives the idea about problem and solution
b)Easy to implement an algorithm rather than starting from scratch
c)Proper Utilization of resources
d)Writing algorithm improves thinking and reasoning abilities.
Flowchart
-A flowchart is a pictorial representation of an algorithm that uses boxes of different shapes to denote different
types of instructions.
-The actual instructions are written within these boxes using clear and concise statements.
-These boxes are connected by solid lines having arrow marks to indicate the flow of operation.
Normally, an algorithm is first represented in the form of a flowchart and the flowchart is then expressed in some
programming language to prepare a computer program.
Since a flowchart shows the flow of operations in pictorial form, any error in the logic of the procedure can be
detected more easily.
Terminal: The terminal symbol is used to indicate the beginning (START) and ending (STOP). It is the first symbol
and last symbol in the program logic.
Input/Output: If there is a program instruction to input data from a disk, cardreader, or any other type of input
device, that step will be indicated in the flowchart with an input/output symbol. Similarly, all output instructions
whether it is output on a printer, magnetic tape, terminal screen or any output device, are indicated in the flowchart
with an input/output symbol.
Processing: A processing symbol is used in a flowchart to represent arithmetic and data movement instructions.
Adding, subtracting, multiplying and dividing are shown by a processing symbol.
Flowlines: Flow lines with arrowheads are used to indicate the flow of operations. The normal flow of flowchart is
from top to bottom and left to right. Flow lines should not cross each other.
Decision: The decision symbol is used in a flowchart to indicate a point at which a decision has to be made and a
branch to one of two or more alternative points is possible. The criteria for making the decision should be indicated
clearly within the decision box.
Connector: Whenever a flowchart becomes complex enough that the direction of flowlines is confusing or it
spreads over more than one page, it is useful to utilize the connector symbol
Problem: A student appeared in semester examination. There were total 5 subjects and the total marks of each
subject was 100. Take the input data(marks of each subject), calculate the percentage and display output using
Flowchart.
[Hint: To calculate the percentage : First calculate total marks obtained ‘TotalMarksObtained’ (TMO) Then
calculate the total full marks ‘TotalFullMarks’ (TFM) Now calculate percentage as : Percentage = (TMO / TFM) *
100% ]
Problem: Draw a flowchart to check whether a number entered by user is even or odd. (assignment no .1)
The compilation process can be divided into four steps, i.e., Pre-processing, Compiling, Assembling, and Linking.
Pre-processing: 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.
Compiling: The compiler converts the pre-processed code into assembly code.
Assembling: The assembly code is converted into object code by using an assembler.If the name of the source file is
'hello.c', then the name of the object file would be 'hello.obj'.
Linking: Mainly, all the programs written in C use library functions.The main working of the linker is to combine
the object code of library files with the object.
Execution: After the creation of an object code, the linker creates the executable file. The loader will then load the
executable file for the execution.
Testing
-Testing is the process of reviewing and executing a program with the intent of detecting errors.
-Testing can be done manually and computer based testing.
-Manual testing includes code inspection by the programmer, code inspection by a test group and a review by a peer
group.
-Computer based testing is done by computer with the help of compiler.
Programming Documentation
Any written text, illustrations or video that describe a software or program to its users is called programming
documentation. User can be anyone from a programmer, system analyst and administrator to end user.
These are some guidelines for creating the documents −
1)Documentation should be from the point of view of the reader
2)Document should be unambiguous
3)There should be no repetition
4)Industry standards should be used
5)Documents should always be updated
Advantages of Documentation These are some of the advantages of providing program documentation –
1)Keeps track of all parts of a software or program
2)Maintenance is easier
3)Programmers other than the developer can understand all aspects of software
4)Improves overall quality of the software.
Unit -2
2.1 Historical Development of C
2.2 Importance of C
2.3 Basic Structure of C Programs
2.4 Executing a C Program
History of C language
The base or father of programming languages is ‘ALGOL.’ It was first introduced in 1960. ‘ALGOL’ was used on a
large basis in European countries. ‘ALGOL’ introduced the concept of structured programming to the developer
community. In 1967, a new computer programming language was announced called as ‘BCPL’ which stands for
Basic Combined Programming Language. BCPL was designed and developed by Martin Richards, especially for
writing system software. This was the era of programming languages. Just after three years, in 1970 a new
programming language called ‘B’ was introduced by Ken Thompson that contained multiple features of ‘BCPL.’
This programming language was created using UNIX operating system at AT&T and Bell Laboratories. Both the
‘BCPL’ and ‘B’ were system programming languages.
In 1972, a great computer scientist Dennis Ritchie created a new programming language called ‘C’ at the Bell
Laboratories. It was created from ‘ALGOL’, ‘BCPL’ and ‘B’ programming languages. ‘C’ programming language
contains all the features of these languages and many more additional concepts that make it unique from other
languages.
‘C’ is a powerful programming language which is strongly associated with the UNIX operating system. Even most
of the UNIX operating system is coded in ‘C’. Initially ‘C’ programming was limited to the UNIX operating system,
but as it started spreading around the world, it became commercial, and many compilers were released for cross-
platform systems. Today ‘C’ runs under a variety of operating systems and hardware platforms. As it started
evolving many different versions of the language were released. At times it became difficult for the developers to
keep up with the latest version as the systems were running under the older versions. To assure that ‘C’ language
will remain standard, American National Standards Institute (ANSI) defined a commercial standard for ‘C’ language
in 1989. Later, it was approved by the International Standards Organization (ISO) in 1990. ‘C’ programming
language is also called as ‘ANSI C’.
Languages such as C++/Java are developed from ‘C’. These languages are widely used in various technologies.
Thus, ‘C’ forms a base for many other languages that are currently in use.
Why is C so popular
Advantages of C
Disadvantages of C
Difficult to debug.
C allows a lot of freedom in writing code, and that is why you can put an empty line or white space
anywhere in the program. And because there is no fixed place to start or end the line, so it isn't easy to read
and understand the program.
C compilers can only identify errors and are incapable of handling exceptions (run-time errors).
C provides no data protection.
It also doesn't feature the reusability of source code extensively.
It does not provide strict data type checking (for example, an integer value can be passed for floating
datatype).
‘C’ is a structured programming language in which program is divided into various modules. Each module can be
written separately and together it forms a single ‘C’ program. This structure makes it easy for testing, maintaining
and debugging processes.
‘C’ contains 32 keywords, various data types and a set of powerful built-in functions that make programming very
efficient.
Another feature of ‘C’ programming is that it can extend itself. A ‘C’ program contains various functions which are
part of a library. We can add our features and functions to the library. We can access and use these functions
anytime we want in our program. This feature makes it simple while working with complex programming.
Various compilers are available in the market that can be used for executing programs written in this language.
It is a highly portable language which means programs written in ‘C’ language can run on other machines. This
feature is essential if we wish to use or execute the code on another computer.
Clang compiler
MinGW compiler (Minimalist GNU for Windows)
Portable ‘C’ compiler
Turbo C
C Basic Commands
Following are the basic commands in C programming language:
The following code is one of the simplest C programs that will help us the basic syntax structure of a C program.
Example:
#include <stdio.h>
int main() {
int a = 10;
printf("%d", a);
return 0;
Output:
10
Structure of a C program
After the above example, we can formally assess the structure of a C program. By structure, it is meant that any
program can be written in this structure only. Writing a C program in any other structure will hence lead to a
Compilation Error. The structure of a C program is as follows:
Components of a C Program:
The first and foremost component is the inclusion of the Header files in a C program.
All lines that start with ## are processed by a preprocessor which is a program invoked by the compiler.
In the above example, the preprocessor copies the preprocessed code of stdio.h to our file. The .h files are called
header files in C.
Some of the C Header files:
stdlib.h – Defines numeric conversion functions, pseudo-random network generator, and memory allocation
It is the entry point of a C program and the execution typically begins with the first line of the main().
The empty brackets indicate that the main doesn’t take any parameter.
The int that was written before the main indicates the return type of main().
The value returned by the main indicates the status of program termination. 3. Bo
The body of a function in the C program refers to statements that are a part of that function.
A pair of curly brackets define the body of a function. All functions must start and end with curly brackets.
4. Statement –
Statements are the instructions given to the compiler. In C, a statement is always terminated by a semicolon (;).
In this particular case, we use printf() function to instruct the compiler to display “Hello World” text on the screen.
In order to execute the above program, we need to first compile it using a compiler and then we can run the
generated executable. There are online IDEs available for free, that can be used to start development in C without
installing a compiler.
1. Windows : There are many free IDEs available for developing programs in C like Code Blocks and Dev-CPP.
IDEs provide us with an environment to develop code, compile it and finally execute it. We strongly recommend
Code Blocks.
2. Linux: GCC compiler comes bundled with Linux which compiles C programs and generates executables for us to
run. Code Blocks can also be used with Linux.
3. macOS : macOS already has a built-in text editor where you can just simply write the code and save it with a
“.c” extension.
Application of C
Operating systems: C is widely used for developing operating systems such as Unix, Linux, and Windows.
Embedded systems: C is a popular language for developing embedded systems such as microcontrollers,
microprocessors, and other electronic devices.
System software: C is used for developing system software such as device drivers, compilers, and
assemblers.
Networking: C is widely used for developing networking applications such as web servers, network
protocols, and network drivers.
Database systems: C is used for developing database systems such as Oracle, MySQL, and PostgreSQL.
Gaming: C is often used for developing computer games due to its ability to handle low-level hardware
interactions.
Artificial Intelligence: C is used for developin g artificial intelligence and machine learning applications
such as neural networks and deep learning algorithms.
Scientific applications: C is used for developing scientific applications such as simulation software and
numerical analysis tools.
Financial applications: C is used for developing financial applications such as stock market analysis and
trading systems.
Structure
Unit -3
3.1 Character Set
3.2 Identifiers & Keywords
3.3 Data Types and modifier
3.4 Constants, Variables
3.5 Declarations and initialization of variables
3.6 Escape Sequences
3.7 Preprocessors Directives
3.8 typedef statement
3.9 Symbolic Constants
A compiler always ignores the use of characters, but it is widely used for
formatting the data. Following is the character set in ‘C’ programming. A
character set in is divided into the following types:
A compiler always ignores the use of characters, but it is widely used for
formatting the data. Following is the character set in ‘C’ programming:
All the lowercase and uppercase characters from A to Z.
All the digits from 0 to 9.
Such as Blank space, Newline, Carriage return, and Horizontal tab.
Special Characters
Keywords and Identifiers:
In ‘C’ every word can be either a keyword or an identifier.
Keywords have fixed meanings, and the meaning cannot be changed. They act as
a building block of a ‘C’ program. There are a total of 32 keywords in ‘C’.
Keywords are written in lowercase letters.
An identifier is nothing but a name assigned to an element in a program.
Example: name of a variable, function, etc.
Identifiers are the user-defined names consisting of the ‘C’ standard character set.
As the name says, identifiers are used to identify a particular element in a
program.
Each identifier must have a unique name.
Following rules must be followed for identifiers:
The first character must always be an alphabet or an underscore.
It should be formed using only letters, numbers, or underscore.
A keyword cannot be used as an identifier.
It should not contain any white space character.
The name must be meaningful.
Summary:
A token is the smallest unit in a program.
A keyword is reserved words by language.
There is a total of 32 keywords.
An identifier is used to identify elements of a program.
Tokens in C
A token in C can be defined as the smallest individual element of the C
programming language that is meaningful to the compiler. It is the basic
component of a C program.
Types of Tokens in C
The tokens of C language can be classified into six types based on the functions
they are used to perform. The types of C tokens are as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. C Token – Keywords
The keywords are pre-defined or reserved words in a programming language.
Each keyword is meant to perform a specific function in a program. Since
keywords are referred names for a compiler, they can’t be used as variable names
because by doing so, we are trying to assign a new meaning to the keyword which
is not allowed. You cannot redefine keywords. However, you can specify the text
to be substituted for keywords before compilation by using C preprocessor
directives. C language supports 32 keywords which are given below:
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
2. C Token – Identifiers
Identifiers are used as the general terminology for the naming of variables,
functions, and arrays. These are user-defined names consisting of an arbitrarily
long sequence of letters and digits with either a letter or the underscore(_) as a
first character. Identifier names must differ in spelling and case from any
keywords. You cannot use keywords as identifiers; they are reserved for special
use. Once declared, you can use the identifier in later program statements to
refer to the associated value. A special kind of identifier called a statement label
can be used in goto statements.
3. C Token – Constants
The constants refer to the variables with fixed values. They are like normal
variables but with the difference that their values cannot be modified in the
program once they are defined. Constants in C refer to fixed values that program
cannot change during the time of execution. Constants are also known as literals. A
constant can be of any data type like character constant, integer constant, string
constant etc.
For Example : 'A', 1234, 123.5, "TechCrashCourse"
C Constants are like normal variables, the only difference is, their values cannot be
changed by the program once they are defined.
Types of Constants in C
Integer constants
Character Constants
Backslash Character Constants
Integer Constants
Floating Point Constants
String Constants
4. C Token – Strings
Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in
double quotes. Whereas, a character is enclosed in single quotes in C and C++.
Examples of String
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
6. C Token – Operators
Operators are symbols that trigger an action when applied to C variables and
other objects. The data items on which operators act are called operands.
Depending on the number of operands that an operator can act upon, operators
can be classified as follows:
Unary Operators: Those operators that require only a single operand to act upon
are known as unary operators. For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are
called binary operators. Binary operators can further are classified into:
Arithmetic operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operator
Ternary Operator: The operator that requires three operands to act upon is called
the ternary operator. Conditional Operator(?) is also called the ternary operator.
Variables:
A variable is an identifier that is used to store some value.
Constants can never change at the time of execution.
Variables can change during the execution of a program and update the
value stored inside it.
A single variable can be used at multiple locations in a program.
A variable name must be meaningful.
It should represent the purpose of the variable.
Example: Height, age, are the meaningful variables that represent the
purpose it is being used for.
Height variable can be used to store a height value.
The age variable can be used to store the age of a person.
A variable must be declared first before it is used somewhere inside the
program.
A variable name is formed using characters, digits, and an underscore.
Local variable in C
A local variable is declared inside a function.
A local variable is visible only inside their function, only statements inside
function can access that local variable.
Local variables are declared when control enters a function and local
variables gets destroyed, when control exits from function.
Global variable in C
Global variables are declared outside of any function.
A global variable is visible to any every function and can be used by any
piece of code.
Unlike local variable, global variables retain their values between function
calls and throughout the program execution.
Following are the rules that must be followed while creating a variable:
A variable name should consist of only characters, digits, and an
underscore.
A variable name should not begin with a number.
A variable name should not consist of white space.
A variable name should not consist of a keyword.
‘C’ is a case-sensitive language that means a variable named ‘age’ and
‘AGE’ are different.
Data types: ‘C’ provides various data types to make it easy for a programmer to
select a suitable data type as per the requirements of an application. Following
are the three data types:
Primitive data types
Derived data types
User-defined data types
Modifier
Modifiers are keywords in c which changes the meaning of basic data type in c. It
specifies the amount of memory space to be allocated for a variable. Modifiers are
prefixed with basic data types to modify the memory allocated for a variable.
There are five data type modifiers in C Programming Language:
long
short
signed
unsigned
Basic Syntax
OR
where,
Note 1: The Data type and the Value used to store in the Variable must match.
There are few conventions needed to be followed while declaring and assigning
values to the Variables –
Types of Initialization
1. Static Initialization –
In this method, the variable is assigned a value in advance. Here, the values are
assigned in the declaration statement. Static Initialization is also known as Explicit
Initialization.
Example –
int a;
a = 5;
int b = 10;
int x = 4, y = 5;
2. Dynamic Initialization –
In this method, the variable is assigned a value at the run-time. The value is either
assigned by the function in the program or by the user at the time of running the
program. The value of these variables can be altered every time the program runs.
Dynamic Initialization is also known as Implicit Initialization.
Example –
int speed;
scanf("%d", &speed);
Escape Sequence in C
An escape sequence in C language is a sequence of characters that doesn't
represent itself when used inside string literal or character.
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\? Question Mark
\0 Null
#include<stdio.h>
int main(){
int number=50;
printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
return 0; }
Output:
You
are
learning
'c' language
"Do you know C language"
Preprocessors Directives
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution
tool and it instructs the compiler to do required pre-processing before the actual
compilation. We'll refer to the C Preprocessor as CPP.
The C preprocessor is a macro preprocessor (allows you to define macros) that
transforms your program before it is compiled. These transformations can be the
inclusion of header files, macro expansions, etc.
All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin in
the first column. The following section lists down all the important preprocessor
directives −
2 #include
Inserts a particular header from another file.
3 #undef
Undefines a preprocessor macro.
4 #ifdef
Returns true if this macro is defined.
5 #ifndef
Returns true if this macro is not defined.
6 #if
Tests if a compile time condition is true.
7 #else
The alternative for #if.
8 #elif
#else and #if in one statement.
9 #endif
Ends preprocessor conditional.
10 #error
Prints error message on stderr.
11 #pragma
Issues special commands to the compiler, using a standardized
method.
C Macros
1. Object-like Macros
2. Function-like Macros
Object-like Macros
#define PI 3.14
Here, PI is the macro name which will be replaced by the value 3.14.
Function-like Macros
C Predefined Macros
typedef statement
The typedef is a keyword that is used to provide existing data types with a new name. The C typedef
keyword is used to redefine the name of already existing data types.
When names of datatypes become difficult to use in programs, typedef is used with user-defined
datatypes, which behave similarly to defining an alias for commands.
C typedef Syntax
typedef existing_name alias_name;
After this declaration, we can use the alias_name as if it were the real existing_name in out C program.
Example of typedef in C
typedef long long ll;
#include <stdio.h>
// Driver code
int main()
ll var = 20;
printf("%ld", var);
return 0;
Output
20
Use of typedef in C
Following are some common uses of the typedef in C programming:
The typedef keyword gives a meaningful name to the existing data type which helps other users to
understand the program more easily.
It can be used with structures to increase code readability and we don’t have to type struct repeatedly.
The typedef keyword can also be used with pointers to declare multiple pointers in a single statement.
1. typedef struct
typedef can also be used with structures in the C programming language. A new data type can be
created and used to define the structure variable.
// C program to implement
#include <stdio.h>
#include <string.h>
char name[50];
char branch[50];
int ID_no;
} stu;
// Driver code
int main()
{
stu st;
st.ID_no = 108;
return 0;
Output
ID_no: 108
Example:
In the above statement var, var1, and var2 are declared as pointers of type int which helps us to declare
multiple numbers of pointers in a single statement.
C
// C program to implement
#include <stdio.h>
// Driver code
int main()
ptr var;
*var = 20;
return 0;
Output
Value of var is 20
Example:
#include <stdio.h>
// Driver code
int main()
return 0;
Output
10 20 30 40
C typedef vs #define
The following are the major difference between the typedef and #define in C:
#define is capable of defining aliases for values as well, for instance, you can
define 1 as ONE, 3.14 as PI, etc. Typedef is limited to giving symbolic names to
types only.
Preprocessors interpret #define statements, while the compiler interprets typedef
statements.
There should be no semicolon at the end of #define, but a semicolon at the end of
typedef.
In contrast with #define, typedef will actually define a new type by copying and
pasting the definition values.
#include <stdio.h>
// macro definition
#define LIMIT 3
// Driver code
int main()
return 0;
Output
2
Symbolic Constants
A symbolic constant is a name given to some numeric constant, or a character
constant or string constant, or any other constants.
#define PI 3.141592
Operators
Operators are the symbols which tell the computer to execute certain
mathematical or logical operations. A mathematical or logical expression is
generally formed with the help of an operator. C programming offers a number of
operators which are classified into 8 categories viz.
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
1. Arithmetic Operators
Note: ‘/’ is integer division which only gives integer part as result after division. ‘%’
is modulo division which gives the remainder of integer division as result.
Some examples of arithmetic operators are:
a+b
a–b
a*b
a /b
a%b
2. Relational Operators
1<5
9 != 8
2 > 1+3
Note: Arithmetic operators have higher priority than relational operators meaning
that if arithmetic expressions are present on two sides of a relational operator
then arithmetic expressions will be calculated first and then the result will be
compared.
3. Logical Operators
Logical operators are used when more than one conditions are to be tested and
based on that result, decisions have to be made. C programming offers three
logical operators. They are:
For example:
a < 18 || a> 60
Highest precedence !
&&
Lowest precedence ||
4. Assignment Operators
Assignment operators are used to assign result of an expression to a variable. ‘=’ is
the assignment operator in C. Furthermore, C also allows the use of shorthand
assignment operators. Shorthand operators take the form:
var op = exp;
var op = exp;
Consider an example:
x += y;
x = x + y;
In the example above, m++ simply means m=m+1; and m– simply means m=m-1;
Increment and decrement operators are mostly used in for and while loops.
++m and m++ performs the same operation when they form statements
independently but they function differently when they are used in right hand side
of an expression.
++m is known as prefix operator and m++ is known as postfix operator. A prefix
operator firstly adds 1 to the operand and then the result is assigned to the
variable on the left whereas a postfix operator firstly assigns value to the variable
on the left and then increases the operand by 1. Same is in the case of decrement
operator.
For example,
X=10;
Y=++X;
And,
X=10;
Y=X++;
In this case, the value of Y will be 10 and the value of X will be 11.
6. Conditional Operator
The operator pair “?” and “:” is known as conditional operator. These pair of
operators are ternary operators. The general syntax of conditional operator is:
For example,
a=3;
b=5;
if (a > b)
x=a;
else
x=b;
Now, this if else statement can be written by using conditional operator as:
x = (a > b) ? a : b ;
7. Bitwise Operator
In C programming, bitwise operators are used for testing the bits or shifting them
left or right. The bitwise operators available in C are:
8. Special Operators
C programming supports special operators like comma operator, sizeof operator,
pointer operators (& and *) and member selection operators (. and ->). The
comma operator and sizeof operator are discussed in this section whereas the
pointer and member selection operators are discussed in later sections.
1. Comma Operator
The comma operator can be used to link the related expressions together. A
comma linked expression is evaluated from left to right and the value of the right
most expression is the value of the combined expression.
For example:
x = (a = 2, b = 4, a+b)
In this example, the expression is evaluated from left to right. So at first, variable a
is assigned value 2, then variable b is assigned value 4 and then value 6 is assigned
to the variable x. Comma operators are commonly used in for loops, while loops,
while exchanging values, etc.
2 .Sizeof() operator
The sizeof operator is usually used with an operand which may be variable,
constant or a data t ype qualifier. This operator returns the number of bytes the
operand occupies. Sizeof operator is a compile time operator. Some examples of
use of sizeof operator are:
x = sizeof (a);
y = sizeof(float);
The sizeof operator is usually used to determine the length of arrays and structures
when their sizes are not known. It is also used in dynamic memory allocation.
Expressions
C Operator Precedence
At first, the expressions within parenthesis are evaluated. If no parenthesis is
present, then the arithmetic expression is evaluated from left to right. There are
two priority levels of operators in C.
High priority: * / %
Low priority: + –
First Pass
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets
changed.
For example,
x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are
evaluated first from left to right. The expression is now evaluated in three passes
as:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7
There may even arise a case where nested parentheses are present (i.e.
parenthesis inside parenthesis). In such case, the expression inside the innermost
set of parentheses is evaluated first and then the outer parentheses are evaluated.
x = 9 – ((12 / 3) + 3 * 2) – 1
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2
Note: The number of evaluation steps is equal to the number of operators in the
arithmetic expression.
Example 1: Arithmetic Operators
// Working of arithmetic operators
#include <stdio.h>
int main()
{
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);
c = a/b;
printf("a/b = %d \n",c);
c = a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Run Code
Output
a+b = 13
a-b = 5
a*b = 36
a/b = 2
Remainder when a divided by b=1
The operators +, - and * computes addition, subtraction, and multiplication
respectively as you might have expected.
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program.
It is because both the variables a and b are integers. Hence, the output is also an
integer. The compiler neglects the term after the 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.
Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,
// Either one of the operands is a floating-point number
a/b = 2.5
a/d = 2.5
c/b = 2.5
return 0;
}
Run Code
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--. Visit this page to learn more about
how increment and decrement operators work when used as postfix.
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);
return 0;
}
Run Code
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
return 0;
}
Run Code
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
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
return 0;
}
Run Code
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
Explanation of logical operator program
(a == b) && (c > 5) evaluates to 1 because both operands (a == b) and (c > b) is 1
(true).
(a == b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
(a == b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0
(false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1
(true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).
return 0;
}
Run Code
Output
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Operator Precedence
Operator precedence helps us determine which of the operators in an expression
must be evaluated first in case the expression consists of more than a single
operator.
Example,
50 – 2 * 15 is going to yield 20. It is because it gets evaluated as 50 – (2 * 15), and
not as (50 – 2) * 15. The reason here is that subtraction (-) has lower precedence
as compared to multiplication (*).
Operator Associativity
We use associativity when two or more than two operators with the same
precedence are present in the same expression.
Example,
The precedence of Division and Multiplication arithmetic operators is the same. So,
let’s say we have an expression with us which is 6 * 3 / 20. The evaluation of this
expression would be (6 * 3) / 20 because the associativity will be left to right for
both the operators – multiplication and division. In a similar case, the calculation of
40 / 4 * 5 would be (40 / 4) * 5 because the associativity would be from right to left
here as well.
Associativity rules describe how an under parenthesized expression should be
parenthesized when the expression has a bunch of the same kind of operator. For
example, addition is associative from left to right, so a + b + c is equivalent
to (a + b) + c, not a + (b + c). In ordinary arithmetic, these two
expressions always give the same result; in computer arithmetic, they do not
necessarily. (As an exercise can you find values for a, b, c such that (a + b) +
c is unequal to a + (b + c) in C#?)
Order of evaluation :
OE refers to the operator precedence and associativity rules according to which
mathematical expressions are evaluated.
temp2 = G();
temp3 = H();
stdin: This file is used to receive the input (usually is keyborad file, but can also
take input from the disk file).
stdout: This file is used to send or direct the output (usually is a monitor file,
but can also send the output to a disk file or any other device).
stderr: This file is used to display or store error messages.
Input means to provide the program with some data to be used in the program
and Output means to display data on screen or write the data to a printer or a
file.C programming language provides many built-in functions to read any given
input and to display data on screen when there is a need to output the result.
There are mainly two of Input/Output functions are used for this purpose. These
are discussed as:
getchar()
putchar()
gets()
puts()
getch()
getche()
getchar()
This function is an Input function. It is used for reading a single character from the
keyboard. It is a buffered function n. Buffered functions get the input from the
keyboard and store it in the memory buffer temporally until you press the Enter
key.
v = getchar();
where v is the variable of character type. For example:
char n;
n = getchar();
A simple C-program to read a single character from the keyboard is as:
/*To read a single character from the keyboard using the getchar() function*/
#include <stdio.h>
main()
{
char n;
n = getchar();
}
putchar()
putchar(v);
where v is the variable of character type. For example:
char n;
putchar(n);
A simple program is written as below, which will read a single character using
getchar() function and display inputted data using putchar() function:
gets()
This function is an input function. It is used to read a string from the keyboard. It is
also a buffered function. It will read a string when you type the string from the
keyboard and press the Enter key from the keyboard. It will mark null character
(‘\0’) in the memory at the end of the string when you press the enter key. The
general syntax is as:
gets(v);
where v is the variable of character type. For example:
char n[20];
gets(n);
A simple C program to illustrate the use of gets() function:
puts(v);
or
puts("text line");
where v is the variable of character type.
A simple C program to illustrate the use of puts() function:
This is also an input function. This is used to read a single character from the
keyboard like getchar() function. But getchar() function is a buffered is function,
getchar() function is a non-buffered function. The character data read by this
function is directly assigned to a variable rather it goes to the memory buffer, the
character data is directly assigned to a variable without the need to press the Enter
key.
Another use of this function is to maintain the output on the screen till you have
not press the Enter Key. The general syntax is as:
v = getch();
where v is the variable of character type.
All are same as getch(0 function execpt it is an echoed function. It means when
you type the character data from the keyboard it will visible on the screen. The
general syntax is as:
v = getche();
where v is the variable of character type.
Formatted I/O functions which refers to an Input or Ouput data that has been
arranged in a particular format. There are mainly two formatted I/O functions
discussed as follows:
scanf()
printf()
scanf()
The scanf() function is an input function. It used to read the mixed type of data
from keyboard. You can read integer, float and character data by using its control
codes or format codes. The general syntax is as:
scanf("control strings",arg1,arg2,..............argn);
or
scanf("control strings",&v1,&v2,&v3,................&vn);
Where arg1,arg2,……….argn are the arguments for reading and v1,v2,v3,……..vn all
are the variables.
%s To read a string
%[..] To read a string of words from the defined range
%[^] To read string of words which are not from the defined range
Example Program:
/*Program to illustrate the use of formatted code by using the formatted scanf()
function */
#include <stdio.h>
main()
{
char n,name[20];
int abc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
}
printf()
This ia an output function. It is used to display a text message and to display the
mixed type (int, float, char) of data on screen. The general syntax is as:
printf("control strings",&v1,&v2,&v3,................&vn);
or
The control strings use some printf() format codes or format specifiers or
conversion characters. These all are discussed in the below table as:
Format Code Meaning
%s To read a string
Example Program:
/*Below the program which show the use of printf() function*/
#include <stdio.h>
main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch();
}
Format Specifiers
To print values of different data types using the printf() statement and while taking input
using the scanf() function, it is mandatory to use format specifiers.
It is a way to tell the compiler what type of data is in a variable.
Some examples are %c, %d, %f, etc.
Here is a list of all the format specifiers.
int %d, %i
char %c
float %f
double %lf
Datatype Format Specifier
unsigned int %u
signed char %c
unsigned char %c
I/O operations that reads or writes data as a stream of bytes without regard to any format.
Unformatted I/O in C is carried out with the aid of functions like fread() and fwrite(). Without
formatting, these operations are used to read and write data directly to and from files.
Syntax:
In this syntax, a pointer to the buffer where the data will be read, the size of each element to be
read, the number of elements to be read, and a pointer to the file from which the data will be
read.
Example
AD
#include <stdio.h>
int main() {
char data[100];
FILE *fp;
fp = fopen("file.txt", "w+");
fread(data, sizeof (
char), 100, fp);
printf("%s\n", data);
fclose(fp);
return 0;
}
Output:
Explanation:
In the example, we first declare a file pointer (fp) and a character array (data). After that, the file
pointer is assigned to 'fp' after using the 'fopen()' method to open the 'file.txt' file in write mode.
The string "This is an example of unformatted output." is written to the file using
the 'fputs()' function. The file pointer is then moved to the file's beginning using
the 'fseek()' function. After that, the data is shown using the 'printf()' function after being read
from the file into the 'data' buffer using the 'fread()' function.
UNIT-6
Control Statements
STATEMENTS
A statement causes the computer to carry out some definite action. There are three different classes
of statements in C:
Expression statements, Compound statements, and Control statements.
Null statement
A null statement consisting of only a semicolon and performs no operations . It can appear wherever
a statement is expected. Nothing happens when a null statement is executed.
Syntax: -
Statements such as do, for, if, and while require that an executable statement appear as the statement
body. The null statement satisfies the syntax requirement in cases that do not need a substantive
statement body.
The Null statement is nothing but, there is no body within loop or any other statements in C.
Example illustrates the null statement:
for ( i = 0; i < 10; i++) ;
or
for (i=0;i<10;i++)
{
//empty body
}
Expression
Most of the statements in a C program are expression statements. An expression statement is simply
an expression followed by a semicolon. The lines
i = 0;
i = i + 1;
and printf("Hello, world!\n");
are all expression statements. In C, however, the semicolon is a statement terminator. Expression
statements do all of the real work in a C program. Whenever you need to compute new values for
variables, you'll typically use expression statements (and they'll typically contain assignment
operators). Whenever you want your program to do something visible, in the real world, you'll
typically call a function (as part of an expression statement). We've already seen the most basic
example: calling the function printf to print text to the screen.
Note -If no expression is present, the statement is often called the null statement.
Return
The return statement terminates execution of a function and returns control to the calling function,
with or without a return value. A function may contain any number of return statements. The return
statement has
syntax: return expression(opt);
If present, the expression is evaluated and its value is returned to the calling function. If necessary, its
value is converted to the declared type of the containing function's return value.
A return statement with an expression cannot appear in a function whose return type is void . If
there is no expression and the function is not defined as void , the return value is undefined. For
example, the following main function returns an unpredictable value to the operating system:
main ( )
{
return;
}
Compound statements
A compound statement (also called a "block") typically appears as the body of another statement,
such as the if statement, for statement, while statement, etc
A Compound statement consists of several individual statements enclosed within a pair of braces {
}. The individual statements may themselves be expression statements, compound statements or
control statements. Unlike expression statements, a compound statement does not end with a
semicolon. A typical Compound statement is given below.
{
pi=3.14;
area=pi*radius*radius;
}
The particular compound statement consists of two assignment-type expression statements.
Example:
if statement.
The if statement controls conditional branching. The body of an if statement is executed if the value
of the expression is nonzero. Or if statement is used to execute the code if condition is true. If the
expression/condition is evaluated to false (0), statements inside the body of if is skipped from
execution.
Syntax : if(condition/expression)
{
true statement;
}
statement-x;
If the condition/expression is true, then the true statement will be executed otherwise the true
statement block will be skipped and the execution will jump to the statement-x. The „true statement‟
may be a single statement or group of statement.
If there is only one statement in the if block, then the braces are optional. But if there is more than
one statement the braces are compulsory
Flowchart
Example:
#include<stdio.h>
main()
{
int a=15,b=20;
if(b>a)
{
printf("b is greater");
}
}
Output
b is greater
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// Test expression is true if number is less than 0
if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
Output 1
Enter an integer: -2
You entered -2.
The if statement is easy.
Output 2
Enter an integer: 5
The if statement in C programming is easy.
If-else statement : The if-else statement is an extension of the simple if statement. The general
form is. 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 : if (condition)
{
true statement;
}
else
{
false statement;
}
statement-x;
If the condition is true , then the true statement and statement-x will be executed and if the condition
is false, then the false statement and statement-x is executed.
Or
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.
Flowchart
Example:
// Program to check whether an integer entered by the user is odd or even
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
}
statement-x;
If the condition-1 is false, the statement-3 and statement-x will be executed. Otherwise it continues
to perform the second test. If the condition-2 is true, the true statement-1 will be executed
otherwise the statement-2 will be executed and then the control is transferred to the statement-x
Flowchart
Example
#include<stdio.h>
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 !=var2)
{
printf("var1 is not equal to var2");
//Below – if-else is nested inside another if block
if (var1 >var2)
{
printf("var1 is greater than var2");
}
else
{
printf("var2 is greater than var1");
}
}
Else
{
printf("var1 is equal to var2");
}
…
Else if ladder.
The if else-if statement is used to execute one code from multiple conditions.
Syntax : if( condition-1)
{
statement-1;
}
else if(condition-2)
{
statement-2;
}
else if(condition-3)
{
statement-3;
}
else if(condition-n)
{
statement-n;
}
else
{
default-statement;
}
statement-x;
Flowchart
Example
#include<stdio.h>
#include<conio.h>
void main(){
int number=0;
clrscr();
printf("enter a number:");
scanf("%d",&number);
if(number==10){
printf("number is equals to 10");
}
else if(number==50){
printf("number is equal to 50");
}
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 10, 50 or 100");
}
getch();
}
Switch statement : when there are several options and we have to choose only one option from
the available ones, we can use switch statement. Depending on the selected option, a particular task
can be performed. A task represents one or more statements.
Syntax:
switch(expression)
{
case value-1:
statement/block-1;
break;
case value-2:
statement/block t-2;
break;
case value-3:
statement/block -3;
break;
case value-4:
statement/block -4;
break;
default:
default- statement/block t;
break;
}
The expression following the keyword switch in any „C‟ expression that must yield an integer value.
It must be ab integer constants like 1,2,3 .
The keyword case is followed by an integer or a character constant, each constant in each must be
different from all the other.
First the integer expression following the keyword switch is evaluated. The value it gives is searched
against the constant values that follw the case statements. When a match is found, the program
executes the statements following the case. If no match is found with any of the case statements, then
the statements follwing the default are executed.
Rules for writing switch() statement.
1 : The expression in switch statement must be an integer value or a character constant.
2 : No real numbers are used in an expression.
3 : The default is optional and can be placed anywhere, but usually placed at end.
4 : The case keyword must terminate with colon ( : ).
5 : No two case constants are identical.
6:The case labels must be constants.
Valid Switch Invalid Switch Valid Case Invalid Case
switch(x) switch(f) case 3; case 2.5;
switch(x>y) switch(x+2.5) case 'a'; case x;
switch(a+b-2) case 1+2; case x+2;
switch(func(x,y)) case 'x'>'y'; case 1,2,3;
Example
#include<stdio.h>
main()
{
int a;
printf("Please enter a no between 1 and 5: ");
scanf("%d",&a);
switch(a)
{
case 1:
printf("You chose One");
break;
case 2:
The while loop is an entry controlled loop statement, i.e means the condition is evaluated first
and it is true, then the body of the loop is executed. After executing the body of the loop, the
condition is once again evaluated and if it is true, the body is executed once again, the process of
repeated execution of the loop continues until the condition finally becomes false and the control is
transferred out of the loop.
Example : Program to print first 10 natural numbers
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
x=1;
while(x<=10)
{
printf("%d\t", x);
x++;
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
C Program to reverse number
#include<stdio.h>
#include<conio.h>
main()
{
int n, reverse=0, rem;
clrscr();
printf("Enter a number: ");
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number: %d",reverse);
getch();
}
Flowchart
do-while loop
Syntax : variable initialization ;
do{
statements ;
variable increment or decrement ;
}while (condition);
The do-while loop is an exit controlled loop statement The body of the loop are executed first and
then the condition is evaluated. If it is true, then the body of the loop is executed once again. The
process of execution of body of the loop is continued until the condition finally becomes false and
the control is transferred to the statement immediately after the loop. The statements are always
executed at least once.
Flowchart
Example : Program to print first ten multiple of 5
#include<stdio.h>
#include<conio.h>
void main()
{
int a,i;
a=5;
i=1;
do
{
printf("%d\t",a*i);
i++;
}while(i <= 10);
getch();
}
Output
5 10 15 20 25 30 35 40 45 50
Example
main()
{
int i=0
do
{
printf("while vs do-while\n");
}while(i= =1);
printf("Out of loop");
}
Output:
while vs do-while
Out of loop
For Loop:
This is an entry controlled looping statement.
One of the most important features of this loop is that the three actions can be taken at a time like
variable initialization, condition checking and increment/decrement.
The for loop can be more concise and flexible than that of while and do-while loops.
Example:
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
for(x=1; x<=10; x++)
{
printf("%d\t",x);
}
getch();
}
Output
1 2 3 4 5 6 7 8 9 10
Various forms of FOR LOOP
I am using variable num in all the below examples –
1) Here instead of num++, I‟m using num=num+1 which is nothing but same as num++.
for (num=10; num<20; num=num+1)
2) Initialization part can be skipped from loop as shown below, the counter variable is declared
before the loop itself.
int num=10;
for (;num<20;num++)
Must Note: Although we can skip init part but semicolon (;) before condition is must, without which
you will get compilation error.
3) Like initialization, you can also skip the increment part as we did below. In this case semicolon (;)
is must, after condition logic. The increment part is being done in for loop body itself.
for (num=10; num<20; )
{
//Code
num++;
}
4) Below case is also possible, increment in body and init during declaration of counter variable.
int num=10;
for (;num<20;)
{
//Statements
num++;
}
5) Counter can be decremented also, In the below example the variable gets decremented each time
the loop runs until the condition num>10 becomes false.
for(num=20; num>10; num--)
Program to calculate the sum of first n natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when n is less than count
Output:
Enter a number: 5
Factorial of 5 is: 120
Flow Chart of for Loop :
statement ;
}
}
Example:
main()
{
for (int i=0; i<=5; i++)
{
for (int j=0; j<=5; j++)
{
printf("%d, %d",i ,j);
}
}
}
Example : Program to print half Pyramid of numbers
#include<stdio.h>
#include<conio.h>
void main( )
{
int i,j;
for(i=1;i<5;i++)
{
printf("\n");
for(j=i;j>0;j--)
{
printf("%d",j);
}
}
getch();
}
Output
1
21
321
4321
54321
Jump Statements
Jumping statements are used to transfer the program‟s control from one location to another, these are
set of keywords which are responsible to transfer program‟s control within the same block or from
one function to another.
There are four jumping statements in C language:
goto statement
return statement
break statement
continue statement
goto statement : goto statement doesnot require any condition. This statement passes control
anywhere in the program i.e, control is transferred to another part of the program without testing
any condition.
Example
int main()
{
int age;
Vote:
printf("you are eligible for voting");
NoVote:
printf("you are not eligible to vote");
printf("Enter you age:");
scanf("%d", &age);
if(age>=18)
goto Vote;
else
goto NoVote;
return 0;
}
Output
Enter you age:19
you are eligible for voting
Enter you age:15
you are not eligible to vote
Break Statement
Break is a keyword. The break statement terminates the loop (for, while and do...while loop)
immediately when it is encountered. The break statement is used/ associated with decision making
statement such as if ,if-else.
Syntax of break statement
break;
Flowchart
printf("%d \n",i);
if(i==5){//if value of i is equal to 5, it will break the loop
break;
}
}//end of for loop
getch();
}
Output
12345
Continue Statement
Continue is keyword exactly opposite to break. The continue statement is used for continuing next
iteration of loop statements. When it occurs in the loop it does not terminate, but it skips some
statements inside the loop / the statements after this statement. . The continue statement is used/
associated with decision making statement such as if ,if-else.
Syntax of continue Statement
continue;
Flowchart of continue Statement
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=1;//initializing a local variable
5. clrscr();
6. //starting a loop from 1 to 10
7. for(i=1;i<=10;i++){
8. if(i==5){//if value of i is equal to 5, it will continue the loop
9. continue;
10. }
11. printf("%d \n",i);
12. }//end of for loop
13. getch();
14. }
Output
1234678910
Break
Continue
1 : break statement takes the control to the 1 :continue statement takes the control to
ouside of the loop the beginning of the loop..
2 : it is also used in switch statement. 2 : This can be used only in loop
statements.
3 : Always associated with if condition in 3 : This is also associated with if
loops. condition.
UNIT -7
Functions
7.1 Advantages of using Function
7.2 User Defined & Library Functions
7.3 Function Prototypes, definition & return statement
7.4 Call by Value & Call by reference
7.5 Concept of Local, Global & Static variables
7.6 Recursive Function
7.7 Storage Classes and Visibility, Automatic or local variables, Global variables, Static variables,
External variables
Functions
Functions are building blocks of a C program. Understanding functions is one of the most
important steps in C language.
Definition
A function is a self-contained program segment that carries out a specific, well-defined
task. A function is a collection of instructions that performs a specific task. Every function
is given a name. The name of the function is used to invoke (call) the function. A
function may also take parameters (arguments). If a function takes parameters, parameters
are to be passed within parentheses at the time of invoking function.
A function theoretically also returns a value, but you can ignore the return value of the
function in C language. Function name must follow the same rules of formation as other
variables in C. The argument list contains valid variable names separated by commas.
C is a function-oriented language. Many operations in C language are done through
functions. For example, we have used printf() function to display values, scanf() function
to read values from keyboard, strlen() function to get the length of the string etc.
Classification of Functions
C functions can be classified into two categories namely
1. Library functions
2. User defined functions.
The main difference between these 2 categories is that
library functions are not required to be written by the user, printf, scanf, strlen, sqrt
and pow, etc belong to the category of library functions.
user defined function has to be developed by the user at the time of writing a
program. main() function is an example of user-defined function. Every program
must have a main function to indicate where the program has to begin its
execution.
Standard/Library functions
A function which is made available to programmer by compiler is called as
standard or pre-defined function. Every C compiler provides good number offunctions. All that a
programmer has to do is use them straight away. For example, if you have to find length of a
string , use strlen() without having to write the required code.
The code for all standard functions is available in library files, like cs.lib, and
graphics.lib. These library files are supplied by the vendor of compiler. Where
these libraries are stored in the system depends on the compiler. For example, if
you are using Turbo C, you find libraries in LIB directory under directory where
Turbo C is installed.
Declarations about standard functions are available in header files such as stdio.h,
and string.h. Turbo C provides around 400 functions covering various areas like
Screen IO, graphics, disk IO etc.
User-defined functions
User-defined function is a function that is defined by user. That means, the code
for the function is written by user (programmer). User-defined functions are
similar to standard functions in the way you call. The only difference is instead of
C language providing the function, programmer creates the function.
If a program is divided into functional parts than each part may be independently coded
and later combined into single unit.
Advantages of Functions:
1. The length of the source program can be reduced by using functions at appropriate
places.
2. It becomes easier to locate a faculty functions.
3. Many other programs may use a function.
User-defined functions are used mainly for two purposes:
(1) To avoid repetition of code
In programming you often come across the need to execute the same code in
different places in the program. For exam ple, if you have to print an array at the
beginning of the program and at the end of the program. Then you need to write
the code to display the array twice.
If you create a function to display the array, then you have to call the function
once at the beginning of the program. That means, the source code need not be
written for multiple times. It is written only for once and called for multiple times.
(2) To break large program into smaller units
It is never a good idea to have a single large code block. If you write entire C
program as one block, the entire blocks ends up in main() function. It becomes
very difficult to understand and manage.
If you can break a large code block into multiple smaller blocks, called functions,
then it is much easier to manage the program. In the following example, instead
of taking input, processing and displaying output in main() function, if you can
divide it into three separate functions, it will be much easier to understand and
manage.
Terminology of Functions
Function Declaration:
A function may contain declaration and definition. Function declaration specifies
function name, return type, and type of parameters. This is normally given at the
beginning of the program. Though it is not mandatory in all cases, it is better to declare
each function. In fact header files (*.h) contain declarations of all standard functions.
following is the syntax for function declaration.
return-type functionname ( parameters );
Function declaration is called as Prototype declaration. Though it is not necessary in
majority of cases, it is needed in cases where the following conditions apply:
Call to function comes before definition of the function
Function returns non-integer value.
Function Definition:
Function definition is where the statements to be executed are given. When the function
is called the statements given here are executed.
return-type function nname ( parameters )
{
statements;
return value;
}
Where,
Return type: specifies the type of value function returns. If function doesn’t return any
value then it must be void.
Parameters are :formal parameters of the function.
Statements :are the statements to be executed when function is called.
Return: statement is used to return a value from function.
Passing Parameters:
A parameter or argument is a value passed to function so that function can use that value
while performing task. A function may take none, one or more parameters depending
upon the need.
Example: line(); /*function that pass no parameters*/
line(20); /*function that pass one parameter*/
getaverage(10,20); /*function that pass more than one parameter*/
Actual Parameter: It is the value that is passed to function while calling the function. For
example; 10 and 20 values that we passed to line() and getaverage() function in the
above are actual parameters.
Formal Parameter: Variable that is used to receive actual parameter is called formal
parameter.
Example: getaverage(int a, int b); Here a and b are formal parameters.
Returning Value:
Normally after performing the task functions return a value. The return value may be of
any type. But a function can return only one value. To return a value from the function,
we have to first specify what type of value the function returns and then we have to use
return statement in the code of the function to return the value.
When return type is not explicitly mentioned it defaults to int. If a function doesn't
return any value then specify return type as void.
A function returns the value to the location from where it has been called.
Storage Classes
Properties of a variable:
A variable in C language is associated with the following properties:
Blocks:
C is a block structured language. Blocks are delimited by { and }. Every block can have its
own local variables. Blocks can be defined wherever a C statement could be used. No
semi-colon is required after the closing brace of a block.
Scope
The area of the program from where a variable can be accessed is called as scope of the
variable. The scope of a variable determines over what parts of the program a variable is
actually available for use (active). Scope of the variable depends on where the variable is
declared. The following code illustrate the scope of a variable:
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
. . . .
}
The scope of a variable may be either global or local.
Global Scope: It means the variable is available throughout the program. It is available to
all functions that are defined after the declaration of the variable. This is the scope of the
variables, which are declared outside of all functions. Variables that have global scope are
called as Global Variables.
In the above example, variable g has global scope; that means the variable is accessible to
all the functions of the program (main, sum) that are defined after the variable is defined.
Local Scope: Variables declared at the beginning of the block are available only to that
block in which they are declared. When the scope of the variable is confined to block it is
called as Local Scope. Variables with local scope are called as Local Variables.
In the above example, variables x and y have local scope; that means the variables are
accessible only to the functions at which they are declared.
C allows you to create variables not only at the beginning of a function, you can also
declare variables at the beginning of the block.
main()
{
int x; /* scope of x is throughout main function */
. . . .
if( ...) {
int p; /* scope of p is accessible only within if block */
. . . .
}
else {
int q; /*scope of q is accessible only within else block*/
. . . .
}
}
You cannot change the scope of a variable, it is completely dependent on the place of
declaration in the program.
Visibility:
Normally visibility and scope of variables are same. In other words, a variable is visible
throughout its scope.
Visibility means the region of the program in which a variable is visible. A variable can
never be visible outside the scope. But it may be invisible inside the scope.
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
int g;
g=20; /* local variable g is used not global variable g */
}
In the above code, variable g has global scope. But it becomes invisible throughout the
function sum as a variable with the same name is declared in that function.
When a global variable is re-declared in a function then the local variable takes
precedence i.e., g in function sum will reference g in function but not g declared as global
variable. So, in this case though g has scope throughout program, it is not visible
throughout function sum.
For global variable to get its visibility in a function, when a local variable with same
variable name is declared and use we use scope resolution operator(::). This helps in
accessing global variable even though another variable with same name is existing.
int g; /* scope of g is from this point to end of program */
main()
{
int x; /* scope of x is throughout main function */
. . . .
}
void sum()
{
int y; /* scope of y is throughout function sum */
int g;
g=20; /* local variable g is used not global variable g */
::g=g+10; /*global variable g is used now with the operator*/
/*'::' called scope resolution operator*/
}
Extent/Lifetime
Also called as Longevity. This refers to the period of time during which a variable resides
in the memory and retains a given value during the execution of a program. Longevity
has a direct effect on the utility of a given variable.
A variable declared inside a block has local extent. Because it exists in the memory as
long as the block is in execution. It is created when block is invoked and removed when
the execution of the block is completed.
On the other hand, variable declared outside all functions has static extent as they remain
in memory throughout the execution of program.
Though variable is available in memory, we can access it only from the region of the
program to which the variable is visible. That means, just because the variable is there in
the memory we cannot access it.
STORAGE CLASS SPECIFIERS
'Storage' refers to the scope of a variable and memory allocated by compiler to store that
variable. Scope of a variable is the boundary within which a variable can be used.
Storage class defines the scope and lifetime of a variable.
From the point view of C compiler, a variable name identifies physical location from a
computer where variable is stored. There are two memory locations in a computer
system where variables are stored as: Memory and CPU Registers.
Functions of storage class:
To determine the location of a variable where it is stored?
Set initial value of a variable or if not specified then setting it to default value.
Defining scope of a variable.
To determine the life of a variable.
Syntax:
[storage-class] data type variable [= value] ;
Category of Functions:
A function depending on whether arguments are present or not and whether a value is
returned or not may belong to one of the following categories:
1. Functions with no arguments and no return value.
2. Functions with arguments and no return value.
3. Functions with arguments and return value.
4. Functions with no arguments and return value.
printf("Average of 3 numbers:\n");
avg = average();
printf("Average: %f",avg);
}
float average()
{
int a,b,c,s;
printf("Enter 3 numbers: ");
scanf("%d %d %d",&a,&b,&c);
s=a+b+c;
return s/3.0;
}
Functions with arguments and no return value
When a function has argument(s), it does receive data from calling function. When it
does not return a value, the calling function receives does not data from called function.
In effect, there is data transfer between calling function & called function.
Program 1:
#include<stdio.h>
main()
{
dline(15);
printf("\nFunctions...");
dline(15);
getch();
}
dline(int n)
{
int l;
for(l=0;l<n;l++)
putch('-');
}
Program 2:
#include<stdio.h>
void interest(float,int,float);
main()
{
int t;
float p,r;
printf("Enter principal amount: ");
scanf("%f",&p);
printf("Enter time period: ");
scanf("%d",&t);
printf("Enter rate: ");
scanf("%d",&r);
interest(p,t,r);
}
void interest(float pr,int tp,float rate)
{
float si;
si = (pr*tp*rate)/100;
printf("Simple Interest for Rs %0.2f is %0.2f",pr,si);
}
Functions with arguments and return value
When a function has an argument, it receives back any data from calling function. When
it returns a value, the calling function receives any data from called function. In effect,
there is a data transfer between the calling function & called function.
Program:
int getsum(int n);
main()
{
int v,sum;
printf("Enter n value: ");
scanf("%d",&v);
sum = getsum(v);
printf("Sum=%d",sum);
}
int getsum(int n)
{
int s=0;
for(;n>0;n--)
s+=n;
return s;
}
Call by Reference:
If data is passed by reference, a pointer to the data is copied instead of the actual
variable as it is done in a call by value. Because a pointer is copied, if the value at that
pointers address is changed in the function, the value is also changed in main().
In the call by reference we pass the address of the variables whose arguments are also
send. So that when we use the reference then, we pass the address the variables.
When we pass the address of variables to the arguments then a function may effect on
the variables. So, when a function will change the values then the values of variables gets
automatically changed and when a function performs some operation on the passed
values, then this will also effect on the actual values.
Example: Program to illustrate the concept of call by reference
#include <stdio.h>
swap (int *, int *);
main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
getch();
}
swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:
Enter value of a & b: 2 3
Before swapping: 2 3
After swapping: 3 2
It is then up to the function to read the first item from the array, move the pointer along
to the next item, and then carry on until it finds the end of the array - thus, it has to
somehow know how long the array is.
function_name(int x[5])
function_name(int x[])
The parameter x in the above declarations are also internally taken as an integer pointer
by C to access the elements of the array from the first element.
Passing a 1-dimensional array as argument to function:
Example 1: Program to print the given array
printarray(int []);
main()
{
int a[5],i;
for(i=0;i<5;i++)
scanf("%d",&a[i]);
printarray(a);
}
printarray(int ar[5])
{
int i;
for(i=0;i<5;i++)
printf("%d\n",i[ar]);
}
Example 2: Program to find largest from the given array
#define SIZE 50
int big(int [], int);
main()
{
int a[SIZE], n, i, b;
printf("\nEnter size of array: ");
scanf("%d", &n);
printf("\nEnter elements:\n");
for (i=0; i<n; i++)
scanf("%d", &a[i]);
b = big(a, n);
printf("\nLargest number: %d", b);
}
int big(int a[], int n)
{
int b, i;
b = a[0];
for(i=0; i<n; i++)
if (a[i] > b) b = a[i];
return b;
}
}
Passing structure as argument to function
A structure can be passed to a function. To pass a structure to a function you have to
pass it just like how you would pass standard data types like int and float.
Example: Program to illustrate the concept of passing structure to function.
struct point
{
int x,y;
};
void display(struct point t);
main()
{
struct point p;
printf("Read Coordinates of a point: ");
scanf("%d %d",&p.x,&p.y);
display(p);
}
void display(struct point t)
{
printf("Coordinates of a point: x=%d, y=%d",t.x,t.y);
}
When you are sending a structure to a function, make sure that both calling function and
called function have access to structure. This can be done if you declare the structure at
the beginning of the program.
Just like how we send a structure variable to a function you can also send an array of
structures to a function.
Return a Structure
A function can also return a structure as return type. All that you have to do is specify
return type as structure and return a structure variable.
Example: Program to call a function that returns a variable of structure.
struct point {
int x,y;
};
struct point getpoint();
main()
{
struct point p;
p = getpoint();
printf("Coordinates of a point: x=%d, y=%d",p.x,p.y);
}
struct point getpoint()
{
struct point t;
printf("Enter point coordinates: ");
scanf("%d %d",&t.x,&t.y);
return t;
}
printf("%c",p[i]);
}
else
continue;
}
}
Calling Function within Function
One of the main reasons of using various functions in your program is to isolate
assignments; this allows you to divide the jobs among different entities so that if
something is going wrong, you might easily know where the problem is.
Functions trust each other, so much that one function does not have to know HOW the
other function performs its assignment. One function simply needs to know what the
other function does, and what that other function needs.
Once a function has been defined, other functions can use the result of its assignment.
Imagine you define two functions A and B.
If Function A needs to use the result of Function B, function A has to use the name of
function B. This means that Function A has to “call” Function B:
When calling one function from another function, provide neither the return value nor
the body, simply type the name of the function and its list of arguments, if any.
{
printf("Sum of 2 numbers %d and %d is %d",x,y,s);
}
Pointer to Function
It is also possible to have a pointer pointing to a function. A pointer to a function
contains the address of the location to which control is transferred when you use the
pointer.
The following example shows how to declare a pointer to a function and use it to
invoke the function.
/*pointer pointing to function that returns void*/
void (*fp)();
void print();
main()
{
/*make fp pointing to print function*/
fp = print;
/*call print function through pointer to function*/
(*fp)();
}
void print()
{
printf("Hello! From Function Print...");
}
Recursion
Recursion is a process of defining something in terms of itself and is sometimes called
circular definition. When a function calls itself it is called as recursion. Recursion is natural
way of writing certain functions.
Recursive Function: A function is said to be recursive if a statement in the body of the
function calls itself. Each recursive function must specify an exit condition for it to
terminate, otherwise it will go on indefinitely.
A simple example of recursion is presented below:
main()
{
printf("\nThis is an example of recursion");
main();
}
When executed, this program will produce an output like:
This is an example of recursion
This is an example of recursion
…
…
…
This is an example of recursion
…
long fact(int n)
{
int m;
if (n == 1)
return n;
else
return n * fact(n-1);
}
Example: Program to find the GCD of two given integers using Recursion
#include<stdio.h>
#include<conio.h>
int gcd (int, int); //func. declaration.
void main( )
{
int a, b, res;
clrscr( );
printf("Enter the two integer values:");
scanf("%d%d", &a, &b);
res= gcd(a, b); // calling function.
printf("\nGCD of %d and %d is: %d", a, b, res);
getch( );
}
int gcd( int x, int y) //called function.
{
int z;
z=x%y;
if(z==0)
return y;
gcd(y,z); //recursive function
}
Example: Program to generate the Fibonocci series using Recursion.
#include<stdio.h>
#include<conio.h>
int fibno(int); // function declaration.
void main()
{
int ct, n, disp;
clrscr( );
printf("Enter the no. of terms:");
scanf("%d", &n);
printf("\n The Fibonocci series:\n");
for( ct=0; ct<=n-1; ct++)
{
disp= fibno(ct); //calling function.
printf("%5d", disp);
}
getch( );
}
int fibno( int n)
{
int x, y;
if(n==0)
return 0;
else if(n==1)
return 1;
else
{
x= fibno( n-1);
y= fibno( n-2);
return (x+y);
}
}
UNIT – 8
Arrays and Strings
8.1 Introduction
8.2 Single and Multi-dimension arrays
8.3 Processing an array
8.4 Passing arrays to Functions
8.5 Arrays of Strings
8.6 String Handling Function
ARRAYS
Array is a collection or group of elements (data). All the elements of array are
homogeneous (similar). It has contiguous memory location.
Array of character is a string. Each data item of an array is called an element. And
each element is unique and located in separated memory location. Each of
elements of an array share a variable but each element having different index no.
known as subscript.
An array can be a single dimensional or multi-dimensional and number of
subscripts determines its dimension. And number of subscript is always starts
with zero. One dimensional array is known as vector and two dimensional arrays
are known as matrix.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an
array easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code
only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of Array
Fixed Size: Whatever size, we define at the time of declaration of array, we can't
exceed the limit. So, it doesn't grow the size dynamically like LinkedList.
Types of Array
1. Static Array
2. 2. Dynamic Array.
Static Array An array with fixed size is said to be a static array.
Types of static array:
1. One Dimensional Array
2. Two Dimensional Array.
3. Multi Dimensional Array.
3. Multi Dimensional Array. This array does not exist in c and c++.
Dynamic Array. This type of array also does not exist in c and c++.
Declaring an array
An array is declared just like an ordinary variable but with the addition of number
of elements that the array should contain.
A particular value is indicated by writing a number called 'index or subscript'
number in brackets for after the array name.
Syntax:
type variablename[size];
The type specifies data type of element that will be contained in an array such as
int, float, char, and double.
The size indicates the maximum number of elements that can be stored inside the
array.
E.g. The following declaration declares n array of 20 elements where each
element is of int type.
int marks[20];
Now, marks is the name of the array of 20 integers. Marks occupies 40 bytes, if int
occupies 2 bytes (20*2).
Array can be of any variable type. The ability to use a single name to represent a
collection to refer to an item by specifying the item number enables us to develop
efficient programs.
TYPES:
Arrays in C Programming are of 3 types:
(1) One [or] Single Dimensional Array
(2) Two [or] Double Dimensional Array
(3) Multi Dimensional Array
ONE-DIMENSIONAL ARRAY
A list of items can be given one variable name using only one subscript and such a
variable is called a single subscripted variable or one dimensional array.
For Example: If we want to represent a set of 5 numbers 35, 40, 20, 57, 19 by an array
variable 'number' then we may declare the variable number as follows:
int number[5]; and computer reverses 5 storage locations are shown below:
The elements can be used in programs just like as any other 'C' variable.
It is not possible to either add new elements or delete existing elements after the array is
created. In other words the size of the array is static and it cannot be changed at runtime.
Initializing an array
It is possible to store values into an array during time of declaration.
int a[5] = {10, 20, 30, 40, 50};
Values given in { } are placed in corresponding element of an array. If number of values
given is more than the size, C displays an error "Too many Initializers in Function...". If
number of values given is less than the size, then the number of elements then only the
corresponding elements are filled.
In certain case, you can ignore the size of the array if you are initializing the array. C
determines the size of the array from the number of values given in the initialization.
int a[] = {20,30,40}; /*is an array of 3 elements*/
Sample C Programs
Example: Program to insert elements into an array and print the array elements.
#include<stdio.h>
#include<conio.h>
main()
{
int a[5],i;
clrscr();
printf("Enter 5 elements into an array:\n");
for(i=0;i<=4;i++) {
scanf("%d",&a[i]);
}
printf("The 5 elements are:\n");
for(i=0;i<=4;i++)
printf("%d\n",a[i]);
getch();
}
Output:
Enter 5 elements into an array:
35
23
45
67
11
The 5 elements are:
35
23
45
67
11
Example: Take an array of 10 integers and accept values into it. Sort the array in
descending order.
#include<stdio.h>
#include<conio.h>
main()
{
int ar[10];
int i, j, temp;
clrscr();
for (i = 0 ; i < 10 ; i++)
{
printf("Enter number for [%d] element: ",i);
scanf("%d", &ar[i]);
}
/* sort array in descending order */
for ( i = 0 ; i < 9 ; i++)
{
for ( j = i+1; j < 10 ; j ++)
{
if ( ar[i] > ar[j])
{
/* interchange */
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
} /* end of j loop */
} /* end of i loop */
/* display sorted array */
printf("\nSorted Numbers \n");
for ( i = 0 ; i < 10 ; i++)
{
printf("%d\n", ar[i]);
}
getch();
}
Output:
Enter number for [0] element: 35
Enter number for [1] element: 67
Enter number for [2] element: 98
Enter number for [3] element: 12
Enter number for [4] element: 6
Enter number for [5] element: 58
Enter number for [6] element: 49
Enter number for [7] element: 23
Enter number for [8] element: 71
Enter number for [9] element: 85
Sorted Numbers
6
12
23
35
49
58
67
71
85
98
TWO-DIMENSIONAL ARRAY
A list of items can be given one variable name using two subscripts and such a variable is
called a double subscripted variable or two-dimensional array. So to access
twodimension array you have to have one row index and one column index.
Things which you must consider while initializing 2D array – You must remember that
when we give values during one dimensional array declaration, we don’t need to
mention dimension. But that’s not the case with 2D array; you must specify the second
dimension even if you are giving values during the declaration. Let’s understand this with
the help of few examples –
/* Valid declaration*/
int abc[2][2] = {1, 2, 3 ,4 }
/* Valid declaration*/
int abc[][2] = {1, 2, 3 ,4 }
/* Invalid declaration – you must specify second dimension*/
int abc[][] = {1, 2, 3 ,4 }
/* Invalid because of the same reason mentioned above*/
int abc[2][] = {1, 2, 3 ,4 }
Sample C Programs
Example: Program to insert elements into array and display the array
#include<stdio.h>
#include<conio.h>
main()
{
int a[2][2],i,j;
clrscr();
printf("Enter 4 elements into array: ");
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++) {
scanf("%d",&a[i][j]);
}
}
printf("The 4 elements are:\n\t");
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++) {
printf("%d\t",a[i][j]);
}
printf("\n\t");
}
getch();
}
Output:
Enter 4 elements into array:
6
3
2
1
The 4 elements are:
6 3
2 1
Example: Program to print Multiplication Table
#include<stdio.h>
#include<conio.h>
#define ROWS 5
#define COLUMNS 5
main()
{
int row,column,product[ROWS][COLUMNS];
int i,j;
clrscr();
printf(" MULTIPLICATION TABLE \n\n");
printf(" ");
for(j=1;j<=COLUMNS;j++)
printf("%4d",j);
printf("\n");
printf("-----------------------\n");
for(i=0;i<ROWS;i++)
{
printf(" ");
row=i+1;
printf("%2d",row);
for(j=1;j<COLUMNS;j++)
{
column=j+1;
product[i][j] = row*column;
printf("%4d",product[i][j]);
}
printf("\n");
}
getch();
}
Output:
MULTIPLICATION TABLE
1 2 3 4 5
-----------------------
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Example: Program to solve multiplication of 2 matrices
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,m,n,p,q,k;
clrscr();
printf("Enter order of matrix A for m & n\n");
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("Enter a[%d][%d] element: ",i,j);
scanf("%d",&a[i][j]);
}
}
printf("Enter order of matrix B for p & q\n");
scanf("%d%d",&p,&q);
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("Enter b[%d][%d] element: ",i,j);
scanf("%d",&b[i][j]);
}
}
if(n==p) {
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<m;k++)
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
printf("A MATRIX\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%5d",a[i][j]);
}
printf("\n");
}
printf("B MATRIX\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%5d",b[i][j]);
}
printf("\n");
}
printf("Elements after multiplication\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
printf("%5d",c[i][j]);
}
printf("\n");
}
}
else
printf("Mutliplication Not Possible for given matrices!");
getch();
}
Output:
Enter order of matrix A for m & n
2 2
Enter a[0][0] element: 1
Enter a[0][1] element: 2
Enter a[1][0] element: 3
Enter a[1][1] element: 4
Enter order of matrix B for p & q
2 2
Enter b[0][0] element: 2
Enter b[0][1] element: 3
Enter b[1][0] element: 4
Enter b[1][1] element: 5
A MATRIX
1 2
3 4
B MATRIX
2 3
4 5
Elements after multiplication
10 13
22 29
Strings Handling
A collection of characters is called as string. In the absence of string data type to store
strings in C we have to simulate string using an array of characters. Any group of
characters (except double quote sign) defined between double quotation marks is a
constant string.
Character strings are often used to build meaningful and readable programs. The
common operations performed on character strings are:
Reading and writing strings
Combining strings together
Copying one string to another
Comparing strings for equality
Extracting a portion of a string
Declaring a String
An array of characters is also a collection of characters. So an array of characters is used
to represent a string in C. For example, to store a name, which may be up to 50
characters, you would declare a string as follows:
/* name can contain up to 50 characters */
char name[50];
/* to store 10 names where each name can contain 20 characters */
char names[10][20];
(2) puts()
The function puts() writes a string argument onto the screen. The puts() can only
output a string of characters. It takes less space and runs faster than printf().
Syntax: puts(variable);
fflush(stdin):
The fflush(stdin) is a standard library function, which is used to clear the buffer, which it
receives as a parameter.
Syntax: fflush(<std.buf.ref.>);
strlen() function
This function counts and returns the number of characters in a string. The length does not
include a null character.
Syntax: len = strlen(string);
where len is integer variable which receives the value of length
of the string.
Example: Program to find length of the string using strlen() function.
#include<stdio.h>
#include<string.h>
main()
{
char name[100];
int length;
printf("Enter a string: ");
gets(name);
length = strlen(name);
printf("\nNumber of characters in the string is %d",length);
getch();
}
Output:
Enter a string: peter
Number of characters in the string is 5
strlwr() function
This function converts all characters in a string from uppercase to lowercase.
Syntax: strlwr(string);
For Example: strlwr("EXFORSYS");
converts to exforsys.
strupr() function
This function converts all characters in a string from lowercase to uppercase.
Syntax: strupr(string);
For Example: strupr("exforsys");
converts to EXFORSYS.
Example: Program to convert lowercase to uppercase and uppercase to lowercase.
#include<stdio.h>
#include<string.h>
main()
{
char name[100];
clrscr();
printf("Enter a string: ");
gets(name);
printf("\nUppercase String: ");
puts(strupr(name));
strlwr(name);
printf("\nLowercase String: ");
puts(name);
getch();
}
Output:
Enter a string: peter
Uppercase String: PETER
Lowercase String: peter
strrev() function
This function reverses the characters in a string.
Syntax: strrev(string);
For Example: strrev("exforsys");
reverses the characters to sysrofxe.
strcpy() function
C does not allow to assign the characters to a string directly as in the statement
name="exforsys"; instead use the strcpy() function found in most compilers.
Syntax: strcpy(string1,string2);
For Example: strcpy(name,"exforsys");
String exforsys is assigned to the string called name.
strcmp() function
In C we cannot directly compare the value of 2 strings in a condition like
if(string1==string2)
Most libraries however contain the strcmp() function, which returns a zero if 2 strings are
equal, or a non zero number (>0 or <0) if the strings are not same.
Syntax: strcmp(string1,string2);
string1 and string2 may be variables or constants. Some computers
return a negative value if string1 is alphabetically less than the
second and a positive if the string1 is greater than the second.
For Example:
strcmp("their","there");
will return -9 which is the numeric difference between
ASCII 'i' and ASCII 'r'.
strcmp("the","The");
will return 32 which is the numeric difference between
ASCII 't' and ASCII 'T'.
strcmp("hello","hello");
will return 0 as two strings are equal.
strcmpi() function
This function is same as strcmp() which compares 2 strings but not case sensitive.
Syntax: strcmpi(string1,string2);
For Example:
strcmpi("the","THE");
will return 0 as it ignores case of the string.
Example: Program to check whether given string is palindrome or not.
#include<stdio.h>
#include<string.h>
main()
{
char name1[20],name2[20];
clrscr();
printf("Enter a string: ");
gets(name1);
strcpy(name2,name1); strrev(name2);
printf("Reversed String is ",name2);
if(strcmp(name1,name2) == 0)
printf("String is Palindrome");
else
printf("String is Not Palindrome");
getch();
}
Output:
Enter a string: peter
Reversed String: retep
String is not Palindrome
strcat() function
When you combine two strings, you add the characters of one string to the end of other
string. This process is called concatenation. The strcat() function joins 2 strings together. It
takes the following form:
Syntax: strcat(string1,string2);
When the function strcat is executed string2 is appended to string1, the string at string 2
remains unchanged.
For Example:
strcat(st1,"hello ");
strcat(st2,"world");
printf("%s",strcat(st1,st2));
From the above program segment of value of st1 becomes "hello world".
The string at st2 remains unchanged as "world".
Example: Program to sort an array of 10 strings
#include<stdio.h>
#include<string.h>
main()
{
char names[10][20];
int i,j;
char temp[20];
clrscr();
printf("Enter array of strings:\n");
for(i=0;i<10;i++)
gets(names[i]);
for(i=0;i<9;i++)
for(j=i+1;j<10;j++)
if(strcmp(names[i],names[j])>0)
{ strcpy(temp,names[i]);
strcpy(names[i],names[j]);
strcpy(names[j],temp);
}
printf("Sorted array of strings: \n");
for(i=0;i<10;i++)
puts(names[i]);
}
Output:
Enter array of strings:
santosh
anand
praneeth
manohar
naidu
hari
rajesh
aditya
julie
pavan
Sorted array of strings:
aditya
anand
hari
julie
manohar
naidu
pavan
praneeth
rajesh
santosh
strstr() function
This function returns the address (pointer) in string1 where string2 is starting in string1.
Syntax: strstr(string1,string2);
strchr() function
This function returns the address (pointer) of first occurrence of character ch in string.
Syntax: strchr(string,ch);
Sample C Programs for String Operations without using String Functions
Example: Program to read a line of text
#include<stdio.h>
main()
{
char line[81],character;
int c=0;
clrscr();
printf("Enter text. Press Enter at end\n");
do {
character = getchar();
line[c] = character;
c++;
}
while(character!='\n');
c=c-1;
line[c] = '\0';
printf("\n%s\n",line);
getch();
}
Output:
Enter text. Press Enter at end
This program reads a string and prints.
This program reads a string and prints.
Example: Program to Accept a string and display string in uppercase.
#include<stdio.h>
main()
{
char st[20];
int i;
clrscr();
/* accept a string */
printf("Enter a string: ");
gets(st);
/* display it in upper case */
for ( i = 0 ; st[i] != '\0'; i++)
if ( st[i] >= 'a' && st[i] <= 'z' )
putch( st[i] - 32);
else
putch( st[i]);
getch();
} Output:
Enter a string: c programming
C PROGRAMMING
Example: Program to write string using %s format.
#include<stdio.h>
main()
{
char country[15]="United Kingdom";
clrscr();
printf("\n\n");
printf("-------------------\n");
printf("|%15s|\n",country);
printf("|%5s|\n",country);
printf("|%15.6s|\n",country);
printf("|%.6s|\n",country);
printf("|%15.0s|\n",country);
printf("|%.3s|\n",country);
printf("|%s|\n",country);
printf("------------------\n");
getch();
}
Output:
------------------
| United Kingdom|
|United Kingdom|
| United|
|United|
| |
|Uni|
|United Kingdom|
------------------
Example: Program to find length of the string.
#include<stdio.h>
main()
{
char str[20];
int i = 0;
clrscr();
printf("\nEnter any string: ");
gets(str);
while (str[i] != '\0') i++;
printf("\nLength of string: %d", i);
getch();
}
Output:
Enter any string: ANIL NEERUKONDA
Length of string: 15
Example: Program to accept a string and display it in reverse.
#include<stdio.h>
main()
{
char st[20];
int i;
clrscr();
printf("Enter a string: "); /* accept a string */
gets(st);
/* get length of the string */
for ( i = 0 ; st[i] != '\0'; i++);
/* display it in reverse order */
for ( i -- ; i >= 0 ; i --)
putch(st[i]);
getch();
}
Output:
Enter a string: HELLO WORLD
DLROW OLLEH
Example: Program to Concatenate of 2 Strings
#include<stdio.h>
#include<conio.h>
main()
{
char string1[30], string2[20];
int i, length=0, temp;
printf("Enter the Value of String1: \n");
gets(string1);
printf("\nEnter the Value of String2: \n");
gets(string2);
for(i=0; string1[i]!='\0'; i++)
length++;
temp = length;
for(i=0; string2[i]!='\0'; i++)
{
string1[temp] = string2[i]; temp++;
}
string1[temp] = '\0';
printf("\nThe concatenated string is:\n");
puts(string1);
getch();
}
Output:
Enter the Value of String1:
C Language
Enter the Value of String2:
is good
The concatenated string is:
C Language is good
Example: Program to Copy one string to another string.
#include <stdio.h>
#include <conio.h>
main()
{
char string1[20], string2[20];
int i;
clrscr();
printf("Enter the value of STRING1: \n");
gets(string1);
for(i=0; string1[i]!='\0'; i++)
string2[i]=string1[i];
string2[i]='\0';
printf("\nThe value of STRING2 is:\n");
puts(string2);
getch();
}
Output:
Enter the value of STRING1:
c programs are cool
The value of STRING2 is:
c programs are cool
Example: Program to Compare two given strings.
#include<stdio.h>
main()
{ char string1[15],string2[15];
int i,temp = 0;
clrscr();
printf("Enter the string1 value:\n");
gets(string1);
printf("\nEnter the String2 value:\n");
gets(string2);
for(i=0;string1[i] != ‘\0’;i++) {
if(s1[i] == s2[i])
temp = 1;
else
temp = 0;
}
if(temp==1)
printf("Both strings are same.");
else
printf("Both strings not same.");
getch();
}
Output1:
Enter the string1 value:
c programs
Enter the String2 value:
cprograms
Both strings not same.
Output2:
Enter the string1 value:
c programs
Enter the String2 value:
c programs
Both strings are same.
Example: Program to print alphabet set in decimal and character form.
#include<stdio.h>
main()
{
char c;
clrscr();
printf("\n\n"); for(c=65;c<=122;c=c+1)
{
if(c>90 && c<97)
continue;
printf("%5d - %c",c,c);
}
printf("\n");
getch();
}
Output:
65 - A 66 - B 67 - C 68 - D 69 - E 70 - F 71 - G 72 - H
73 -I 74 - J 75 - K 76 - L 77 - M 78 - N 79 - O 80 - P
81 - Q 82 - R 83 - S 84 - T 85 - U 86 - V 87 - W 88 - X
89 - Y 90 - Z 97- a 98 - b 99 - c 100 - d 101 - e 102 - f
103 - g 104 - h 105 - i 106 - j 107 - k 108 - l 109 - m 110 - n
111 - o 112 - p 113 - q 114 - r 115 - s 116 - t 117 - u 118 - v
119 - w 120 - x 121 - y 122 - z
UNIT – 9
Pointers
9.1 Fundamentals
9.2 Pointer Declarations and initialization
9.3 Accessing value through a pointer
9.4 Pointer to a pointer
9.5 Similarities between Pointers and one dimensional arrays
9.6 Pointer with one dimensional and two dimensional arrays
9.7 Passing Pointers to Functions
9.8 Dynamic Memory Allocation
Fundamentals
Pointer is a variable that stores/hold address of another variable of same data type/ t is also known
as locator or indicator that points to an address of a value. A pointer is a derived data type in C.
Pointer allows references to function and thereby helps in passing of function as arguments to other
function.
Declaration of Pointer
data_type* pointer_variable_name;
int* p;
Note: void type pointer works with all data types, but isn't used often.
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to pointer variable. Pointer
variable contains address of variable of same data type
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or,
As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4.
The value of number variable is 50. But the address of pointer variable p is aaa3.
By the help of * (indirection operator), we can print the value of pointer variable p.
Dereferencing of Pointer
Once a pointer has been assigned the address of a variable. To access the value of variable, pointer is
dereferenced, using the indirection operator *.
int a,*p;
a = 10;
p = &a;
printf("%d",*p); //this will print the value of a.
printf("%d",*&a); //this will also print the value of a.
printf("%u",&a); //this will print the address of a.
printf("%u",p); //this will also print the address of a.
printf("%u",&p); //this will also print the address of p.
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
Normal variable stores the value whereas pointer variable stores the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.
Two pointers can be subtracted to know how many elements are available between these two
pointers.
Example:
#include <stdio.h>
#include <conio.h>
void main(){
int number=50;
int *p;
clrscr();
p=&number;//stores the address of number variable
printf("Address of number variable is %x \n",&number);
printf("Address of p variable is %x \n",p);
printf("Value of p variable is %d \n",*p);
getch();
}
Output
Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50
Example:
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
Output:
Address of var is: 00XBBA77
Address of var is: 00XBBA77
Address of pointer p is: 77221111
Value of pointer p is: 00XBBA77
Value of var is: 10
Value of var is: 10
Value of var is: 10
NULL Pointer
A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any
address to be specified in the pointer at the time of declaration, you can assign NULL value.
Or
It is always a good practice to assign a NULL value to a pointer variable in case you do not have an
exact address to be assigned. This is done at the time of variable declaration. A pointer that is
assigned NULL is called a null pointer.int *p=NULL;
Note: The NULL pointer is a constant with a value of zero defined in several standard libraries/ in
most the libraries, the value of pointer is 0 (zero)
Example:
The value of ptr is 0
Here variable arr will give the base address, which is a constant pointer pointing to the element,
arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
We can declare a pointer of type int to point to the array arr.
int arr[5]={ 1, 2, 3, 4, 5 };
int *p;
p = arr;
or p = &arr[0]; //both the statements are equivalent.
Now we can access every element of array arr using p++ to move from one element to another.
NOTE : You cannot decrement a pointer once incremented. p-- won't work.
Pointer to Array
we can use a pointer to point to an Array, and then we can use that pointer to access the array. Lets
have an example,
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i=0; i<5; i++)
{
printf("%d", *p);
p++;
}
In the above program, the pointer *p will print all the values stored in the array one by one. We can
also use the Base address (a in above case) to act as pointer and print all the values.
Relation between Arrays and Pointers
Consider an array:
int arr[4];
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.
&arr[0] is equivalent to arr
Since, the addresses of both are the same, the values of arr and &arr[0] are also the same.
arr[0] is equivalent to *arr (value of an address of the pointer)
Similarly,
&arr[1] is equivalent to (arr + 1) AND, arr[1] is equivalent to *(arr + 1).
&arr[2] is equivalent to (arr + 2) AND, arr[2] is equivalent to *(arr + 2).
&arr[3] is equivalent to (arr + 3) AND, arr[3] is equivalent to *(arr + 3).
.
.
&arr[i] is equivalent to (arr + i) AND, arr[i] is equivalent to *(arr + i).
Example: Program to find the sum of six numbers with arrays and pointers
#include <stdio.h>
int main()
{
int i, classes[6],sum = 0;
printf("Enter 6 numbers:\n");
for(i = 0; i < 6; ++i)
{
// (classes + i) is equivalent to &classes[i]
scanf("%d",(classes + i));
// *(classes + i) is equivalent to classes[i]
sum += *(classes + i);
}
printf("Sum = %d", sum);
return 0;
}
Output
Enter 6 numbers:
2
3
4
5
3
4
Sum = 21
Pointer Arithmetic and Arrays
pointer holds address of a value, so there can be arithmetic operations on the pointer variable.
There are four arithmetic operators that can be used on pointers:
o Increment(++)
o Decrement(--)
o Addition(+)
o Subtraction(-)
Increment pointer:
1. Incrementing Pointer is generally used in array because we have contiguous memory in array and
we know the contents of next memory location.
2. Incrementing Pointer Variable Depends Upon data type of the Pointer variable.
++Address = Address
Pictorial Representation :
Note :
32 bit
For 32 bit int variable, it will increment to 2 byte.
64 bit
For 64 bit int variable, it will increment to 4 byte.
Example:
#include <stdio.h>
void main(){
int number=50;
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ;
/* output the returned value */
printf( "Average value is: %f ", avg );
return 0;
}
double getAverage(int arr[], int size) {
int i;
double avg;
double sum = 0;
for (i = 0; i < size; ++i) {
sum += arr[i];
}
avg = sum / size;
return avg;
}
Output
Average value is: 214.400000
Example2: pass an entire array to a function argument
#include <stdio.h>
myfuncn( int *var1, int var2)
{
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(&var_arr, 7);
return 0;
}
Output
Value of var_arr[0] is: 11
Value of var_arr[1] is: 22
Value of var_arr[2] is: 33
Value of var_arr[3] is: 44
Value of var_arr[4] is: 55
Value of var_arr[5] is: 66
Value of var_arr[6] is: 77
Example: Call by value method –
#include <stdio.h>
disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'j'};
for (int x=0; x<=10; x++)
{
/* I‟m passing each element one by one using subscript*/
disp (arr[x]);
}
return 0;
}
Output:
abcdefghij
In this method of calling a function, the actual arguments gets copied into formal arguments. In this
example actual argument(or parameter) is arr[x] and formal parameter is ch.
Example: Call by reference method: Using pointers
#include <stdio.h>
disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<=10; i++)
{
/* I‟m passing element‟s address*/
disp (&arr[i]);
}
return 0;
}
Output:
1234567890
Array of Pointers
An array of pointers would be an array that holds memory locations. An array of pointers is an
indexed set of variables in which the variables are pointers (a reference to a location in memory).
Syntax:
data_type_name * variable name
Example
int *ptr[MAX];
Array alpha[] Pointer a
alpha[0] *a
alpha[1] *(a+1)
alpha[2] *(a+2)
alpha[3] *(a+3)
alpha[n] *(a+n)
#include <conio.h>
main()
{ clrscr();
int *array[3];
int i;
array[0] = &x;
array[1] = &y;
array[2] = &z;
getch();
return 0; }
Output
Example3:
#include <stdio.h>
const int MAX = 4;
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i = 0;
for ( i = 0; i < MAX; i++) {
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
Output:
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
Example4:
#include <stdio.h>
int main()
{
char *fruit[] = {
"watermelon",
"banana",
"pear",
"apple",
"coconut",
"grape",
"blueberry"
};
int x;
for(x=0;x<7;x++)
puts(fruit[x]);
return(0);
}
Pointers to Void and to Functions
Pointers to Void
Note:
1. Suppose we have to declare integer pointer, character pointer and float pointer then we need to
declare 3 pointer variables.
2. Instead of declaring different types of pointer variable it is feasible to declare single pointer
variable which can act as integer pointer,character pointer.
A pointer variable declared using a particular data type can not hold the location address of variables
of other data types. It is invalid and will result in a compilation error.
Ex:- char *ptr;
int var1;
ptr=&var1; // This is invalid because „ptr‟ is a character pointer variable.
Here comes the importance of a “void pointer”. A void pointer is nothing but a pointer variable
declared using the reserved word in C „void‟.
Void Pointer Basics :
3. In C General Purpose Pointer is called as void Pointer.
7. The compiler has no idea what type of object a void Pointer really points to ?
Void pointer: A void pointer is a pointer that has no associated data type with it. A void pointer can
hold address of any type and can be typcasted to any type. Special type of pointer called void
pointer or general purpose pointer.
Declaration of void pointer
void * pointer_name;
Void pointer example
void *ptr; // ptr is declared as Void pointer
char cnum;
int inum;
float fnum;
ptr = &cnum; // ptr has address of character data
ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data
Advantages of void pointers:
1) malloc() and calloc() return void * type and this allows these functions to be used to allocate
memory of any data type (just because of void *)
int main(void)
{
// Note that malloc() returns void * which can be
// typecasted to any type like int *, char *, ..
int *x = malloc(sizeof(int) * n);
}
2) void pointers in C are used to implement generic functions in C.
#include<stdio.h>
int main()
{
int a = 10;
void *ptr = &a;
printf("%d", *ptr);
return 0;
}
Pointers to functions/ Function Pointers
A pointer to a function points to the address of the executable code of the function.
We can use pointers to call functions and to pass functions as arguments to other
functions.
The type of a pointer to a function is based on both the return type and parameter types of
the function.
A declaration of a pointer to a function must have the pointer name in parentheses.
The function call operator () has a higher precedence than the dereference operator *.
Without them, the compiler interprets the statement as a function that returns a pointer to a
specified return type.
Here double is a return type of function, p2f is pointer name & (double, char) is an argument
list for the function. Which means the first argument for this function should be double and
the second one would be of char type.
Example:
#include<stdio.h>
int sum (int num1, int num2)
{
return sum1+sum2;
}
int main()
{
int (*f2p) (int, int);
f2p = sum;
int op1 = f2p (10, 13);
int op2 = sum (10, 13);
printf("Output 1 – for function call via Pointer: %d",op1);
printf("Output2 – for direct function call: %d", op2);
return 0;
}
Output:
Output 1 – for function call via Pointer: 23
Output2 – for direct function call: 23
You would have noticed that the output of both the statements is same – f2p(10, 13) ==
sum(10, 13)
which means in generic sense you can write it out as:
pointer_name(argument list) == function(same argument list)
wherein pointer_name is declared as:
return_type(*pointer_name)(argument list);
pointer_name = function_name(argument list);
Memory Allocation Functions
The concept of dynamic memory allocation in c language enables the C programmer to
allocate memory at runtime.
Or
The process of allocating memory at runtime is known as dynamic memory allocation.
Library routines known as "memory management functions" are used for allocating and
freeing memory during execution of a program. These functions are defined in stdlib.h.
Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
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.
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
calloc()
calloc stands for "contiguous allocation".
Calloc() is another memory allocation function that is used for allocating memory at runtime. calloc
function is normally used for allocating memory to derived data types such as arrays and structures.
The calloc() function allocates multiple block of requested memory.
It initially initialize (sets) all bytes to zero.If it fails to locate enough space( memory) it returns a
NULL pointer. 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.
Syntax
ptr = (cast-type*)calloc(n/number, element-size);
calloc() required 2 arguments of type count, size-type.
Count will provide number of elements; size-type is data type size
Example
int*arr;
arr=(int*)calloc(10, sizeof(int)); // 20 byte
cahr*str;
str=(char*)calloc(50, siceof(char)); // 50 byte
Example
struct employee
{
char *name;
int salary;
};
typedef struct employee emp;
emp *e1;
e1 = (emp*)calloc(30,sizeof(emp));
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) calloc(num, sizeof(int));
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
calloc() malloc()
calloc() initializes the allocated memory with 0 malloc() initializes the allocated memory with
value. garbage values.
Number of arguments is 2 Number of argument is 1
Syntax : Syntax :
(cast_type *)calloc(blocks , size_of_block); (cast_type *)malloc(Size_in_bytes);
syntax
ptr=realloc(ptr, new-size)
Example
int *x;
x=(int*)malloc(50 * sizeof(int));
x=(int*)realloc(x,100); //allocated a new memory to variable x
Example
void*realloc(void*, size-type);
int *arr;
arr=(int*)calloc(5, sizeof(int));
.....
........
....
arr=(int*)realloc(arr,sizeof(int)*10);
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Address of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\t",ptr + i);
printf("\nEnter new size of array: ");
scanf("%d", &n2);
ptr = realloc(ptr, n2);
for(i = 0; i < n2; ++i)
printf("%u\t", ptr + i);
return 0;
}
free()
When your program comes out, operating system automatically release all the memory allocated by
your program but as a good practice when you are not in need of memory anymore then you should
release that memory by calling the function free().
The memory occupied by malloc() or calloc() functions must be released by calling free() function.
Otherwise, it will consume memory until program exit.
Or
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:
free(ptr);
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
}
Output
Example2
#include <stdio.h>
void main(int argc, char *argv[] ) {
printf("Program name is: %s\n", argv[0]);
if(argc < 2){
printf("No argument passed through command line.\n");
}
else{
printf("First argument is: %s\n", argv[1]);
}
}
Output
program.exe hello
Program name is: program
First argument is: hello
Note
But if you pass many arguments within double quote, all arguments will be treated as a single
argument only.
Example
./program "hello c how r u"
Program name is: program
First argument is: hello c how r u
You can write your program to print all the arguments. In this program, we are printing only
argv[1], that is why it is printing only one argument.
Example3
#include<stdio.h>
#include<conio.h>
void main(int argc, char* argv[])
{
int i;
clrscr();
printf("Total number of arguments: %d",argc);
for(i=0;i< argc;i++)
{
printf("\n %d argument: %s",i,argv[i]);
getch();
}
}
Output
C:/TC/BIN>TCC mycmd.c
C:/TC/BIN>mycmd 10 20
Number of Arguments: 3
0 arguments c:/tc/bin/mycmd.exe
1 arguments: 10
2 arguments: 20
Note: In above output we passed two arguments but is show "Number of Arguments: 3" because
argc take Number of arguments in the command line including program name. So here two
arguments and one program name (mycmd.exe) total 3 arguments.
Example4:
#include<stdio.h>
#include<conio.h>
void main(int argc, char* argv[])
{
clrscr();
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
getch();
}
Output
C:/TC/BIN>TCC mycmd.c
C:/TC/BIN>mycmd this is a program
Structure
During programming, there is a need to store multiple logically related elements
under one roof. For instance, an employee’s details like name, employee number,
and designation need to be stored together. In such cases, the C language provides
structures to do the job for us.
Structure is a user defined data type which hold or store heterogeneous/different types data item
or element in a single variable. It is a Combination of primitive and derived data type.
A structure is a collection of one or more data items of different data types, grouped together under a
single name.
Variables inside the structure are called members of structure.
Each element of a structure is called a member.
struct keyword is used to define/create a structure. struct define a new data type which is a
collection of different type of data.
Syntax to Define a Structure in C
struct structName
{
// structure definition
Data_type1 member_name1;
Data_type2 member_name2;
Data_type2 member_name2;
};
Below is the description of Structure in C programming
Description of the Syntax
Keyword struct: The keyword struct is used at the beginning while defining a
structure in C. Similar to a union, a structure also starts with a keyword.
structName: This is the name of the structure which is specified after the keyword
struct.
data_Type: The data type indicates the type of the data members of the structure.
A structure can have data members of different data types.
member_name: This is the name of the data member of the structure. Any
number of data members can be defined inside a structure. Each data member is
allocated a separate space in the memory.
In the above program, a structure named Patient is defined. It has three data
members- P_name, P_age, and P_gender. These data members have not been
allocated any space in the memory yet. The variables p1 and p2 are the structure
variables declared in the main function.
As soon as these variables are created, they get a separate copy of the structure’s
members with space allocated to them in the memory. Both p1 and p2 are
accessing their copies of the structure’s members to modify them using the dot
operator.
In the above program, the function passByValue() accepts the structure’s variable
P1 as an argument. This argument is passed by value. When the function makes a
modification in the member ID, this modification does not affect the P1’s version
of ID. The reason is that in the case of pass-by-value, only a copy of the members is
passed to the function. So, any changes made by the function do not reflect in the
original copy.
Designated Initialization
In the C99 standard, there is a unique feature that is not available in other
standards like C90 or GNU C++. Designated initialization is supported
for array, union, and structure in C. To understand the working of designated
initialization, consider the following example of array initialization at the time of
declaration.
int my_arr[5] = {10, 20, 30, 40, 50};
// my_arr[0] = 10, my_arr[1] = 20, ..., my_arr[5] = 50.
In the above array initialization, all array elements are initialized in the fixed order.
This means that the element at index 0 is initialized first, then the index 1 element
is initialized, and so on.
These array elements can also be initialized in any random order, and this method
is called designated initialization. Consider the following example which initializes
the array elements in random order.
int a[5] = {[3] = 30, [2] = 20 };
// OR
int a[5] = {[3]30 , [2]20 };
The following program illustrates the designated initialization of a structure in C.
#include <stdio.h>
struct rectangle
{
int length, breadth, height;
};
int main()
{
// Examples of initialization using designated initialization
struct rectangle r1 = {.breadth = 10, .height = 5, .length = 6};
struct rectangle r2 = {.breadth = 20};
printf("The values of r1 are: \n");
printf("length = %d, breadth = %d, height = %d\n", r1.length, r1.breadth,
r1.height);
printf("The values of r2 are: \n");
printf("length = %d, breadth = %d, height = %d\n\n", r2.length, r2.breadth,
r2.height);
return 0;
}
In the above example, the structure members- length, breadth, and height are
initialized in a random order using the designated initialization. This type of
initialization would throw an error in the compiler of other standards and even C++
does not support this functionality.
Array of Structures
Array of structures to store much information of different data types. Each
element of the array representing a structure variable. The array of structures is
also known as collection of structures.
Ex : if you want to handle more records within one structure, we need not specify
the number of structure variable. Simply we can use array of structure variable to
store them in one structure variable.
Suppose you need to store the details of students like name, class, and roll number
in your database. Now, the first thing that comes to your mind would be to create
a structure variable and access the student details. This method is practical for a
few students only, but what if the total number of students is 100 or something. It
is not convenient to create 100 separate structure variables for 100 students. In
such cases, we use an array of structures.
Just like other data types (mostly primitive), we can also declare an array of
structures. An array of structures acts similar to a normal array. However, there is
one thing to be kept in mind and that is the name of the structure followed by the
dot operator(.) and the name of the array has to be mentioned to access an array
element.
The following example illustrates the working of the array of structures in C.
#include <stdio.h>
// structure definition
struct Student
{
// data members
char name[10];
int marks;
};
// declare an array of the structure Student.
struct Student stu[3];
int i, j;
// function to read the values
// from the user and print them.
void print()
{
// read input from the user.
for (i = 0; i < 3; i++)
{
printf("\nEnter the record of Student %d\n", i + 1);
printf("\nStudent name: ");
scanf("%s", stu[i].name);
printf("Enter Marks: ");
scanf("%d", &stu[i].marks);
}
// print the details of each student.
printf("\nDisplaying Student record\n");
for (i = 0; i < 3; i++)
{
printf("\nStudent name is %s", stu[i].name);
printf("\nMarks is %d", stu[i].marks);
}
}
int main()
{
// function call
print();
return 0;
}
In the above example, we have created a structure Student that holds student
names and marks. We have initialized an array stu of size 3 to get the names and
marks of 3 students. Note that unlike the usual array in C, the array of structures in
C is initialized by using the names of the structure as a prefix.
Structure Pointer
A pointer structure is a variable that holds the address of the memory block of the
structure. It is similar to other pointer variables like a pointer to an int or a pointer
to a float.
Consider the following code snippet.
struct point
{
// data member
int num;
};
int main()
{
// struct1 variable var
struct struct1 var;
// pointer variable
struct point *ptr = &var;
return 0;
}
Here, var is the structure variable of struct1 and ptr is the pointer variable. The ptr
is storing the address of the var. In the case of a pointer to a structure, the
members can be accessed using the arrow (->) operator.
The following example illustrates the pointer to a structure in C.
#include<stdio.h>
struct myStruct
{
int x, y;
};
int main()
{
struct myStruct var1 = {1, 2};
// var2 is a pointer to structure var1.
struct myStruct *var2 = &var1;
// Accessing data members of myStruct using a structure pointer.
printf("%d %d", var2->x, var2->y);
return 0;
}
In the above example, the structure myStruct has a variable var1. The var2 is the
pointer variable that stores the address of this structure variable.
Nested Structures
The C programming language allows the nesting of the structure. This can be done
by using one structure into the body of another structure. Nesting of multiple
separate structures enables the creation of complex data types.
For instance, you need to store the information of multiple students. Now the data
members of the structure may be student name, student class, and student roll
number. Now class can have multiple subparts like standard, section, and stream.
Such types of cases can use nested structures to a great extent.
A structure in C can be nested in two ways:
By Creating a Separate Structure
We can create two separate, let's say struct1 and struct2 structures, and then nest
them. If you want to nest struct2 in struct1, then it is necessary to create struct2
variable inside the primary structure i.e., struct1. The nested structure would be
used as a data member of the primary structure.
Consider the following code snippet.
// structure 2
struct struct2
{
// data members of struct2
};
// structure 1
struct struct1
{
// data members of struct1
// struct2 variable
struct struct2 obj2;
}obj1; // struct1 variable
Here, struct1 is the primary structure and struct2 is the secondary one. It is clearly
observable that the variable of struct2 is created inside struct1.
Example
The following example illustrates the nesting of a structure in C by creating a
separate structure.
#include <stdio.h>
// structure 2
struct class_details
{
int standard;
char section;
char stream[20];
};
// structure 1
struct Student
{
char name[20];
int roll_num;
// nested structure 2 in structure 1
// class_details variable Class
struct class_details Class;
};
int main()
{
// Student variable stu
struct Student stu;
// read the input from user
printf("Enter details of the student: \n");
scanf("%s %d %d %c %c",
&stu.name,
&stu.roll_num,
&stu.Class.standard,
&stu.Class.section,
&stu.Class.stream);
// display the input info
printf("The Student's details are: \n");
printf("Name: %s\nRoll_num: %d\nStandard: %d\nSection: %c\nStream %s: ",
stu.name,
stu.roll_num,
stu.Class.standard,
stu.Class.section,
stu.Class.stream);
return 0;
}
In the above example, we created two structures, Student and class_details. The
structure Student contains the basic information about the student while the
structure class_details contains the information about the class of the student
specifically. The class_details structure is nested inside the Student structure by
creating the object inside it so that all the data members of the class_details can
be accessed by the Student structure too.
Here, the logic and the data members are exactly the same as in the previous
example. The major difference here is that instead of creating a separate structure
of details of the class, we created an embedded structure. You can observe that
even though the methods are different, the outputs of both methods are exactly
the same.
Data hiding is not possible in structures. Structure in C does not permit any data
members to be hidden and allows every function to access them.
You can not define member functions inside a structure in C. Structure in C only
allows the definition of data members inside it and prohibits functions.
The concept of access modifiers is absent in the C language. So data members in a
structure are always public to all the functions outside that structure.
Structure in C does not permit the creation of static members and constructors
inside its body.
Difference between Structure and Union
Unions
A union is a special data type available in C that allows to store different data types
in the same memory location.
Unions are conceptually similar to structures. The syntax of union is also similar to
that of structure. The only difference is in terms of storage. In structure each
member has its own storage location, whereas all members of union use a single
shared memory location which is equal to the size of its largest data member.
We can access only one member of union at a time. We can‟t access all member
values at the same time in union. But, structure can access all member values at
the same time. This is because, Union allocates one common storage space for all
its members. Where as Structure allocates storage space for all its members
separately.
syntax
union union_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example
union employee
{ int id;
char name[50];
float salary;
};
Example
#include <stdio.h>
#include <string.h>
union employee
{ int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//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);
return 0;
}
Output:
employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal
As you can see, id gets garbage value because name has large memory size. So only
name will have actual value.
Example
#include <stdio.h>
#include <conio.h>
union item
{
int a;
float b;
char ch;
};
int main( )
{
union item it;
it.a = 12;
it.b = 20.2;
it.ch='z';
clrscr();
printf("%d\n",it.a);
printf("%f\n",it.b);
printf("%c\n",it.ch);
getch();
return 0;
}
Output
-26426
20.1999
z
As you can see here, the values of a and b get corrupted and only variable c prints
the expected result. Because in union, the only member whose value is currently
stored will have the memory.
Bit-Fields
Syntax
struct {
type [member_name] : width ;
};
The following table describes the variable elements of a bit field –
Elements Description
type An integer type that determines how
a bit-field's value is interpreted. The
type may be int, signed int, or
unsigned int.
member_name The name of the bit-field.
width The number of bits in the bit-field.
The width must be less than or equal
to the bit width of the specified type
The variables defined with a predefined width are called bit fields. A bit field can
hold more than a single bit; for example, if you need a variable to store a value
from 0 to 7, then you can define a bit field with a width of 3 bits as follows −
struct {
unsigned int age : 3;
} Age;
The above structure definition instructs the C compiler that the age variable is
going to use only 3 bits to store the value. If you try to use more than 3 bits, then it
will not allow you to do so. Let us try the following example –
#include <stdio.h>
#include <string.h>
struct {
unsigned int age : 3;
} Age;
int main( ) {
Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", Age.age );
return 0;
}
Output
Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
Age.age : 0
typedef
The typedef is a keyword that allows the programmer to create a new data type
name for an existing data type. So, the purpose of typedef is to redefine the name
of an existing variable type.
Syntax
typedef datatype alias_name;
Example of typedef
#include<stdio.h>
#include<conio.h>
typedef int Intdata; // Intdata is alias name of int
void main()
{
int a=10;
Integerdata b=20;
typedef Intdata Integerdata; // Integerdata is again alias name of Intdata
Integerdata s;
clrscr();
s=a+b;
printf("\n Sum:= %d",s);
getch();
}
Output
Sum: 20
Advantages of typedef :
1 : Provides a meaningful way of declaring the variable.
2 : Increase the readability of the program.
#include<stdio.h>
#include<conio.h>
void main()
{
typedef int digits;
digits a,b,sum;
clrscr();
printf("Enter a and b values:");
scanf("%d%d",&a,&b);
sum=a+b;
printf("The sum is:%d",sum);
getch();
}
Note: By using typedef only we can create the alias name and it is under control of
compiler.
Application of typedef
typedef can be used to give a name to user defined data type as well. Lets see its
use with structures.
typedef struct
{
type member1;
type member2;
type member3;
} type_name ;
Here type_name represents the stucture definition associated with it. Now this
type_name can be used to declare a variable of this stucture type.
type_name t1, t2 ;
Example of structure definition using typedef
#include<stdio.h>
#include<conio.h>
#include<string.h>
typedef struct employee
{
char name[50];
int salary;
} emp ;
void main( )
{
emp e1;
printf("\nEnter Employee record\n");
printf("\nEmployee name\t");
scanf("%s",e1.name);
printf("\nEnter Employee salary \t");
scanf("%d",&e1.salary);
printf("\nstudent name is %s",e1.name);
printf("\nroll is %d",e1.salary);
getch();
}
typedef and Pointers
typedef can be used to give an alias name to pointers also. Here we have a case in
which use of typedef is beneficial during pointer declaration.
In Pointers * binds to the right and not the left.
int* x, y ;
By this declaration statement, we are actually declaring x as a pointer of type int,
whereas y will be declared as a plain integer.
typedef int* IntPtr ;
IntPtr x, y, z;
But if we use typedef like in above example, we can declare any number of
pointers in a single statement.
NOTE : If you do not have any prior knowledge of pointers, do study Pointers first.
Enumerations
An enum is a keyword, it is an user defined data type. All properties of integer are
applied on Enumeration data type so size of the enumerator data type is 2 byte. It
work like the Integer.
It is used for creating an user defined data type of integer. Using enum we can
create sequence of integer constant value.
Syntax
enum tagname {value1, value2, value3,....};
In above syntax enum is a keyword. It is a user defiend data type.
In above syntax tagname is our own variable. tagname is any variable name.
There are two main types of files in C programming: text files and binary files. Text files contain data that
is human-readable and can be opened and edited using a text editor. Binary files, on the other hand,
contain non-textual data that is encoded in binary format and is typically processed by computer
programs.
1. What is ASCII Text file?
In C programming, an ASCII text file is a type of text file that uses the ASCII (American Standard Code for
Information Interchange) character set to represent text. ASCII is a standard character encoding that assigns
a unique numerical value to each character, including letters, digits, punctuation marks, and other
symbols. ASCII text files are human-readable and can be opened and edited using a text editor.
In an ASCII text file, each character is represented using a single byte (8 bits) of information, allowing for
a maximum of 256 possible characters. This includes the standard ASCII characters as well as extended
ASCII characters that are specific to certain languages or regions.
2. What is a Binary file?
A binary file is a type of file that contains non-textual data encoded in binary format, meaning that the
data is represented using a sequence of 1s and 0s. Binary files are typically used to store executable code,
images, audio, video, or other types of data that cannot be easily represented as text.
Binary files can be either processed sequentially or can be processed using random access techniques. In C,
processing a file using random access techniques involves moving the current file position to an
appropriate place in the file before reading or writing data.
Importance of File Handling in C Programming
File handling is an important aspect of programming because it allows programs to read data from and
write data to files, which are external storage devices. This is essential for many programs that need to
store data beyond the lifetime of a program’s execution.
Here are some specific reasons why file handling is important in programming:
Persistent Data Storage: Files allow data to be stored outside of the program’s memory, so it can be
accessed even after the program has terminated. This is important for programs that need to save data
between runs, or for programs that need to share data with other programs.
Data Processing: Many programs process large amounts of data, and files provide an efficient means of
storing and processing this data. This is particularly true for programs that work with text or binary files.
Configuration Files: Many programs use configuration files to store settings that are used each time the
program is run. This allows users to customize the behavior of the program without changing the
program’s source code.
Interprocess Communication: Programs running on the same computer can use files to communicate with
each other. This allows programs to share data or coordinate tasks.
DEFINITION:
A file can be defined as a collection of bytes stored on the disk under a name. A file may
contain anything, in the sense the contents of files may be interpreted as a collection of
records or a collection of lines or a collection of instructions etc.
A file is a collection of records. Each record provides information to the user. These files
are arranged on the disk.
FILE is a data type which is a means to identify and specify which file you want to
operate on because you may open several files simultaneously.
When a request is made for a file to be opened, what is returned is a pointer to the
structure FILE. To store that pointer, a pointer variable is declared as follows:
FILE *file_pointer;
where file_pointer points to first character of the opened file.
Opening of a file:
A file needs to be opened when it is to be used for read/write operation. A file is opened
by the fopen() function with two parameters in that function. These two parameters are
file name and file open mode.
Syntax: fopen(filename, file_open_mode);
The fopen function is defined in the “stdio.h” header file. The filename parameter refers
to any name of the file with an extension such as “data.txt” or “program.c” or
"student.dat" and so on.
File open mode refers to the mode of opening the file. It can be opened in ‘read mode’
or ‘write mode’ or ‘append mode’.
The function fopen() returns the starting address of file when the file we are trying to
open is existing (i.e. success) else it returns NULL which states the file is not existing or
filename given is incorrect.
E.g.: FILE *fp;
fp=fopen("data.txt","r");
/*If file exists fp points to the starting address in memory
Otherwise fp becomes NULL*/
if(fp==NULL) printf("No File exists in Directory");
NULL is a symbolic constant declared in stdio.h as 0.
Modes of Operation:
1. "r" (read) mode: open file for reading only.
2. "w" (write) mode: open file for writing only.
3. "a" (append) mode: open file for adding data to it.
4. "r+" open for reading and writing, start at beginning
5. "w+" open for reading and writing (overwrite file)
6. "a+" open for reading and writing (append if file exists)
When trying to open a file, one of the following things may happen:
When the mode is ‘writing’ a file with the specified name is created if the file does
not exist. The contents are deleted, if the file is already exists.
When the purpose is ‘appending’, the file is opened with the current contents safe.
A file with the specified name is created if the file does not exist.
When the purpose is ‘reading’, and if it exists, then the file is opened with the
current contents safe; otherwise an error occurs.
With these additional modes of operation (mode+), we can open and use a number of
files at a time. This number however depends on the system we use.
Closing a file:
A file must be closed as soon as all operations on it have been completed. This ensures
that all outstanding information associated with the file is flushed out from the buffers
and all the links to the file are broken. It also prevents any accidental misuse of file.
Closing of unwanted files might help open the required files. The I/O library supports a
function to do this for us.
Syntax: fclose(file_pointer);
/*This would close the file associated with the FILE pointer file_pointer*/
fcloseall();
/*This would close all the opened files. It returns the number of files it closed. */
fgetc(fp);
The file pointer moves by one character position for every operation of getc and putc.
The getc will return an end-of-file marker EOF, when end of the file has been reached.
Therefore, the reading should be terminated when EOF is encountered.
Example: Program for Writing to and reading from a file
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("Write data to file: \n");
f1 = fopen("test.txt","w");
while((c=getchar())!='@')
putc(c,f1);
/*characters are stored into file until '@' is encountered*/
fclose(f1);
printf("\nRead data from file: \n");
f1 = fopen("test.txt","r"); /*reads characters from file*/
while((c=getc(f1))!=EOF)
printf("%c",c);
fclose(f1);
getch();
}
Example: Program to write characters A to Z into a file and read the file and print the
characters in lowercase.
#include<stdio.h>
main()
{
FILE *f1;
char c;
clrscr();
printf("Writing characters to file... \n");
f1 = fopen("alpha.txt","w");
for(ch=65;ch<=90;ch++)
fputc(ch,f1);
fclose(f1);
printf("\nRead data from file: \n");
f1 = fopen("alpha.txt","r");
/*reads character by character in a file*/
while((c=getc(f1))!=EOF)
printf("%c",c+32); /*prints characters in lower case*/
fclose(f1);
getch();
}
Example: Program to illustrate the append mode of operation for given file.
#include<stdio.h>
main()
{
FILE *f1;
char c,fname[20];
clrscr();
printf("Enter filename to be appended: ");
gets(fname);
printf("Read data from file: \n");
f1 = fopen(fname,"r");
if(f1==NULL)
{
printf("File not found!");
exit(1);
}
else
{
while((c=getc(f1))!=EOF)
printf("%c",c);
}
fclose(f1);
f1 = fopen(fname,"a");
while((c=getchar())!='@')
putc(c,f1);
/*characters are appended into file with existing data until
'@' is encountered*/
fclose(f1);
getch();
}
Reading and Writing Integers getw and putw functions:
These are integer-oriented functions. They are similar to getc and putc functions and are
used to read and write integer values. These functions would be useful when we deal
with only integer data.
The general forms of getw and putw are:
putw: Writes an integer to a file.
putw(integer,fp);
getw: Reads an integer from a file.
getw(fp);
fgets reads characters from current position until new line character is encountered or
len-1 bytes are read from file associated with FILE pointer fp. Places the characters read
from the file in the form of a string into str.
fgets(char *st,int len,FILE *fp);
E.g.: fgets(str,50,fp);
Example: Program to illustrate fgets and fputs function.
#include<stdio.h>
main()
{
FILE *fp;
char s[80];
clrscr();
fp=fopen("strfile.txt","w");
printf("\nEnter a few lines of text:\n");
while(strlen(gets(s))>0)
{
fputs(s,fp);
fputs("\n",fp);
}
fclose(fp);
printf("Content in file:\n");
fp=fopen("strfile.txt","r");
while(!feof(fp))
{
puts(s);
fgets(s,80,fp);
}
fclose(fp);
getch();
}
fprintf and fscanf functions
The functions fprintf and fscanf perform I/O operations that are identical to the familiar
printf and scanf functions, except of course that they work on files. The first argument of
these functions is a file pointer, where specifies the file to be used.
fprintf(): Writes given values into file according to the given format. This is similar to
printf but writes the output to a file instead of console.
fscanf(): Reads values from file and places values into list of arguments. Like scanf it
returns the number of items that are successfully read. When the end of file is reached, it
returns the value EOF.
The general form of fprintf and fscanf isfprintf(file_pointer/stream, “control string”, list);
fscanf(file_pointer/stream, “control string”, list);
where file_pointer is a pointer associated with a file that has been opened for writing.
The stream refers to a stream or sequence of bytes that can be associated with a device or
a file. The following are the available standard file pointers/streams:
stdin refers to standard input device, which is by default keyboard.
stdout refers to standard output device, which is by default screen.
stdprn refers to printer device.
stderr refers to standard error device, which is by default screen.
The control string (format specifier) contains output specifications for the items in the list.
The list may include variables, constants and strings.
E.g.:
fprintf(fp, “%s %d %f”, name, age, 7.5); /*writes to file*/
fprintf(stdout, “%s %d %f”, name, age, 7.5); /*prints data on console*/
fscanf(fp, “%s %d %f”, name, &age, &per); /*reads from file*/
fscanf(stdin, “%s %d %f”, name, &age, &per); /*reads data from console*/
Example: Program to illustrate fprintf and fscanf function.
#include<stdio.h>
main()
{
FILE *fp;
int number,quantity,i;
float price,value;
char item[20],filename[10];
clrscr();
printf("Enter filename: ");
gets(filename);
fp=fopen(filename,"w");
printf("Enter Inventory data: \n");
printf("Enter Item Name, Number, Price and Quantity
(3 records):\n");
for(i=1;i<=3;i++) {
fscanf(stdin,"%s %d %f %d",item,&number,&price,&quantity);
fprintf(fp,"%s %d %0.2f %d",item,number,price,quantity);
}
fclose(fp);
fprintf(stdout,"\n\n");
fp=fopen(filename,"r");
printf("Item Name\tNumber\tPrice\tQuantity\tValue\n");
for(i=1;i<=3;i++)
{
fscanf(fp,"%s %d %f %d",item,&number,&price,&quantity);
value=price*quantity;
fprintf(stdout,"%s\t%10d\t%8.2f\t%d\t%11.2f\n",item,number,price,
quantity,value);
}
fclose(fp);
getch();
}
C File management
A File can be used to store a large volume of persistent data. Like many other languages ‘C’ provides following file
management functions,
1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file
Following are the most important file management functions available in ‘C,’
function purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
function purpose
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
fseek () Sets the position of a file pointer to a specified location
ftell () Returns the current position of a file pointer
rewind () Sets the file pointer at the beginning of a file
FILE *fp;
fp = fopen ("file_name", "mode");
In the above syntax, the file is a data structure which is defined in the standard library.
If the file is not present on the system, then it is created and then opened.
If a file is already present on the system, then it is directly opened using this function.
Whenever you open or create a file, you have to specify what you are going to do with the file. A file in ‘C’
programming can be created or opened for reading/writing purposes. A mode is used to specify whether you want
to open a file for any of the below-given purposes. Following are the different types of modes in ‘C’ programming
which can be used while working with a file.
File
Description
Mode
Open a file for reading. If a file is in reading mode, then no data
r
is deleted if a file is already present on a system.
Open a file for writing. If a file is in writing mode, then a new file
is created if a file doesn’t exist at all. If a file is already present
w
on a system, then all the data inside the file is truncated, and it
is opened for writing purposes.
Open a file in
a append mode. If a file is in append mode, then the file is
opened. The content within the file doesn’t change.
r+ open for reading and writing from beginning
w+ open for reading and writing, overwriting a file
a+ open for reading and writing, appending to file
In the given syntax, the filename and the mode are specified as strings hence they must always be enclosed within
double quotes.
Example:
#include <stdio.h>
int main() {
FILE *fp;
fp = fopen ("data.txt", "w");
}
‘C’ provides the fclose function to perform file closing operation. The syntax of fclose is as follows,
fclose (file_pointer);
Example:
FILE *fp;
fp = fopen ("data.txt", "r");
fclose (fp);
To execute any program we are required to first enter the program, compile it, and then execute it.
Instead of the program prompting for entering the source and target filenames it can be through
command prompt in the form: C> filecopy sample1.c sample2.c where sample1.c is the source filename
and sample2.c is target filename. The second option is possible by passing the source filename and
target filename to the function main(). Let us first consider an example:
#include “stdio.h>
3 No such process
5 I/O error
errno value Error
10 No child processes
11 Try again
12 Out of memory
13 Permission denied
1. Operation not permitted: Sometimes while performing operations of file handling in C, we try to read
from a file or change permissions of a file by accessing it. If we don't have ownership rights or system
rights to access a file, then we get this particular error message.
2. No such file or directory: This error message occurs whenever we try to access a file or directory that
doesn't exists. It also occurs when we specify wrong file destination path.
3. No such process: When we perform some operations that are not supported during file handling in C,
it gives no such process error.
4. Interrupted System call: If we try to read user's input and if there is no input present, then the system
calling process will not return any value and will be blocked forever. This results in interrupted system
calls.
5. I/O error: I/O stands for input/output errors that occur when system is not able to perform basic
operations like reading from a file or copying data from one file to another.
6. No such device or address: When we specify incorrect device path or address while opening or
accessing them, this error occurs.
For example: If we are trying to access a device driver using its path but in actual, it has been removed
from the system.
7. Argument list too long: This error generally occurs when we work with large number of files.
For example: If we need to get count of no. of files in a directory (consisting of large number of files)
that starts with string - "Scaler", then due to limited buffer space it will show an error message -
"Argument list too long" as no. of files in that directory will be equal to the arguments list.
8. Exec format error: This error occurs when we try to execute a file that is not executable or has an
invalid executable-file format.
9. Bad file number: This error occurs generally when we try to write to a file which is opened for read-
only purpose.
10. No child process: If a process has no further sub-process or child process, then the code returns -
1 value and we get no child process error message.
11. Try again: An attempt to create a process fails, when there are no more process slots or not enough
memory available. We then get try again error.
12. Out of memory: This error occurs when there is not enough memory available to execute a process.
13. Permission denied: This error occurs when we try to read from a file that is not opened. It suggests
that an attempt was made to access a file in a way that is incompatible with the file's attributes.
int main(){
FILE* fp;
fp = fopen("test.txt","r");
int main(){
FILE* fp;
fp = fopen("test.txt","r");
3. ferror()
ferror() function is contained in stdio.h header file.
This function basically checks for error in the file stream. It returns zero value if there is no error or else,
it returns a positive non-zero value in case of error.
File pointer stream is passed as an argument to the function. It will check for the error until the file is
closed or we call clearerr() function.
To identify the type of error, we can further use perror() function.
Syntax:
int ferror(FILE *stream);
C Program to illustrate the use of ferror() function: In this program, we are trying to read data from the file
but has opened the file in the wrong access mode i.e, writing mode. Now, ferror() function will detect
this error in the file stream and using perror() function, we will display the error message.
#include <stdio.h>
int main(){
FILE *fp;
fp = fopen("test.txt","w");
char ch = fgetc(fp); //Trying to read data, despite of writing mode opened
if(ferror(fp)){ //Error detected in the file stream pointer
printf("File is opened in writing mode!");
printf("\nError in reading from the file!");
perror("Error Message from perror");
//Identifying the type of error using perror() function
}
fclose(fp);
return(0);
}
Output:
File is opened in writing mode!
Error Message from perror: Bad file descriptor
Error in reading from the file!
Here, we are printing error messages both user-defined and from perror() function as well.
4. feof()
feof() function is contained in stdio.h header file.
This function tests for end-of-file (eof indicator) for the file pointer stream passed as an argument to the
function.
On detecting that the end-of-file indicator associated with the file stream is set, it returns a non-zero
positive value or else, zero is returned.
Syntax:
int feof(FILE *stream);
Here, file pointer stream is passed as an argument and on detecting the end-of-file, this function will
return a non-zero positive value.
C Program to illustrate the use of feof() function: In this program, we are trying to read data from the file
and to avoid printing the garbage value characters, we are using feof() function. On detecting the end-of-
file, it will return a non-zero value and hence, breaks the loop.
#include <stdio.h>
#include <stdbool.h>
int main(){
FILE *fp;
fp = fopen("test.txt","r");
if(fp==NULL){
perror("Message from perror");
return -1;
}
while(true){
char ch = fgetc(fp); //Reading data from the file
if(feof(fp)){
//On detecting the end-of-file, feof() function will return non-zero value
//hence, it will break the loop
break;
}
printf("%c",ch);
}
fclose(fp);
return 0;
}
Output: Assuming there's some data present in the "test.txt" file, it will read and print:
Scaler Topic: Error Handling in C during File Operations
In absence of feof() function, it will further print the garbage value characters.
5. clearerr()
clearerr() function is contained in stdio.h header file.
This function clears the end-of-file and the error indicators from the file stream.
Error indicators are not automatically cleared and they continue to return the errors until clearerr()
function is called.
Syntax:
void clearerr(FILE *stream)
C Program to illustrate the use of clearerr() function: In this program, we are trying to read data from the
file but has opened the file in the wrong access mode i.e, writing mode. Now, we will clear the error
indicators using clearerr() function from the file stream and hence, ferror() couldn't then detect that
error again.
#include <stdio.h>
int main(){
FILE *fp;
fp = fopen("test.txt","w");
char ch = fgetc(fp); //Trying to read data but the file is opened in writing mode
if(ferror(fp)) { //ferror() will detect error in file pointer stream
printf("Error in reading from file!");
}
clearerr(fp); //clearerr() will clear error-indicators from the file stream
if(ferror(fp)){ //No error will be detected now
printf("Error again in reading from file!");
}
fclose(fp);
return 0;
}
After opening the file in writing mode, we are trying to read data from it using fgetc() and therefore,
using ferror() function we can detect the error. After using clearerr() function, it will remove the error in
the file pointer stream and further, we won't get any error on checking through ferror() function.
Output:
Error in reading from file!
In absence of clearerr() function, output will be:
Error in reading from file!
Error again in reading from file!
6. Exit Status
The macros of exit status() functional method are defined in stdlib.h header file. They are used to inform
calling function about the error.
There are two constant exit status values available for the exit() function: EXIT_STATUS and
EXIT_FAILURE.
When program code comes out after a successful operation, then EXIT_SUCCESS is used to show
successful exit. Its value is defined as 0.
We use EXIT_FAILURE in case of failures or abrupt termination of the program. Its value is defined as -1.
Syntax:
exit(EXIT_SUCCESS); //successful termination
exit(EXIT_FAILURE); //unsuccessful termination
C Program to illustrate the use of Exit Status function: In this program, we are illustrating the use of two exit
function constant values: EXIT_SUCCESS and EXIT_FAILURE depending upon how the program code is
terminated.
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main(){
FILE *fp;
fp = fopen ("test.txt","r");
if(fp==NULL){
printf("Value of errno: %d",errno);
perror("Error printed by perror");
exit(EXIT_FAILURE); //Good practice to exit the program using exit status
printf("This message will not be printed!");
//This won't be printed due to exit above
}
else{
fclose (fp);
exit(EXIT_SUCCESS); //Successful exit from the program
printf("This message will not be printed!");
//This won't be printed due to exit above
}
return 0;
}
After opening a file using file pointer fp, if it doesn't exists then we will print the error messages and exit
from the function (EXIT_FAILURE). If file exists, then we will exit from the program by executing else
condition here (EXIT_SUCCESS). Output: In case, if "test.txt" file doesn't exists: exit(EXIT_FAILURE)
Error printed by perror: No such file or directory
Value of errno: 2
7. Division by zero
If we divide a number by zero, C programming language will give warnings and also give runtime error.
To avoid such an undefined behaviour, there is no construct or method in C.
To avoid such situations, we can check the value of divisor before using it for division purposes. This can
be done using if-else conditions and whenever we encounter such a situation, we can simply print error
message.
C Program to illustrate the error of Division by zero: In this program, we are keeping a check if in case we
get zero number value for division that can produce errors and can also abruptly terminate the program.
#include <stdio.h>
#include <stdlib.h>
int main(){
int x = 0;
division(x); //Calling function to perform division
return 0;
}
Here, we have passed the value x in division function. Using if condition we check if it is 0, then we can't
perform division using it. Using else condition, we divide 10 by x and then print the resultant
value. Output:
Division by Zero is not allowed!
UNIT 12.
Graphics
Graphics programming in C used to drawing various geometrical shapes(rectangle, circle eclipse etc), use
of mathematical function in drawing curves, coloring an object with different colors and patterns and
simple animation programs like jumping ball and moving cars.
Graphics options are used in c-programming to draw different graphical shapes. First of all we have to
call the initgraph() function that will initialize the graphics mode on the computer.
initgraph() initializes the graphics system by loading a graphics driver from disk (or validating a
registered driver) then putting the system into graphics mode. initgraph() also resets all graphics settings
(color, palette, current position, viewport, etc.) to their defaults, then resets graph result to 0.
gdriver:
It is declared as integer variable that specifies the graphics driver to be used.
gmode:
It is also declared as integer variable which specifies the initial graphics mode (unless gdriver = DETECT).
If gdriver = DETECT, initgraph sets gmode to the highest resolution available for the detected driver.
path_to_driver:
Specifies the directory path where initgraph() looks for graphics drivers (e.g. egavga.bgi in turbo c++)
1. If the driver is not there, initgraph() looks in the current directory.
2. If path_to_driver is null, the driver files must be in the current directory.
After a call to initgraph, gdriver is set to the current graphics driver, and gmode is set to the
current graphics mode.
Gdriver =DETECT auto-detects the attached video adapter at run time and pick the corresponding driver.
If we tell initgraph to auto-detect, it calls detectgraph to select a graphics driver and mode.
Normally, initgraph() loads a graphics driver by allocating memory for the driver, then loading the
appropriate .BGI file from disk
Next
This function is used to load the graphics drivers and initialize the graphics system. For every function, that uses
graphics mode, graphics mode must be initialized before using that function.
void initgraph(int far *driver, int far *mode, char far *path)
Detectgraph function determines the graphics hardware in the system, if the function finds a graphics adapter
then it returns the highest graphics mode that the adapter supports.
void detectgraph(int far *driver, int far *mode)
Function cleardevice()
This function clears the graphics screen contents and return the control to the location (0,0).
void cleardevice(void)
Function closegraph()
This function shutdown the graphics mode and returns to the position it was before the initgraph() function was
called. The closegraph() function releases all the resources occupied by the graphics system like memry, fonts,
drivers etc…
void closegraph(void)
Sample Program
Error Handling
• graphresult() function is used to check if
certain graphics operation succeeded or not.
• It return 0 for no error.
Some Functions in Graphics
• putpixel() and getpixel()
• setcolor() and setbcolor()
• line()
• circle()
• ellipse
• rectangle()
• settextstyle() and outtext()
• getmaxx() and getmaxy()
1)putpixel() and getpixel()
getpixel returns the color of pixel present at point(x, y).
putpixel plots a pixel at a point(x, y) of specified color.
Syntax:
int getpixel(int x, int y);
void putpixel(int x, int y, int color);
2)setbcolor()
setbkcolor function changes current background color e.g. setbkcolor(YELLLOW) changes the current background
color to YELLOW.
Remember that default drawing color is WHITE and background color is BLACK.
Syntax :-
void setbkcolor(int color);
3)setcolor()
setcolor function changes current drawing color e.g. setcolor(YELLLOW) changes the
current drawing color to YELLOW.
Syntax :-
void setcolor(int color);
4)line()
line function is used to draw a line from a point(x1,y1) to point(x2,y2)
Syntax :-
void line(int x1, int y1, int x2, int y2);
5)circle()
Circle function is used to draw a circle with center (x,y) and third parameter specifies the
radius of the circle.
Syntax :-
void circle(int x, int y, int radius);
6.ellipse()
Ellipse is used to draw an ellipse (x,y) are coordinates of center of the ellipse, stangle is
the starting angle, end angle is the ending angle, and fifth and sixth parameters specifies
the X and Y radius of the ellipse.
Syntax :-
void ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius);
7.rectangle()
Coordinates of left top and right bottom corner are required to draw the rectangle.
Syntax:-
void rectangle(int left, int top, int right, int bottom);
8.settextstyle()
font argument specifies the font of text, Direction can be HORIZ_DIR (Left to right) or
VERT_DIR (Bottom to top).
Syntax :-
– void settextstyle( int font, int direction, int charsize);
9.outtext()
outtext function displays text at current position.
Syntax :-
void outtext(char *string);
10.getmaxx() and getmaxy()
getmaxx function returns the maximum X coordinate for current graphics mode and driver.
Declaration :- int getmaxx();
getmaxy function returns the maximum Y coordinate for current graphics mode and driver.
Declaration :- int getmaxy();
The line function which is most important function in creating any graphics.
Function line()
This function draws an arc from start to the end point. It uses the radius and the angle inputted in the function
void arc (int x, int y, int start, int end, int radius)
Function bar()
The bar() functions draws a rectangular bar on the screen. It takes four parameters of type int which are infact the
points on the graphics screen, and fills the bar with the defined fill-pattern. Function prototye is
Here left & top are the starting point for the rectangular bar from x and y coordinates respectively and right &
Function bar3d()
As the name suggests that this function will draw the 3 Dimensional rectangular bar on the screen. Bar3d function
takes six parameters of which four are the points , fifth one is the depth of the bar and sixth is the flag to indicate
Draws the circle on the screen using a point(x,y) and the radius for the circle.
Here numpoints is the number of end points in the polygon. And points is the integer array which contains the x
Function ellipse()
void ellipse(int x, int y, int start, int end, int xradius, int yradius)
Function floodfill()
This function fills an object drawn on the graphics screen with the defined color and fill pattern. Now if the x,y
coordinates lie within the boundries of the object then it will fill the interior of the object otherwise out side the
object.
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main()
errorcode = graphresult();
getch();
/* draw a line */
/* clean up */
getch();
closegraph();
return 0;
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
int main()
Int x,y;
errorcode = graphresult();
getch();
/* draw a line */
circle(x,y,100);
/* clean up */
getch();
closegraph();
return 0;
int main()
circle(x, y, radius);
getch();
closegraph();
return 0;
#include<conio.h>
int main()
getch();
closegraph();
return 0;
#include <dos.h>
int main()
initgraph(&gd,&gm,"C:\\TC\\BGI");
settextstyle(DEFAULT_FONT,HORIZ_DIR,2);
getch();
for( i = 0 ; i <= 420 ; i = i + 10, j++ )
rectangle(50+i,275,150+i,400);
rectangle(150+i,350,200+i,400);
circle(75+i,410,10);
circle(175+i,410,10);
setcolor(j);
delay(100);
if( i == 420 )
break;
if ( j == 15 )
j = 2;
getch();
closegraph();
return 0;