Programming in C -NOTES(1 to 5)-1
Programming in C -NOTES(1 to 5)-1
1.1 ALGORITHMS:
Definition1:
An algorithm can be defined as “a complete, unambiguous, finite number of logical
steps for solving a specific problem”
Definition2:
An algorithm, is defined as a:“well-ordered collection of unambiguous and effectively
computable operations, that when executed, produces a result and halts in a finite amount
of time.”
Definition3:
An algorithm is defined as a finite sequence of explicit instruction that provides a set
of input values, process an output and then terminates.
Definition4:
An algorithm is a well-defined computational procedure consisting of a set of
instructions that takes some value or set of values, as input, and produces some value or
set of values, as output
algorithm
Input Output
Definition5:
An algorithm consists of a set of explicit and unambiguous finite steps which, when
carried out for a given set of initial conditions, produce the corresponding output and
terminate in a finite time. An algorithm is a step-by-step procedure for solving a problem
in a finite number of steps.
Definition6:
An algorithm is a finite number of clearly described, unambiguous “doable” steps that can be
systematically followed to produce a desired result for given input in a finite amount of time.
1
UNIT-1 I YEAR/I SEM
Step3 : Identification the processing operations : All the calculations to be performed in order
to lead to output from the input are to be identified in an orderly manner.
Step4 : Processing Definiteness : The instructions composing the algorithm must be clear and
there should not be any ambiguity in them.
Step5 : Processing Finiteness : If we go through the algorithm, then for all cases, the algorithm
should terminate after a finite number of steps.
Step6 : Possessing Effectiveness : The instructions in the algorithm must be sufficiently basic
and in practice they can be carries out easily.
PROPERTIES OF AN ALGORITHM:
1. Finiteness: An algorithm must terminate in a finite number of steps
2. Definiteness: Each step of the algorithm must be precisely and unambiguously stated
3. Effectiveness: Each step must be effective, in the sense that it should be primitive
easily convert able into program statement) can be performed exactly in a finite amount of time.
4. Generality: The algorithm must be complete in itself so that it can be used to solve
problems of a specific type for any input data.
5. Input/output: Each algorithm must take zero, one or more quantities
as input data produce one or more output values.
2
UNIT-1 I YEAR/I SEM
operations.
4. Test the algorithm: choose data sets and verify that your algorithm works!
Bottom up approach
Example Algorithm 1
Step 1: Start.
Step 2: Read two numbers a and b.
Step 3: Add the numbers a and b and store in sum as
sum=a+b Step 4: Display sum
3
UNIT-1 I YEAR/I SEM
Step 5: Stop
Example Algorithm 2
Step 1: Start.
Step 2: Read the three numbers A,B,C.
Step 3: Compare A and B. If A is greater, store A in MAX, else store B in MAX.
Step 4: Compare MAX and C. If MAX is greater, output “MAX is greater” else
output “C is greater”.
Step 5: Stop.
Statements
State
Control flow
Functions
Statements
Reserved words - words that have pre-defined meanings in the Java language
Identifiers - words that are created by programmers for names of variables, functions,
classes, etc.
Literals - literal values written in code, like strings or numbers
Operators - special symbols that perform certain actions on their operands
Calls to
functio
ns State
State is the information that the program manipulates to accomplish some task. It
is data or information that gets changed or manipulated throughout the runtime of a
program. The state of an algorithm is defined as its condition regarding stored data. The
stored data in an algorithm are stored as variables or constants. The state shows its
current values or contents. An instruction is a single operation, that describes a
computation. When it executed it convert one state to other. Example: state refers to the
4
UNIT-1 I YEAR/I SEM
set of variables and the values to which they refer.
Control Flow
Control flow is the order that instructions are executed in a program .A control
statement is a statement that determines the control flow of a set of instructions
Pseudocode Flowchart
BEGIN
statement
Statement Action1
END
Action2
5
UNIT-1 I YEAR/I SEM
Conditional Statements:
The following are the conditional statements such as if, if-else,if…elif...else statement
if statement:
The if statement is used to test a condition. If the condition is true, the statements of if
block are executed otherwise the statements following the if block are executed.
Pseudocode:
IF(CONDITION)TH
EN STATEMENTS
ENDIF
Example:
6
UNIT-1 I YEAR/I SEM
if else
The if-else statement is used to execute different actions based on the condition. The if-
else statement evaluates the condition and will execute body of if only when test
condition is true. If the condition is false, body of else is executed. It is a two-way
branching statement
Pseudocode:
IF condition
THEN statement
1
ELSE
statement
2 END‐IF
Example:
7
UNIT-1 I YEAR/I SEM
if elif else
The if elif else statement is used to check multiple conditions. When series of actions are
to performed based on one-by-one decisions, then if –else-if else statements are used. It is
also called as multipath decision statement. If the condition for if is false, it checks the
condition of the next elif block. If all the conditions are false, body of else is executed.
8
UNIT-1 I YEAR/I SEM
Example
9
UNIT-1 I YEAR/I SEM
Looping/Iterative statements:
The following are the looping statements such as while , for
while:
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.In while loop, test expression is checked first. The body of
the loop is entered only if the test_expression evaluates to True. After one iteration, the
test expression is checked again. This process continues until the test_expression
evaluates to False.
1
0
PANIMALAR INSTITUTE OF TECHNOLOGY UNIT-1 I YEAR/I SEM
Example:
for:
The for loop in Python is used to iterate over a sequence .Iterating over a sequence is
called traversal. Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation.
11
PANIMALAR INSTITUTE OF TECHNOLOGY UNIT-1 I YEAR/I SEM
Example:
The statements used to control or terminate from the loop are known as loop control statements.
The following are the loop control statements: break, continue
break
The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop. If break statement is inside a nested
loop (loop inside another loop), break will terminate the innermost loop. Inside the loop
body, you can use the break statement to exit the loop immediately.
12
I YEAR/I SEM
Pseudocode:
WHILE condition
Sequence of
statements BREAK
Continue
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Continue statement will be encountered, and the flow of control will leave that loop
body–but then the loop will continue with the next element in the range.
13
I YEAR/I SEM
Pseudocode:
WHILE condition
Sequence of
statements
CONTINUE
Functions
A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high degree
of code reusing. Other Terms: methods, sub-routines, procedure.
Example:
Function: piece of prewritten code that performs an operation
print function: displays output on the screen
Argument: data given to a function
Example: data that is printed to screen
Types of functions/categories of
functions:
Pseudocode:
BEGIN BEGIN PROCEDURE
CALL PROCEDURE statement1
END statement2
END PROCEDURE
14
I YEAR/I SEM
1.3 NOTATION
(PSEUDOCODE,FLOWCHART,PROGRAMMING
LANGUAGE)
Notation refers to the means of representing the algorithm for solving a task. The
following are the notations for representing the algorithms
Pseudocode
Flowchart
Programming Languages
PSEUDOCODE
Pseudo code derived from „pseudo‟ which means imitation and „code‟ means
instruction is a generic way of describing an algorithm without using any specific
programming language related notations. Pseudocode is an artificial and informal
language that helps programmers to develop algorithms. Pseudocode can be defined as
the narrative description of the flow and logic of the intended program, written in plain
15
I YEAR/I SEM
language that expresses each step of the algorithm.The pseudocode is also called as
Program design language (PDL)
Characteristics/properties of Pseudocode:
Characteristics/properties of flowchart:
Flowcharts are also known as process maps to identify flow of information
Flowchart not only serves as a program documentation but also helps as a means
to communicate with several programmers as it is language independent.
It serves as a useful reference or a programing aid due to its simple and efficient
method of representing the program logic of a problem.
Flowchart disadvantages
They are hard to modify and can be time consuming.
They need special software for symbols
Constructing a flowchart is time-consuming
Reasons for using flowchart as a problem solving tool:
Communication
Effective analysis
Proper documentation
General rules /Guidelines for drawing flowcharts
Only one flow line should enter a decision symbol. However, two or three flow
lines may leave the decision symbol.
Flowcharts are drawn so that flow generally goes from top to bottom of the page or
from left to right
Within standard symbols, write briefly and precisely.
Intersection of flow lines should be avoided.
It is useful to test the validity of the flowchart with normal/unusual test data.
18
I YEAR/I SEM
19
I YEAR/I SEM
Flowchart:
S.no Algorithm Pseudocode Flowchart
1 An algorithm is a A tool to document and A tool to document and
sequence of instructions represent the algorithm represent the algorithm
used to solve a particularReadable, formally Graphical representation
problem styled English like of the algorithm
representation of the
algorithm
2 Provides the logic of the Uses programming Uses graphical symbols
program in steps language constructs
3 Does use symbols and Use keywords Use standardized
programming language symbols
constructs
4 Set of instructions Artificial and Informal A graphical way of
language writing pseudocode
Programming Language:
The programming language is the medium through which the problems to be solved by
computer can be represented in the form of programs or set of instructions. The computer
executes the set of instructions written in a particular language to produce the desired
result. A programming language consists of a set of characters, symbols, and usage rules
that allow the user to communicate with computers. In a simple form it can be defined as -20
any notation for the description of algorithm and data structure may be termed as a
programming language.
I YEAR/I SEM
i) Machine language : The machine language programs were written using the digit 0 and 1.
The instruction in machine language consists of two parts. The first part is an operation which
tells the computer what operation is to be performed. The second part of the instruction is
operand, which tells the computer where to find or store the data after applying the operation
Advantages :
Translation free : Machine language is directly understand by the computer so it does not
need any translation. Otherwise, if a program is developed in high level language then it
has to be translated into the machine language so that the computer can understand the
instructions.
High speed : The application developed in the machine language are extremely fast
because it does not require any conversion.
Disadvantages :
Machine dependent : Program developed in one computer system may not run on an
another computer system.
Complex language : This language was very difficult to understand and programming
techniques were tedious.
Error prone : Writing machine language programs, a programmer has to remember all the
opcodes and memory locations, so machine language is bound to be error prone.
ii) Assembly language : Assembly language is not a single language, but a group of language. An
assembly language provides a mnemonic instruction, usually three letters long, corresponding to
each machine instruction. The letters are usually abbreviated indicating what the instruction
does, like ADD for addition, MUL for multiplication etc. The assembly language allows the
programmer to interact directly with the hardware. Each line of assembly language program
consists of four columns called fields.
The general format of an assembly language instruction is :
[Label] <Opcode> <Operands> [; Comment]
21
e.g. BEGIN ADD A, B ; Add B to A
I YEAR/I SEM
Advantages:
Easy to understand and use : Assembly language uses mnemonics instead of using
numerical opcodes and memory locations used in machine language, so it is easy to
understand and use.
Less error prone : Assembly language is less error prone and it provides better facility to
locate errors and correct them.
Faster : It is much faster and use less memory resources than the high level language.
Disadvantage :
• Assembly language programs are machine dependent.
• Assembly language is complex to learn.
• A program written in assembly language is less efficient than machine language because every
assembly instruction has to be converted into machine language.
iii) High level language : COBOL, FORTRAN, PASCAL and C are the examples of high level
languages. High level languages are similar to English language. Programs written using these
languages may be machine independent. A single instruction of a high level language can
substitute many instructions of machine language and assembly language. Using the high level
language complex software can be design.
Advantages :
• Readability : Since high level languages are similar to English language so they are easy to
learn and understand.
• Programs written in high level languages are easy to modify and maintain.
• High level language programs are machine independent.
• Programs written in high level language are easy to error checking.
Disadvantages :
Programs written in high level language has to be compile first for execution of the
program. This step of compilation increases the execution time of an application.
Moreover, the programs occupies more memory space during the execution time.
Another main drawback of HLL programs is - its poor control on the hardwares.
Language Translators
The language translators or also called language processors are the programs which
converts the high level language programs into the machine language programs for
execution.
Types of Language Translators:
Compiler
Interpreter
Assembler
Compiler : A compiler is a program that can translates an higher level language program
to its machine form. This language processor translates the complete source program as a
whole into machine code before execution. Here the source program means – the program
that is written by the programmer and the translated program is called a object program or
object code. Examples: C and C++ compilers. If there are errors in the source code, the
compiler identifies the errors at the end of compilation. Such errors must be removed to
enable the compiler to compile the source code successfully.
22
I YEAR/I SEM
Problem:
The problem can be defined as the gap between actual and desired conditions.
Analysing algorithms:
As an algorithm is executed, it uses the computers central processing unit to perform
operation and its memory (both immediate and auxiliary) to hold the program and data.
Analysis of algorithms and performance analysis refers to the task of determining how
much computing time and storage an algorithm requires
- Various logical assertions about a situation are made, establishing all known facts.
- Then queries are made. The role of the computer becomes maintaining data and logical
deduction.
- A logical program is divided into three sections:
a series of definitions/declarations that define the problem domain
statements of relevant facts
statement of goals in the form of a query
Advantages:
The advantages of logic oriented programming are
o The system solves the problem, so the programming steps themselves are kept to a
minimum;
o Proving the validity of a given program is simple.
3. Functional programming paradigms:
- The Functional Programming paradigm views all subprograms as functions in the
mathematical sense-informally, they take in arguments and return a single solution.
- The solution returned is based entirely on the input, and the time at which a function is
called has no relevance.
- The computational model is therefore one of function application and reduction.
Advantages:
o Higher level of abstraction
o The lack of dependence on assignment operations
o Possess referential transparency.
Disadvantages
o Perhaps less efficiency
o Problems involving many variables or a lot of sequential activity are sometimes easier
to handle imperatively or with object-oriented programming.
4. Object-Oriented
- Object Oriented Programming (OOP) is a paradigm in which real-world objects are
each viewed as separate entities having their own state which is modified only by built
inprocedures, called methods.
- Because objects operate independently, they are encapsulated into modules which
contain both local environments and methods. Communication with an object is done
by message passing.
- Objects are organized into classes, from which they inherit methods and equivalent
variables. The object-oriented paradigm provides key benefits of reusable code and
code extensibility.
Benefits and Features:
o A new class (called a derived class or subclass) may be derived from another class
(called a base class or superclass) by a mechanism called inheritance. The derived
class inherits all the features of the base class: its structure and behavior(response to
27
messages.
o Inheritance gives OOP its chief benefit over other programming paradigms - relatively
I YEAR/I SEM
easy code reuse and extension without the need to change existing source code.Also,
encapsulation and information hiding are inherent benefits of OOP.
INTRODUCTION TO C PROGRAMMING:
- C is a general-purpose computer programming language developed in 1972 by Dennis
M. Ritchie at the Bell Telephone Laboratories to develop the UNIX Operating System.
- C is also called mother Language of all programming Language. It is the most widely
use computer programming language.
- All other programming languages were derived directly or indirectly from C
programming concepts.
- This language is used for develop system software and Operating System.
Features of C:
Simplicity:
- It is very easy to understand.
Portability:
- It is the concept of carrying the instruction from one system to another system
Powerful:
- C is a very powerful programming language, it have a wide verity of data types,
functions, control statements, decision making statements, etc
Structure oriented:
- Structure oriented programming language aimed on clarity of program, reduce the
complexity of code, using this approach code is divided into sub-program/subroutines.
These programming have rich control structure.
Modularity
- In c programming we can break our code in subprogram.
Middle level language:
- C programming language can supports two level programming instructions with the
combination of low level and high level language that's why it is called middle level
programming language
28
Compiler based:
- C is a compiler based programming language that means without compilation no C
I YEAR/I SEM
printf(“good morning\n”);
printf is a build-in functions which is used to display output in the screen.
\n is called escape sequence to go to next line It always begin with \ (back slash).
Semicolon(;)
It is used to terminate the statement.
return(0);
- This statement terminates the main function.
- Returns the value 0 to the operating system indicating Successful completion of
program.
- Any other number indicates that the program is failed.
C TOKENS:
C tokens are the basic buildings blocks in C language which are constructed together to
write a C program.
IDENTIFIERS:
Identifiers are the name used to identify entities like variable, function, array, structure or any
other user-defined item.
Identifier must be unique.
They are created to give unique name to an entity to identify it during the execution of the
program.
Rules for naming an Identifier
Identifier name in C can have letters, digits or underscore(_).
The first character of an identifier name must be a alphabet (a-z, A-Z),underscore( _ ).
The first character of an identifier cannot be a digit.
Keywords are not allowed to be used as Identifiers.
No special character (except underscore) blank space and comma can be used in
Identifier name.
KEYWORDS
Keywords are reserved words that have a particular meaning in C language.
The meaning of key word is predefined. These meaning of the keyword cannot be
changed.
There are total 32 keywords in C language.
VARIABLES:
It is a name given to the memory location.
In programming, a variable is a container (storage area) to hold data.
To indicate the storage area, each variable should be given a unique name called
identifier. 32
I YEAR/I SEM
L-Value: R-Value
L- Value Is An Object Locator. R-value refers to ‘Read Value’.
L-Value Stands For Left Value
The L-Value Could Legally Stand On The Left Side R-value can be anything of following:
Of An Assignment Operator. 1.Variable
For Example: Mark=20; // 2. Function
The L- Value Should Be A Variable. 3. Constant
Eg, 33
DATA TYPES :
Data types determines the possible values that an identifier can have and the valid
operations that can be applied on it.
The type of a data determines how much space it occupies in storage.
In C Language, data types are broadly classified as
printf("%d",m1);} m1=MAY;printf("%d",m1);}
Output: Output:
3 3
Explanation: Explanation:
In this example, we Integers are assigned to enum
declared “m1” as the constants.
variable and the value of
“APRIL” is allocated to
m1, which is 3.
3. Derived data types
These data types are derived from the basic data types. Derived data types available in c are:
Array
Structure
Union
Pointer
Type conversion (Type casting):
- A type cast is basically a conversion from one type to another.
There are two types of type conversion:
Implicit Type Conversion (Also known as ‘automatic type conversion’):
- This Implicit conversion is done by the compiler on its own, without any
knowledge to the user.
- Generally type casting takes place when in an expression is having more than one
data type in it.
- Here, It is best practice to convert lower data type to higher data type to avoid
data loss. Because, Data will be truncated when the higher data type is converted
to lower. For example, if a float is converted to int, data which is present after
the decimal point will be lost.
- Hence, Compiler convers all operands into datatype of the largest operand.
bool-> char-> short int -> int -> unsigned int -> long -> unsigned -> long long ->float ->
double -> long double
Example 1:(implicit typecasting) Example 2: :(implicit typecasting)
#include<stdio.h> #include <stdio.h>
main() main() {
{ int i = 17;
int a=10; char c = 'c';
float b=6.1; float sum;
float c; sum = i + c; /* ascii value is 99 */
c=a+b; /*integer value 10 is converted to float value as printf("%f\n", sum );
10.0 automatically*/ }
printf("%f",c); Output:
38
} 116.000000
I YEAR/I SEM
Output:
16.100000
Explicit Conversion(Type casting):
The type conversion performed by the programmer by specifying the data type in the
expression.
Data type should be mentioned before the variable name or value.
Syntax:
(data type)expression
Example1: Example2: :(Explicit typecasting)
#include <stdio.h> #include <stdio.h>
main() main()
{ {
int x=13, y=5 ; int x=13, y=5 ;
float z; float z;
z=x/y; // here, quotient is int datatype and it is z=(float)x/y; // int data type is converted to
stored in float variable float and float value(quotiemt) is stored in
printf("%f",z); float variable
} printf("%f",z);
Output: }
2.000000 Output:
2.600000
STORAGE CLASS:
A storage class defines the scope (visibility) and life-time of variables.
Scope - Where to store a variable (Storage area of variable)
Lifetime- How long the variable can be stored in the memory(
alive) The following storage classes are most often used in C
programming.
1.auto 2.static
3.extern 4.register
A variable should be declared in any one of these four storage class.
1. auto storage class:
- auto is the default storage class.
- It is stored in RAM(main memory)
Scope: It can be used only in the block of code where it is declared.(local variable)
Lifetime: It will be alive only inside the block of code where it is declared.
Default value is Garbage Value
39
Syntax: Example:
auto data_type variablename; (or) auto int a;
I YEAR/I SEM
40
I YEAR/I SEM
42
I YEAR/I SEM
Syntax: Example:
register data_type variablename; register int a;
Printing the value of the variable using register storage class Output:
#include<stdio.h> Value of a is 11
int main() Value of a is 11
{ Value of a is 11
increment();
increment(); 43
increment();
I YEAR/I SEM
}
int increment()
{
register int a=10; a+
+;
printf("Value of a is: %d\n", a);
}
Properties of Storage Class:
CONSTANTS (LITERALS):
Constants are the values that cannot be changed during the execution of a program.
Constant is a fixed value which may be an integer, floating point number, character or a string.
Types of constants:
Integer constants:
- Integer constants are integer values like -1, 2, 8 without any decimal point.
- It can be either positive or negative. If no sign proceeds an integer is assumed to be
positive.
There are three types of integer constants in C language:
- Decimal constant (base 10)
- Octal constant (base 8) 44
- Hexadecimal constant (base 16)
I YEAR/I SEM
45
I YEAR/I SEM
Floating-point constants:
- Floating point constants can be written in fractional form or exponential form. Floating
point constant are values like -23.1, 12.8, -1.8e12.
- The floating point constant in an exponential form has two parts: The mantissa part
and the exponent part. Both parts are separated by e or E.
Character constants:
- Character constants can have one character enclosed within single quotes.
- For example: 'a', 'l', 'Y', 'A' etc.
Escape Sequences
- C supports some special character constants that are used in output functions.
- Escape sequence consists of a backward slash (\) followed by a character.
OPERATORS IN C:
Operands:
An operand specifies an entity on which an operation is to be performed.
An operand can be a variable name, constant, a function call.
Operators:
Operators are special symbol that tells the compiler to perform specific mathematical or
logical operations.
Operator specifies the operation to be applied to its operands.
CLASSIFICATION OF OPERATORS:
The operators in c are classified on the basis of the following criteria:
1. The number of operands on which an operator operates.
2. The role of an operator.
Classification based on Number of Operands
Based upon the number of operands on which an operator operates,operators are classified
as,
Unary operator: Binary operator ternary operator
A unary operator operates Binary operator operates Ternary operator operates on three
on only one operand. on two operands. operands. (Conditional operator)
Eg, Eg: Eg,
-3. Here the – is an unary 2-3. Here (-) acts as a ?: is a ternary operator
minus operator. binary operator.
Classification based on role of operator
Based upon their role operators are classified as:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bitwise operators
6. Increment /Decrement operators
7. Conditional operator
8. Special operators
Arithmetic operators
Arithmetic operations like addition, subtraction, multiplication, divisions, etc. The arithmetic
47
operators available in c are given here.
I YEAR/I SEM
c %= a;
printf("c=%d \n", c); return 0;
}
Relational operators:
- Relational operators are used to check the conditions.
- If the relation is true, it returns 1; if the relation is false, it returns value 0.
- The operand may be variables, constants or expressions.
Operator Description Example program Output
:
== Check if two operand are equal #include<stdio.h> 0
!= Check if two operand are not equal. int main() 0
> Check if operand on the left is { 1
greater than operand on the right int a=5,b=8; 0
< Check operand on the left is smaller printf("%d\n",a==b); 1
than right operand printf("%d\n",a>b); 1
>= check left operand is greater than or printf("%d\n",a<b);
equal to right operand printf("%d\n",a>=b);
<= Check if operand on left is smaller printf("%d\n",a<=b);
than or equal to right operand printf("%d\n",a!=b);
}
Logical operators:
- Logical operators are used to combine the results of two or more conditions. C has the
following logical operators.
Op Description Example a=5, b=2
erator
&& Logial AND. True only if all operands are true ((a == 5) && (b > 5)) equals to 0.
|| Logical OR. True only if either one operand is true ((a == 5) || (b > 5)) equals to 1.
! Logical NOT. True only if the operand is 0 ! (a == 5) equals to 0.
Note: 1 represents true and 0 represents false.
Example: Output:
#include <stdio.h> 0
int main() 1
{ 1
int a=5,b=7,c=2;
printf("%d\n",((a==b)&&(a==c)));
printf("%d\n",((a==b)||(a>c)));
printf("%d\n",(!(a==b)));
}
Bitwise operators:
- Bitwise operators perform manipulations of data at bit level.
- It operates on individual bits of the operands.
49
- Bitwise operators are not applicable for float or double data types.
I YEAR/I SEM
Special Operator:
Operator Description Example
Sizeof Returns the size of an variable sizeof(x);
& Returns the address of an variable &x;
* Pointer to a variable *x ;
Example: Output:
#include <stdio.h> Size of integer is 2
int main() Size of Float value is 4
{ Size of character is 1
int a;float b;char c;
printf("Size of integer is %d\n", sizeof(a));
printf("Size of Float value is %d\n", sizeof(b));
printf("Size of character is %d\n", sizeof(c));
}
Conditional operator:
Conditional operator is the ternary operator.
Syntax:
Condition? Expression 1: Expression 2
Condition: condition is checked first. This expression evaluates to 1 if it's true and evaluates51
to 0 if it's false.
I YEAR/I SEM
Expression1: If the condition is true, this expression is evaluated and return the result of
Expression1.
Expression2: If the condition is false, this expression is evaluated.
Advantages of ternary operator:
Using ?: reduce the number of line codes and improve the performance of application.
Example 1: Use of ternary Example 2: Use of ternary operator
operator
#include <stdio.h> #include<stdio.h>
int main() main()
{ {
int a=89,b; int a=10,b=20,small;
b=(a ==100?1:2); printf((a<b ? printf("a is less") : printf("a is greater")));
printf("%d\n",b);return(0); return(0);
} }
Output: Output:
2 a is less
PRECEDENCE OF OPERATORS:(Associativity)
-. Each operator in c has a precedence associated with it..
High precedence operator *, /,%.
Low precedence operator +,
Precedence rule: This rule decides the order in which different operators are applied.
Associativity rule: This rule decides the order in which multiple occurrence of the same
level operators are applied.
Several operators of the same precedence appear together, the operator are evaluated
according their associativity.
If the operators are left-to-right associative, they are applied in left-to –right
order.
If the operators are right-to-left associative, they are applied in right-to-left order.
This table lists C operators in order of precedence (highest to lowest) and their
associativity.
Operator Description Associativity
() Parentheses (function call) left-to-right
[] Brackets (array subscript)
Increment right-to-left
++
decrement
--
Unary plus
+
- unary minus
& Address of operator
sizeof Determine size in bytes on this 52
implementation
I YEAR/I SEM
* Multiplication left-to-right
/ Division
% Modulus
+ Addition left-to-right
- Subtraction
< Relational less than operator left-to-right
<= less than or equal to operator
> Relational greater than
>= greater than or equal to
== Relational is equal to left-to-right
!= is not equal to
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Simple Assignment right-to-left
+= assign addition
-= Assign subtraction
*= Assign multiplication
/= Assign division
%= Assign modulus
, Comma operator left-to-right
Examples:
a=9-12/3+3*2-1 int a; a=2*3+4%5-3/2+6 int a= 5+7*4-9*(3,2)
a=? a=2*3.25+((3+6)/2) a=? a=?
a=9-4+3*2-1 a=? a=6+4-3/2+6 a= 5+7*4-9*2
a=9-4+6-1 a=2*3.25+9/2 a=6+4+1+6 a=5+28-18
a=5+6-1 a=6.50+4 a=10-1+6 a=33-18
a=11-1 a=10.50 a=9+6 a=15
a=10 a=10 a=15
(because ‘a’ is an integer)
53
I YEAR/I SEM
EXPRESSIONS:
Expressions:
An expression is a sequence of operands and operators.
The meaningful expression consists of one or more operands or operators that specify
the operations to be performed on operands.
Example: a+b, a-b.
Operands:
An operand specifies an entity on which an operation is to be performed.
Operators:
Operators are special symbol that tells the compiler to perform specific mathematical or logical
operations.
Operator specifies the operation to be applied to its operands.
Based on the number of operators present in an expression, expressions are classified as
simple expression and compound expressions.
Simple expressions:
An expression that has only one operator is known as a simple expression
For example: a+2;
Compound Expressions:
An expression that has more than one operator is known as compound expressions.
For example: b= 2+3*5;
INPUT AND OUTPUT STATEMENTS:
In c language two types of input/output statements are available. They are
1. Formatted input/output statements
2. Unformatted input/output statements
54
I YEAR/I SEM
scanf() statement:
scanf() is a built-in library function in c.
It is a standard input function used to read inputs from the user during execution of the
program.
Syntax:
scanf(“control strings”,&variable1,&variable2….&variable);
Control strings(Format Specifier):
- Control string is the type of data that the input statement going to accept, this
always preceded with a % sign.
- Each variable name must be preceded by an ampersand (&).
- & is the address of operator which gives the address of variable.
- It is built in function defined in the <stdio.h> header file.
- The given table lists some control strings with its meaning.
Format specifier Meaning
%c Single character
%s String
%d Integer
%f Float
%ld Double
scanf() for integer data type(%d)
Example:
scanf(“%d”,&a);
- here, a is a variable holding integer value.
- %d is the integer format specifier to represent integer data.
- ‘&’ symbol is used to represent the memory address of the variable.
scanf() for float data type(%f)
Example:
scanf(“%f”,&b);
- here, b is a variable holding float or fractional value.
- The format specifier %f indicates floating or fractional data.
scanf for character data
type(%c) Example: 55
scanf(“%c”,&ch);
I YEAR/I SEM
{ The Temperature in
float celsius, fahrenheit; Fahrenheit is:50.000000
printf ("Enter the Temperature in Celsius:");
scanf ("%f", &celsius);
fahrenheit = (1.8 * celsius) + 32;
printf ("The Temperature in Fahrenheit is:%f", fahrenheit);
return(0);
}
Program to find slope and midpoint of a line: Output:
#include<stdio.h> Enter the first point x1,y1:
int main () 10
{ 20
float xmp,ymp,x1,y1,x2,y2,slope; Enter the second point
printf ("Enter the first point x1,y1:\n"); x2,y2:
scanf ("%f %f", &x1,&y1); 30
printf ("Enter the second point x2,y2:\n"); 40
scanf ("%f %f", &x2,&y2); Slope is:1.000000
slope=(y2-y1)/(x2-x1); midpoint is:20.000000
xmp=(x1+x2)/2; 30.000000
ymp=(y1+y2)/2;
printf ("Slope is:%f\n", slope);
printf("midpoint is:%f %f",xmp,ymp);
return(0);
}
59
I YEAR/I SEM
input.
Syntax: Syntax:
variable name=getchar(); putchar(variable_name);
Example Example:
char c; char c;
c=getchar(); putchar(c );
Program using getchar and putchar function:
#include<stdio.h>
int main()
{
char a;
printf("enter any key");
a=getchar(); // read input and store it in variable ‘a’
putchar(a); //display the output on screen
}
Output:
enter any key
s
s
getch() putch()
- getch() accepts only single character It displays any alphanumeric characters to the
from keyboard. standard output device. It displays only one
- getch() function will just wait for any character at a time.
keyboard input (and press ENTER). It won’t Syntax:
display the given input character in output putch(variable_name)
screen. Example:
Syntax: char a;
variable_name=getch(); putch(a);
Example:
char x;
x=getch();
Program using getch() function:
#include <stdio.h>
int main()
{
printf("Hello World! ");
getch();
return 0;
}
Output:
60
Hello World!
I YEAR/I SEM
getche()
Like getch(), getche() also accepts only single character, but getche() displays the entered input
character in the screen.
Syntax:
Variable_name=getche();
Example:
char x;
x=getche();
To use getch(), getche() functions, you need to include #include <conio.h> header file
which is a non-standard header file.
gets() puts()
- gets() accepts any line of string including puts displays a single / paragraph of text to the
spaces from the standard Input device standard output device.
(keyboard). Syntax:
-gets() stops reading character from keyboard puts(variable_name);
only when the enter key is pressed. Example:
Syntax: char name[25];
gets(variable_name); puts(name);
Example:
char name[25];
gets(name);
Program to read and print the string using
gets and puts:
#include<stdio.h>
main()
{ Output:
char name[20]; enter the string
printf("enter the string\n"); hello my
gets(name); friend hello my
puts(name); friend
return(0);
}
Program to convert character from lower case to uppercase and vice versa:
#include<stdio.h> Output 1:
int main() enter the character
{ g
char a; G
printf("enter the character\n"); Output 2:
a=getchar(); enter the character
if(islower(a)) G
putchar(toupper(a)); g
}
else
{
putchar(tolower(a));
} return(0);
}
Difference Between Formatted And Unformatted Input/Output Functions:
Formatted Unformatted
1. These are standard input output library These are console input output library function.
function.
2. Formatted input and output functions can Unformatted input/output can deal with one
deals with all kind of data types. character at a time and string function for array
of characters (string).
3. Unformatted Input / Output functions Formatted Input / Output functions are several
have fixed format to give the input and standard library functions
obtain the output.
1. if statement
If the condition is true, the statements inside if statement will be executed.
If the condition is false, the control will be transferred to the statements outside of if.
If 'expression' is false the 'statement-3' will be executed, otherwise it continues to check the
condition for 'expression 1' .
If the 'expression 1' is true the 'statement-1' is executed otherwise 'statement-2' is executed
65
I YEAR/I SEM
4. else-if ladder :
If there are more than three alternatives, we can go for else if ladder.
Once a true condition(if) is satisfied, the other statements in the ladder will be skipped.
When all conditions became false, then the final else part which contains default statement will
be executed.
66
I YEAR/I SEM
}
else
printf("Root are imaginary\n");
}
Program to find the entered key is an alphabet or numeric Output:
or alphanumeric(using character Build-in functions) Enter any key
#include<stdio.h> 8
int main() Entered key is number
{
char a;
printf("Enter any key\n");
a=getchar();
if(isdigit(a))
printf(" Entered key is number");
else if(isalpha(a))
printf("Entered key is alphabet");
else
printf("Entered key is alphanumeric");
return(0);
}
Program to find the entered key is an alphabet or numeric or Output:
alphanumeric(using print, scanf statements) enter a single character or
#include<stdio.h> value
int main() [
{ Alphanumeric
char ch;
printf("enter a single character or value \n"); scanf("%c",&ch);
if((ch>='a')&&(ch<='z'))
printf("Alphabet\n");
else if((ch>='0')&&(ch<='9'))
printf("Number\n");
else
printf(("Alphanumeric\n")); return(0);
}
Note:
In if statement, a single statement can be written without using curly braces { }
Eg, int x=2;
if(x > 4)
printf("welcome");
In the above case, no curly braces are required, but if we have more than one statement
inside if condition, then we must use curly braces.
Other than 0(zero), all other values are considered as true.
Eg, if(9)
printf("welcome");
In above example, hello will be printed, because the integer 9 is a non zero value. 68
I YEAR/I SEM
Switch statement:
C provides a multi way decision statement called switch statement.
It allows the user to make a decision from number of choices.
The expression(condition) in switch case return an integer value or character constant,
which is compared with the values in different cases.
When the condition matches with the case ,that block of statement is executed.
If there is no match, then default statement is executed.
Note:
It isn't necessary to use break after each block, but if you do not use it, all the consecutive block of
codes will get executed after the matching block.
int i = 1;
switch(i)
{
case 1:
printf("A"); // No break case 2:
printf("B"); //No break case 3:
printf("C");
break;
}
Output : A B C
- The output was supposed to be only A because only the first case matches, but as there is no break
statementaftertheblock,thenextblocksareexecuted,untilthe cursor encounters a break.
Rules for switch Statement:
o Default case is optional andcan be placed anywhere in the switch case. But Usualy we place 69
itattheend.
I YEAR/I SEM
break;
case 4 :
printf("Division is %d : ",a/b);
break;
default :
printf(" Enter Your Correct Choice.");
break;
}
return(0);
}
Printing student GPA details using switch case:
#include<stdio.h> Output:
int main() Enter three subject
{ Marks95
int m1,m2,m3,gpa; 94
float tot, avg; 96
printf("Enter three subject Marks"); grade=A
scanf("%d%d%d",&m1,&m2,&m3);
tot=m1+m2+m3;avg=tot/3; gpa=avg/10;
switch(gpa)
{
case 10: printf("grade=S"); break;
case 9 : printf("grade=A"); break;
case 8 : printf("grade=B"); break;
case 7 : printf("grade=C"); break;
case 6 : printf("grade=D"); break;
case 5 : printf("grade=E"); break;
default : printf("grade=F");
}
return(0);
}
LOOPING STATEMENTS / ITERATIVE STATEMENTS:
In Loop, sequence of statements are executed until a specified condition is true.
This sequence of statements to be executed is kept inside the curly braces { } known as the
Loop body.
After every execution of loop body, condition is verified, and if it is found to be true the loop
body is executed again. When the condition check returns false, the loop body is not executed.
There are 3 type of Loops in C language
for loop
while loop
do-while loop
Entry controlled loop Exit controlled loop
The test condition is checked first before The loop is executed first and then condition
the loop is executed. is checked. 71
I YEAR/I SEM
while Loop:
It is an entry controlled looping statement.
Statements are executed repeatedly until the while condition is true.
It is completed in 3 steps.
Variable initialization. ( e.g int x=0; )
Condition Checking ( e.g while( x<=10) )
Variable increment or decrement ( x++ or x-- or x=x+2)
Description:
Step 1: The while condition is checked first.
Step 2: If the condition is true, the statements inside the loop will be executed, then the variable
value is incremented or decremented at the end of the looping statement.
Step 3: If the condition is false, the loop body will be skipped and the statements after the while
loop will be executed.
}
if(rev == n )
printf("It is a palindrome no.\n"); else
printf("it is not a palindrome no.\n"); return(0);
}
To Check Armstrong number or not: Output:
#include <stdio.h> Enter a number
int main() 153
{ Its an Armstrong number
int n, arm = 0, dig, temp;
printf("Enter a number\n");
scanf("%d", &n);
temp=n;
while (temp != 0)
{
dig = temp %10;arm= arm + (dig*dig*dig);
temp = temp/10;
}
if(arm==n)
printf("Its an Armstrong number"); else
printf("Its an not Armstrong number"); return(0);
}
do whileloop:
It is an exit controlled looping statement.
The do-while loop checks its condition at the bottom of the loop whereas for and while loops,
the loop condition is checked at the top of the loop.
do-while loop is guaranteed to execute the statement at least one time.
74
I YEAR/I SEM
While Do while
Conditionistestedfirstandthen statements are Statements are executed at least
executed. once. then the conditions are
tested.
While loop is entry controlled loop Do wile loop is exit control
loop.
for loop:
for loop is usedtoexecutea set of statements repeatedlyuntilaparticularconditionis satisfied.
Flow of Execution:
i.The initialization step is executed first, and only once. This step allows to declare and
initialize any loop control variables.
ii.Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop will not be executed and flow of control jumps to the next
statement just after the for loop.
iii.After the body of the for loop executes, the flow of control jumps back up to the
increment statement. This statement allows to update any loop control variables.
iv.The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). When the
condition becomes false, the for loop terminates.
Different ways of implementing for loop:
Form Comment
for(i=0;i<10;i++)
Single Statement
Statement1;
for ( i=0 ; i < 10;i++) ; For Loop with no Body ( Carefully Look
at the Semicolon ) 76
I YEAR/I SEM
{
int i, n, a = 0, b = 1, next;
printf("Enter the number of terms: ");
scanf("%d", &n);
for (i = 1; i <= n; ++i)
{
printf("%d,",a);
next=a+b;
a=b;
b=next;
}return 0;
}
To find Factors of a given number: Output:
#include<stdio.h> Enter a number to find
int main() its factors
{ 10
int n,i; factors are: 1
printf("Enter a number to find its factors\n"); factors are: 2
scanf("%d",&n); factors are: 5
for (i=1;i<=n;i++) factors are: 10
{
if(n%i==0)
printf("factors are: %d\n",i);
}
return(0);
}
Program to check the number is prime or not: Output:
#include<stdio.h> enter the no
int main() 11
{ number is prime
int n,i,flag; printf("enter the no\n");
scanf("%d",&n);
for(i=2;i<n;i++) Note:
{ Flag is a Boolean variable that
if(n%i==0) has only 2 states (0 and 1)
{ Eg, On/Off, True/False,
flag=0; Yes/No
break;
}
}
if(flag==0)
printf("number is not prime \n");
else
printf("number is prime\n");
return(0);
}
79
I YEAR/I SEM
Flowchart:
2) continue statement:
C Continue statement are used to skips the rest of the current iteration in a loop and returns to
the top of the loop.
Syntax:
continue;
81
I YEAR/I SEM
Example:
Use of break statement Output: Use of continue statement to Output:
to print numbers: print numbers:
#include <stdio.h> enter the enter the
int main() #include <stdio.h>
number: 10 number: 10
{ int main()
1 { 1
int i,num;
printf("enter the number: "); 2 int i,num; 2
scanf("%d",&num); 3 printf("enter the number: "); 3
for(i=1;i<=num;i++) 4 scanf("%d",&num); 4
{ for(i=1;i<=num;i++) skipped
if(i==5) { 6
{ if(i==5)
7
printf("stop"); {
printf("skipped\n"); 8
break;
} continue; 9
printf("%d\n",i); } 10
} printf("%d\n",i);
return(0); }
} return(0);
}
Break Continue
Break statement is used to transfer the Continue is used to skip some statement of
controlof the program to outside loop or the loop and moves to the next iteration in
switch case statement. the loop.
It is used in loop as well as switch case. It is used only within the loop.
Syntax: break; Syntax: continue;
3) goto statement:
The goto statement is used for altering the normal sequence of program execution by
transferring control to some other part of the program.
When a goto statement is encountered in a C program, the control jumps directly to the
label mentioned in the goto statement.
It us used when loops are deeply nested and simple break statement cannot work
effieciently.
Syntax:
goto label_name;
…
…
label_name
82
I YEAR/I SEM
Preprocessor Directives:
Preprocessor is a program which will be executed automatically before passing the source
program to compiler. This process is called pre-processing.
The preprocessor provides the ability for the inclusion of header files, macro expansions,
conditional compilation, and line control.
Commands used in preprocessor are called preprocessor directives.
They begin with "#" symbol and should be not ended with (;)
Proprocessor Directive can be place any where in the program, but generally it place top of the
program before defining the first function.
Preprocessor directives in C:
Macro substitution directives. example: #define
File inclusion directives. example: #include
Conditional compilation directive. example: #if, #else, #ifdef, #undef, #endif
Miscellaneous directive. example: #error, #line
83
I YEAR/I SEM
Example: Tocheck the Vote eligibility using #if, #else and #endif
#include<stdio.h> Output:
#define AGE 5 Not eligible
int main()
{
#if (AGE>=18)
{
printf("Eligible for voting");
}
#else
{
printf("\n Not eligible");
}
#endif
return(0);
}
#ifdef, #else and #endif:
- #ifdef" directive checks whether particular macro is defined or not.
- If it is defined, "If" clause statements are included in source file. Otherwise, "else" clause
statements are included in source file for compilation and execution.
- In the below example1 macro is not defined. So, else part is executed.
Example: Example:
#include<stdio.h> #include<stdio.h>
int main() #define AGE 1
{ int main()
#ifdef AGE {
{ #ifdef AGE
printf("Eligible for voting\n"); {
} printf("Eligible for voting\n");
#else }
{ #else
printf("Not eligible\n"); {
} printf("Not eligible\n");
#endif }
return(0); #endif
} return(0);
}
Output: Output:
Not eligible Eligible for voting
undef
This directive undefines existing macro in the program.
In below program we first undefine age variable and again it is defined with new value.
Example: Undefining the macro Output:
#include<stdio.h> First define value for age is:
85
#define age 20 20
I YEAR/I SEM
PART A:
1. What are variables? Give Examples (M/J’16)(N/D’14)
2. Define implicit type conversion (M/J’16)
3. What is an array? Give Example (M/J’16) (M/J’15)
4. Define strings. Give examples(M/J’16)
5. What is meant by linking process? (N/D’15)
6. What are the input functions and output functions in C? (N/D’15) (M/J’15)
7. Write a C program to store Fibonacci series in an array. (N/D’15)
8. List the string functions available in C. (N/D’15)
9. List some pre-processor directives. (N/D’15)
10. What are the importance of keyword in C? (M/J’15)
11. How is a character string declared? (M/J’15)
12. Give the use of pre-processor directives. (M/J’15) (N/D’14) (M/J’14)
13. Give an Example of ternary operator. (N/D’14)
14. Describe float array of size 5 and assign 5 values in it. (N/D’14)
15. Give an example for initialization of string array.
16. Define static storage class. (N/D’14)
17. List different data types available in C. (M/J’14)
18. Write a C program to find factorial of the number using iteration. (M/J’14)
19. Write an example code to declare two dimensional array. (M/J’14)
20. List any 4 string handling functions (M/J’14)
PART B:
1. Explain different types of operators in detail.(M/J’16) (M/J’15) (N/D’14)
2. Discuss basic data types in C (M/J’16)
3. Describe various input and output statements in detail. (M/J’16)
4. Write a C program for the following series 1+2+3+4+…N (M/J’16)
5. Write a C program to convert the number of vowels in your name (M/J’16)
6. Write a C program to multiply two matrices/ Write a C program for two 3*3 Matrix
(M/J’16)/(N/D’15) (N/D’14)
7. Write a C program to check whether the given string is palindrome or not (M/J’16)
8. Write a C program to arrange the given 10 numbers in descending order (M/J’16
9. Explain various storage classes in detail. (M/J’16) (N/D’15) (M/J’15) (M/J’14)
10. Describe about pre-processors with suitable examples. (M/J’16) 86
I YEAR/I SEM
11. Describe the structure of C program using ‘calculator program’ example. (N/D’15)
12. Write short notes on branching statements in C. (N/D’15)
13. Write in detail about various looping statements with suitable example.(N/D’15) (M/J’15)
(N/D’14)
14. Write a C program to find determinant of the resultant matrix. (N/D’15)
15. Write the following programs (N/D’15)
(i) To sort the given set of strings alphabetically
(ii) To print whether each word is palindrome or not
(iii) To count the length of the string
16. What are constants? Explain various types of constants in C. (M/J’15)
17. Write a C program to solve(roots of) Quadratic Equation ((M/J’15) (M/J’14)
18. Write a C program to add two matrices. (M/J’15)
19. Write a C program to search a number in an array of elements. (M/J’15) (N/D’14)
20. Write a C program to arrange the given 10 numbers in ascending order/ Write a C program to
sort array of numbers. (N/D’14) (M/J’15) (M/J’14)
21. Explain various string handling functions in C. (M/J’15)
22. Explain various string operations. Write a C program to find the length of the string without
using build in function. (N/D’14)
23. Write a short notes on (i) #include<stdio.h> (ii) ifdef.. # endif (N/D’14)
24. Write a C program to check the given number is prime or not (M/J’14)
25. Write a C program to find sum of digits of a number (M/J’14)
26. Explain entry and exit checked conditional structure with example(M/J’14)
27. Write a C program to subtract two matrices and display the resultant matrix.(M/J’14)
28. (M/J’14)
***************
87
I YEAR/I SEM
UNIT II ARRAYS AND STRINGS
Arrays: Introduction – Declaration of Arrays – Storing Values in Array – Accessing elements of
the Array– Operations on Array – one dimensional arrays – Two dimensional Arrays –String:
Declaring, Initializing, Printing and reading strings, String input and output functions, String
handling functions, Arrays of strings.
INTRODUCTION TO ARRAYS:
Anarray isacollectionof similar data items that arestored undera commonname.
Array is defined as finite ordered collection of similar data, stored in contiguous
(continues) memory locations.
It is a derived data type in C.
What is the use of array?
A single variable cannot store multiple values . But an array can store multiple values of
same data type in one single name.
Example where arrays are used,
to store roll numbers of the students in a class
to store marks of a students
to store list of names of employees etc..
Array can store integer, float and double values which is said to be integer array.
Array that is used to store characters are said to be Character array.
Features of array:
Array might be belonging to any of the data types
Array size must be a constant value.
Array index starts with 0 and ends with n-1.
Element of an array is accessed using index or subscript.
Always, Contiguous (adjacent) memory locations are used to store array elements in
memory.
It is a best practice to initialize an array to zero or null while declaring, if we don’t
assign any values to array.
Advantage of array:
Code Optimization: Less code is required, one variable can store numbers of
value.
Easy to traverse data: By using array easily retrieve the data of array.
Easy to sort data: Easily sort the data using swapping technique.
I YEAR/I SEM
Random Access: With the help of array index you can randomly access any
elements from array.
Types of an array:
1. Single dimensional array
2. Multi dimensional array
Single(one)dimensionalarray:
Array having only one subscript [ ] variable is called One-Dimensional array.
It is also called as Single Dimensional Array or Linear Array or list.
The elements of one dimensional array is also called as linear
array Declaring Array:
data_type array_name[size];
Example:
int roll_num[100];
char name[50];
double balance[10];
Initialization of an Array:
After an arrayis declared it must be initialized.
An array can be initialized in 2 ways (i) Compile time initialization
(ii)Run time initialization
(i) Compile time Array initialization:
- Compiletime initialization ofarrayelementsissame as ordinaryvariableinitialization.
Syntax:
data type array_name[size] = { list of values };
Example:
int marks[4]={ 67, 87, 56, 77 }; //integer array initialization
float area[5]={ 23.4, 6.8, 5.5 }; //float array initialization
double balance[10]={1000.0,20.0,3.4,7.2,50.0}
char str[10]={‘H’,‘a’,‘i’}; // character array
Accessing Array Elements:
We can access array elements with the help of index value of element.
Example:
int marks[50]={10,20,30,15,12}
here, marks is the array name and [50] is the maximum number of elements the array can
hold.
Printing array of numbers(Compile time initialization) Output:
#include<stdio.h> the elements in the
int main() array are
{ 95
int arr[40]={95,58,45,78}; 58
I YEAR/I SEM
int i; 45
printf("the elements in the array are\n"); 78
for(i=0;i<=3;i++)
{
printf("%d\n", arr[i]);
}
return(0);
}
Note: [40] is the maximum size the array can hold.
(ii)Runtime Array initialization:
- An array can also be initialized at runtime using scanf() function.
- This approach is usually used for initializing large array elements , or to initialize
arrayby getting the input from the user.
Syntax:
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
Reading and Printing array of elements( Run Time Output:
initialization) enter the size of an
#include<stdio.h> array
int main() 5
{ enter the elements of
int arr[100],n,i; an array
printf("enter the size of an array\n"); 45
scanf("%d",&n); 45
printf("enter the elements of an array\n"); 78
for(i=0;i<=n-1;i++) 4
{ 12
scanf("%d",&arr[i]); the elements are
} 45
printf("the elements are\n"); 45
for(i=0;i<=n-1;i++) 78
{ 4
printf("%d\n",arr[i]); 12
}
return(0);
}
Operations on 1Darray:
1. Subscripting an 1D array
It is an action of selecting an element from an array.
printf(“%d”, a[5]);
2. Assigning an array to another array
I YEAR/I SEM
A variable can be assigned to another variable but array can’t be assigned to
another arraydirectly.
Output:
#include<stdio.h> //compilation error
int main()
{
int a[3],b[3]={1,2,3};
a[3]=b[3];
printf(“%d”, a[0]);eturn(0);
}
Illustrative Programs:
Searching: Searching is a process of finding a particular element in a given list.
Types:
1. Linearsearch
2. Binary search
Linear Search
- It is a process of finding an element in the list from the beginning and continues till
the end of the list.
Concept of linear Search:
i. To search an element we want, we start with the first element in the list. If this is the
required element, our search is over.
ii. Else, we take up the second element and see if this is the element we search for.
iii. If this is too not the element, we pick up the third element and compare.
iv. This process continues until the element we search for is found.
Advantages:
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27
I YEAR/I SEM
and we have a sorted array, so we also know that the target value must be in the upper
portion of the array.
We change our low to mid + 1 and find the new mid value again.
Like this searching continues until we find the desired element.
Advantages:
Faster than linear search.
Disadvantages :
Binary search algorithm can work only with the sorted array (either ascending or
descending order).
It is time consuming and waste of memory allocation.
If the element to be identified occurs more than once, then it will show the occurrence of
the first one.
Program for Binary search: Output:
#include <stdio.h>
int main() enter size of array
{ 6
int i, first, last, middle, n, item, arr[50]; enter the elements
printf("enter size of array"); 5
scanf("%d",&n); 12
printf("enter the elements\n"); 4
for (i = 0; i <=n-1; i++) 7
{ 18
scanf("%d",&arr[i]); 240
} Enter element to find
printf("Enter element to find\n"); 18
scanf("%d", &item); 18 found at location 4
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (arr[middle] < item)
{
first = middle + 1;
}
else if (arr[middle] == item)
I YEAR/I SEM
{
printf("%d found at location %d.\n", item, middle);
break;
}
else
{
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("%d is not present in the list\n", item);
return (0);
}
Selection Sort:
The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order)
from the unsorted subarray is picked and moved to the sorted subarray.
Consider the following example:
Example:
int arr[2][2];
- this array can hold 2*2=4 elements totally.
I YEAR/I SEM
Array Initialization:
(i) Compile time Initialization
Array Initialization Syntax:
data_type arr_name[2][2] = {{0,0},{0,1},{1,0},{1,1}};
Example:
int arr[2][2] = {1,2, 3, 4};
int arr[2][3] = { {0,0,0}, {1,1,1} };
int arr[2][3] = { 0,0,0, 1,1,1 };
Array accessing syntax:
arr_name[index];
Example:
int arr[2][2] = {1,2, 3, 4};
arr [0] [0] = 1;
arr [0] ]1] = 2;
arr [1][0] = 3;
arr [1] [1] = 4;
Invalid initializations:
Following initializations are wrong and invalid.
int arr[2][ ]={1,2,3,4}; // We need to mention the column size.
Otherwise compiler do not know where the first row size ends.
ii) Run Time initialization:
Syntax:
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,a[i][j]);
}
}
Programs on two dimensional arrays:
C Program To read and display 2 dimensional matrix Output:
#include <stdio.h> enter the size of row and
int main() column
{ 3
int a[10][10]; 3
int i,j,m,n; enter the elements of
printf("enter the size of row and column\n"); matrix
scanf("%d%d",&m,&n); 5
printf("enter the elements of matrix\n"); 2
I YEAR/I SEM
for(i=0;i<=m-1;i++) 5
{ 2
for(j=0;j<=n-1;j++) 5
{ 2
scanf("%d",&a[i][j]); 5
} 2
} 5
printf("the elements are\n"); the elements are
for(i=0;i<=m-1;i++) 5 2 5
{ 2 5 2
for(j=0;j<=n-1;j++) 5 2 5
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
return(0);
}
Program for Matrix Addition: Output:
#include <stdio.h> Enter the size of row and
int main() column
{ 2
int a[10][10], b[10][10]; // array declaration for matrix a&b 2
int c[10][10]={0}; // c matrix initialized to 0 Enter the elements of A
int i,j,m,n; matrix
printf("Enter the size of row and column\n"); 1
scanf("%d%d",&m,&n); //reading size or row and column 3
printf("Enter the elements of A matrix\n"); 2
for(i=0;i<=m-1;i++) 5
{ Enter the elements of B
for(j=0;j<=n-1;j++) matrix
{ 1
scanf("%d",&a[i][j]); //getting the elements of A matrix 5
} 5
} 6
printf("Enter the elements of B matrix\n"); Sum of two matrices:-
for(i=0;i<=m-1;i++) 2 8
{ 7 11
for(j=0;j<=n-1;j++)
{
scanf("%d", &b[i][j]); //getting the elements of B matrix
}
}
printf("Sum of two matrices:-\n");
for(i = 0;i<=m-1;i++)
{
I YEAR/I SEM
for(j=0;j<=n-1;j++)
{
c[i][j] = a[i][j] + b[i][j]; // addition of A and B matrix
printf("%d\t", c[i][j]);
}
printf("\n");
}
return(0);
}
Same program can be written for matrix subtraction with - sign c[i][j] = a[i][j] - b[i][j];
Disadvantages of an array:
The elements in an array must be same data type.
The size of an array is fixed. we can’t expand the size in run time.
The insertion and deletion operations in an array require shifting of
elements which takes more time.
I YEAR/I SEM
INTRODUCTION TO STRINGS
Nowadays, computers are widely used for word processing applications such as creating,
inserting, updating, and modifying textual data. Besides this we need to search for a
particular pattern within a text, delete it, or replace it with another pattern. So there is
actually a lot we as users do to manipulate the textual data.
Programming Tip: Character constants are enclosed in single quotes. String constants
are enclosed in double quotes.
In C language, a string is a null-terminated character array. This means that after the last
character, a null character ('\0') is stored to signify the end of the character array. For
example, if we write
We are declaring a character array that has five usable characters namely, H, E, L, L, and
O. Apart from these characters, a null character ('\0') is stored at the end of the string. So,
the internal representation of the string becomes HELLO'\0'. To store a string of length 5,
we need 5 + 1 locations (1 extra for the null character). The name of the character array
(or the string) is a pointer to the beginning of the string. Figure 6.1 shows the difference
between character storage and string storage.
Then the null character will not be appended automatically to the character array. This is
because str can hold only 5 characters and the characters in HELLO have already filled the
locations allocated to it.
I YEAR/I SEM
Note
Programming Tip: When allocating memory space for a character array, reserve space
to hold the null character also.
Like we use subscripts (also known as index) to access the elements of an array, similarly
subscripts are also used to access the elements of the character array. The subscript
starts with a zero (0). All the characters of a string array are stored in successive memory
locations. Figure 6.2 shows how str[] is stored in ed in memory.
Thus we see that a string is a sequence of characters. In Figure 6.2, 1000, 1001, 1002, and
so on are the memory addresses of individual characters. From the figure, we see that H
is stored at memory location 1000 but in reality the ASCII codes of characters are stored
in memory and not the character itself, i.e., at address 1000, 72 will be stored since the
ASCII code for H is 72.
The above statement declares a constant string as we have assigned value to it while
declaring the string. However, the general form of declaring a string is
char str[size];
When we declare the string in this way, we can store size -1 characters in the array
because the last character would be the null character. For example, char mesg [100]; can
store a maximum of 99 usable characters.
Till now we have seen one way of initializing strings. The other way to initialize a string is
to initialize it as an array of characters, like
We can also declare a string with size much larger than the number of elements that are
initialized. For example, consider the statement below:
In such cases, the compiler creates a character array of size 10; stores the value "HELLO"
in it and finally terminates the value with a null character. Rest of the elements in the
array are automatically initialized to NULL. Figure 6.3 shows the memory representation
of such a string.
char str[3];
str =
"HELLO";
The above declaration is illegal in C and would generate a compile time error because of
two reasons. First, the array is initialized with more elements than it can store. Second,
initialization cannot be separated from declaration.
Note
An array name cannot be used as the left operand of an assignment operator. Therefore,
the following statement is illegal in C.
str2 = strl;
I YEAR/I SEM
Reading Strings
If we declare a string by writing
char str[100];
scanf("%s", str);
Programming Tip: Using & operand with a string variable in the scanf statement is
optional as string variable is a character array and denotes the address where the array
begins.
Although the syntax of scanf() function is well known and easy to use, the main pitfall
with this function is that the function terminates as soon as it finds a blank space. For
example, if the user enters Hello World, then str will contain only Hello. This is because
the moment a blank space is encountered, the string is terminated by the scanf()
function. You may also specify a field width to indicate the maximum number of
characters that can be read in. Remember that extra characters are left unconsumed in
the input buffer.
Unlike int (%d), float (f), and char (c), %s format does not require ampersand before the
variable name.
Note
When scanf() encounters a white space character, it ter- minates reading further and
appends a null character to the string that has been read. The white space character is
left in the input stream and might be mistakenly read by the next scanf() statement. So
in order to delete the white space character from the input stream, either use a space in
the format string before the next conversion code or FLUSH the input stream by using
the fflush function by writing fflush(stdin).
The next method of reading a string is by using gets () function. The string can be read by
writing
gets (str);
I YEAR/I SEM
gets () is a simple function that overcomes the drawbacks of the scanf() function. The
gets () function takes the starting address of the string which will hold the input. The
string inputted using gets () is automatically terminated with a null character.
Last but not the least, strings can also be read by calling the getchar() function repeatedly
to read a sequence of single characters (unless a terminating character is entered) and
simultaneously storing it in a character array as shown below.
i=0;
str[i] = ch;
i++;
Note that in this method, you have to deliberately append the charac- ters with a null
character. The other two functions automatically do this.
Writing Strings
Strings can be displayed on screen using three ways:
We use the conversion character 's' to output a string. We may also use width and
precision specifications along with %s (as discussed in Chapter 2). The width specifies the
minimum output field width. If the string is short, extra space is either left padded or right
padded. A negative width left pads short string rather than the default right justification.
The precision specifies the maximum number of characters to be displayed. If the string is
long, the extra characters are truncated. For example,
printf("%5.3s", str);
The above statement would print only the first three characters in a total field of five
characters. Also these three characters are right justified in the allocated width. To make
the string left justified, we must use a minus sign. For example,
printf("%-5.3s", str);
Note
When the field width is less than the length of the string, the entire string will be
printed. Also if the number of characters to be printed is specified as zero, then nothing
is printed on the screen.
The next method of writing a string is by using puts () function. The string can be displayed
by writing
puts (str);
puts () is a simple function that overcomes the drawbacks of the printf() function. The
puts () function writes a line of output on the screen. It terminates the line with a newline
character ('\n'). It returns an EOF (-1) if an error occurs and returns a positive number on
success. Last but not the least, strings can also be written by calling the putchar() function
repeatedly to print a sequence of single characters.
i=0;
putchar (str[i]);
Note
#include
<conio.h> int
main()
clrscr();
getch();
return 0;
Output
| Introduction to C |
| Introduction to C |
| Introduction to C |
| Intr |
| Intr |
| Intr |
The printf() function in UNIX supports specification of variable field width or precision, i.e.,
if we write,
pattern. H
HE
HE
HELL
H E L L
O H E L
L O H E
LL
HE
LH
EH
#include <stdio.h>
#include
<conio.h> int
main()
int i, w, p;
printf("\n");
p = i+1;
I YEAR/I SEM
printf("\n %-5.*s", p, str);
printf("\n");
p = i+1;
getch();
return 0;
sprintf() Function
The library function sprintf() is similar to printf (). The only difference is that the formatted
output is written to a memory area rather than directly to a standard output
(screen). sprintf() is useful in situations when formatted strings in memory have to be
transmitted over a communication channel or to a special device. The syntax
of sprintf() can be given as
Here, buffer is the place where string needs to be stored. The arguments command is an
ellipsis so you can put as many types of arguments as you want. Finally, format is the
string that contains the text to be printed. The string may contain format tags.
#include
<stdio.h> main()
char buf[100];
}
I YEAR/I SEM
UNIT III FUNCTIONS AND POINTERS
Library functions: Math functions, other miscellaneous functions such as getchar(), putchar(), malloc(),
calloc().
User defined functions - function definition, functions declaration, function call, scope of variables - local
variables, global variables.
Function parameters: Parameter passing- call by value & call by reference, Passing arguments to
Functions, Recursive functions. Storage classes-auto, register, static, extern, scope rules.
1. **Math Functions**: These functions are part of the `<math.h>` library in C and C++. Some
commonly used math functions include:
- `sin`, `cos`, `tan`: Trigonometric functions
- `exp`, `log`, `log10`: Exponential and logarithmic functions
- `sqrt`, `pow`: Square root and power functions
- `ceil`, `floor`: Ceiling and floor functions
- `abs`: Absolute value
- `round`, `trunc`: Rounding functions
Example:
```c
#include <math.h>
double result = sin(3.14);
```
2. **Character I/O Functions**: These functions handle character input and output operations. In
C, `getchar()` and `putchar()` are commonly used.
- `getchar()`: Reads a single character from standard input (usually the keyboard).
- `putchar()`: Writes a single character to standard output (usually the console).
Example:
```c
int ch = getchar();
I YEAR/I SEM
putchar(ch);
```
3. **Dynamic Memory Allocation Functions**: These functions allow dynamic memory allocation
during runtime, managed through `<stdlib.h>`.
- `malloc()`: Allocates a block of memory of a specified size in bytes.
- `calloc()`: Allocates a block of memory for an array of elements, initialized to zero.
- `realloc()`: Resizes the previously allocated block of memory.
Example:
```c
#include <stdlib.h>
int *arr = malloc(10 * sizeof(int)); // Allocates memory for an array of 10 integers
```
These functions are essential in programming as they provide efficient and tested implementations
for tasks like mathematical calculations, character input/output, and memory management, saving
developers from having to implement these functionalities from scratch.
FUNCTIONS:
o A function is a block of code or set of statements that are used toperform a particular task
which repeatedly occurs in the main program.
o By using functions, we can divide complex problem into small components that makes
program easy to understand and use.
o A function is often executed several times, from several different places(sub function) during
the execution of the program.
o After executing the subprogram, the program control return back to main function.
Syntax Example
return-type function-name (parameter-list) int add(int x,int y)
{ {
body of function; int z;
} z=x+y;
return(z);
}
return Statement:
return type specifies the type of value(int, float, char, double) that function is expected to return to the program
calling the function.
It may or may not present send back result to calling function.
Syntax Example
return; return;
I YEAR/I SEM
return(); return();
return(value); return(1);
return(variable); return(c);
Note:
Default data type is int.
Only one value can be returned to a function. Pointers are used to return more values.
If return (a,b,c) is used, only c value is returned to the function
Example:
Calling the function by simply specifying the function name, return value and parameters if present.
Syntax Example
return_variable= function_name(arg1, arg2, ….arg n); c=add(x,y);
Types of Arguments/Parameters:
Output:
globally declared values: m=10 n=10
locally declared values: m=20 n=20
without arguments and without return type without argument and with return type
/* Addition of two numbers */ /* Addition of two numbers */
#include<stdio.h> #include<stdio.h>
void my_add(); int my_add();
int main()
int main() {
{ int c;
int c; c=my_add();
c=my_add(); printf("sum is %d",c);
return(0); return(0);
} }
Output: Output:
enter the values enter the values
5 5
6 6
sum is 11 sum is 11
With argument and without return type With argument and with return type
I YEAR/I SEM
/* Addition of two numbers */ /* Addition of two numbers */
#include<stdio.h> #include<stdio.h>
void my_add(int a,int b); int my_add(int a, int b);
Output: Output:
enter the values enter the values
5 5
6 6
sum is 11 sum is 11
Return Type:
S.no Result type Function
1 Integer strlen, strcmp,strcmpi
2 String strcat, strcpy, strrev, strupr, strlwr, strset, strnset
3 Address strchr, strnchr,strstr
This function returns the nearest integer which is less than or equal to the argument
floor ( ) passed to this function.
This function returns the nearest integer value that passed to this function. If
decimal value is from “.1 to .5”, it returns integer value less than the argument. If
decimal value is from “.6 to .9”, it returns the integer value greater than the
round() argument.
This function returns nearest integer value which is greater than or equal to the
ceil() argument passed to this function.
exp() This function is used to calculate the exponential “e” to the xth power.
sqrt() This function is used to find square root of the argument passed to this function.
trunk() This function truncates the decimal value from floating point value and returns
I YEAR/I SEM
integer value.
RECURSION FUNCTION:
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
But while using recursion, programmers need to be careful to define an exit condition from the
function, otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating the
factorial of a number, generating Fibonacci series, etc.
How Recursion Function Works?
The recursion continues until some condition is met .i,e it must have at least one if statement to
terminate the recursion.
Illustrative Program:
i) Computation of Sine series
ii) Scientific calculator using built-in functions (refer book page no 5.33)
iii) Binary Search using recursive functions .
For example,
STRUCTURES:
- Structure is a collection of various data types shares a common name.
- It is a user defined data type.
- Each element in a C structure is called member.
Example:
Student: name, roll no, mark, avg
Book: author, title, price, year
Address: door no, street name, place, state, pin
Arrays Structures
It uses index or subscript to access It uses (.) dot operator and ->(pointer) operator to access members of
an arrayelement. structures
Steps :
1. Declaring structure
2. Declaring structure variable
3. Initializing the members of the structure
4. Accessing the members of structure
1. Declaring structure:
Syntax: Example:
{ {
float percentage;
datatype membern; };
};
Keyword struct is used for creating a structure. Note: semicolon }; in the ending line is must.
Syntax: Example:
I YEAR/I SEM
struct tag_name
{ struct student
datatype member1; {
Syntax:
structure tagname_1 Example:
{ struct Employee
data_type member1; {
data_type member2; char ename[20];
data_type member3; int empid;
.. int salary;
member n; struct date
structure tagname_2 {
{ int day;
data_type member_1; int month;
data_type member_2; int year;
data_type member_3; }doj;
... }emp;
member_n;
} var1;
} var2;
Syntax:
AccessingdayField : emp1.doj.day
ARRAY OF STRUCTURES:
s[0].name : refers to the name member of the 0th element of the array.
s[0].roll_no : refers to the roll_no member of the 0th element of the array.
s[0].marks : refers to the marks member of the 0th element of the array.
printf("\n");
printf("Name\tRoll no\tMarks\n");
for(i = 0; i < MAX; i++ )
{
printf("%s\t%d\t%.2f\n",
s[i].name, s[i].roll_no, s[i].marks);
}
I YEAR/I SEM
return 0;
}
Note:
Here, array of size 5 to store information of 5 students.
Example:
Displaying book details using pointer to a structure:
#include <stdio.h>
struct book
{
int bookid;
char bookname[50];
char author[30];
float price;
};
int main()
{
struct book b1; // structure variable
declaration struct book *ptr; // pointer
variable declaration ptr=&b1; // pointer variable
initialization printf("enter the bookid\n");
scanf("%d",&ptr->bookid);
printf("enter the book name\
n"); scanf("%s",ptr-
>bookname); printf("enter
author\n"); scanf("%s",&ptr-
I YEAR/I SEM
>author);
I YEAR/I SEM
printf("Enter price");
scanf("%f",&ptr->price);
printf("book details are\n: %d\t %s\t %s\t %f\n\n",ptr->bookid,ptr->bookname,ptr->author,ptr->price);
}
Output:
enter the bookid
1001
enter the book name
python
enter author
Rossum
Enter price 450
book details are
1001 python Rossum 450.000000
Syntax:
Pointer_variable= (type_cast*) malloc(Size_in _bytes)
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable x
Here, 50 represents the total size to be allocated depending upon 16 bit or 32 bit processor. Hence given, sizeof() function irrespective of 2
byte or 4 byte integer
- If it fails to allocate enough space as specified, it returns a NULLpointer.
- malloc () does not initialize the memory allocated during execution. It carries garbage value.
Program (to copy a string to allocated memory using malloc()):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
I YEAR/I SEM
int main()
{
char *ptr;
ptr = (char*)malloc( 20 * sizeof(char) ); // memory is allocated dynamically
if( ptr== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( ptr,"good morning");
}
printf("Dynamically allocated memory content is : " \"%s\n", ptr);
free(ptr);
return(0);
}
Output:
Dynamically allocated memory content is : good morning
Syntax:
Pointer_variable= (type_cast*) calloc(n, element_size)
Example:
float *y;
y= (float*) calloc(25, sizeof(float));
Note:
This statement allocates contiguous space in memory to store 25 elements each of size of float( i.e, 4 bytes)
Syntax:
ptr = realloc(ptr, newsize); //ptr is reallocated with size of newsize.
Example:
int *x;
x = (int*)malloc(50 * sizeof(int));
x = (int*)realloc(x,100); //allocated a new memory to variable x
free()
- free() to release the space that are allocated using memory by malloc (), calloc (), realloc () functions .
- It returns the memory to the system.
Syntax:
free(pointer_variable);
Example:
int *x;
x = (int*)malloc(50 * sizeof(int)); //memory space allocated to variable
x free(x); //releases the memory allocated to variable x
C Program to generate Salary Slip of employee( Dynamic memory allocation for Structure using pointers):
#include <stdio.h> Output:
#include<stdlib.h> enter the number of employee2
struct employee enter the nameravi
{ Enter Basic Salary (RS): 12000
char name[10];
int basic, da, hra, ta, others; Enter Hra1000
int pf,it,t;
int net_salary; Enter da500
}e[10];
int main() Enter TA500
{
A structure that contains at least one pointers to a structure as its member along with other members is known as self-referential structure.
I YEAR/I SEM
Pointer variable declaration in structure Self-referential structure declaration
struct name { struct name {
member 1; member 1;
member 2; member 2;
... ...
member n; struct name *pointer;
}; };
struct name *pointer;
The above illustrated self referential structure prototype describes one node that comprises of two logical segments.
One segment stores data and the other segment is a pointer indicating where the next element is present.
Several such inter-connected nodes create a chain of structures(Linked List).
2. Deleting a node:
If node to be deleted is root, simply delete it.
To delete a middle node, we must have pointer to the node previous to the node to be deleted. So if positions is not zero, we run a loop
position-1 times and get pointer to the previous node.
Advantages of linked list over arrays:
1) list uses Dynamic size whereas, array uses static size.
2) Easy to insert/delete element in list where as array requires shifting of elements.
Drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search
with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
Program to insert, delete and display the elements in singly linked list Output:
void insert()
{
t=h;
p=(LIST*)malloc(sizeof(LIST));
printf("enter the element to be inserted\n");
scanf("%d",&p->no);
printf("enter the position to insert\n");
scanf("%d",&pos);
if(pos==1)
{
h=p;
h->next=t;
}
else
{
for(j=1;j<(pos-1);j++)
t=t->next;
p->next=t->next;
t->next=p;
t=p;
I YEAR/I SEM
I YEAR/I SEM
}
}
void delet()
{
printf("enter the position to delete:\n");
scanf("%d",&pos);
if(pos==1)
{
h=h->next;
}
else
{
t=h;
for(j=1;j<(pos-1);j++)
t=t->next;
pt=t->next->next;
free(t->next);
t->next=pt;
}
}
void display()
{
t=h;
while(t->next!=NULL)
{
printf("\t%d",t->no);
t=t->next;
}
printf("\t %d\t",t->no);
}
TYPEDEF:
- Typedef keyword is used to create a user defined name for existing data type.
- Generally typedef are use to create an alias name (nickname).
Syntax:
typedef datatype alias_name;
typedef int intdata;
1. C program to read, display, add, and subtract two distances. Distance must bedefined Output
using kms and meters using structures.(typedef)
Program:
#include <stdio.h> ***MAIN MENU***
typedef struct distance 1. Read the distances
2. Display the distances
{
3. Add the distances
int kms; 4. Subtract the distances
int metres; 5. EXIT
} DISTANCE; // structure variable Enter your option: 1
DISTANCE add_distance (DISTANCE, DISTANCE);
DISTANCE Enter the first distance in kms and metres:
subtract_distance(DISTANCE,DISTANCE); 3
320
DISTANCE dl, d2, d3, d4;
Enter the second distancekms and metres:
int main() 5
{ 100
int option;
do ***MAIN MENU***
{ 1. Read the distances
2. Display the distances
printf("\n ***MAIN MENU***");
3. Add the distances
printf ("\n 1. Read the distances "); 4. Subtract the distances
printf ("\n 2. Display the distances"); 5. EXIT
printf ("\n 3. Add the distances "); Enter your option: 2
printf ("\n 4. Subtract the distances");
printf ("\n 5. EXIT"); The first distance is: 3 kms 320 metres
printf ("\n Enter your option: "); The second distance is: 5 kms 100 metres
***MAIN MENU***
scanf("%d", &option); 1. Read the distances
switch(option) 2. Display the distances
{ 3. Add the distances
case 1: 4. Subtract the distances
printf("\n Enter the first distance in kms and metres: "); 5. EXIT
scanf ("%d %d", &dl .kms, &dl .metres); Enter your option: 3
printf("\n Enter the second distancekms and metres: ");
The sum of two distances is: 8 kms 420 metres
scanf ("%d %d" , &d2 .kms, &d2 .metres); ***MAIN MENU***
break; 1. Read the distances
case 2: 2. Display the distances
printf("\n The first distance is: %d kms %d metres " , dl.kms, dl.metres); printf("\ 3. Add the distances
n The second distance is: %d kms %d metres " , d2 .kms, d2 .metres); 4. Subtract the distances
break; 5. EXIT
Enter your option: 4
case 3:
d3 = add_distance(dl, d2); The difference between two distances is: 1
I YEAR/I SEM
printf("\n The sum of two distances is: %d kms %d metres", d3.kms, d3.metres);
2.C program to add, subtract two complex numbers using structure. Output
Program: Press 1 to add two complex numbers
#include <stdio.h> Press 2 to subtract two complex numbers
#include <stdlib.h> Press 3 to exit
struct complex Enter your choice
{ 1
int real, img; Enter a and b where a + ib is the first complex
}a,b,c; // Structure Variable number.
int main() a=3
{ b=5
Enter c and d where c + id is the second
I YEAR/I SEM
int choice; complex number.
while(1)
{ c=2
printf("Press 1 to add two complex numbers\n"); d=6
printf("Press 2 to subtract two complex numbers\n"); Sum of two complex numbers = 5 + 11i
printf("Press 3 to exit\n"); Press any key to enter choice again...
printf("Enter your choice\n");
scanf("%d",&choice); Press 1 to add two complex numbers
if( choice == 3) Press 2 to subtract two complex numbers
{ Press 3 to exit
exit(0); Enter your choice
} 2
if(choice >= 1 && choice <= 2) Enter a and b where a + ib is the first complex
{ number.
printf("Enter a and b where a + ib is the 1st complex number."); a=1
printf("\na = "); b=1
scanf("%d", &a.real); Enter c and d where c + id is the second
printf("b = "); complex number.
scanf("%d", &a.img); c=2
printf("Enter c and d where c + id is the 2nd complex number."); d=1
printf("\nc = "); Difference of two complex numbers = -1 + 0i
scanf("%d", &b.real); Press any key to enter choice again...
printf("d = "); Press 1 to add two complex numbers
scanf("%d", &b.img); Press 2 to subtract two complex numbers
} Press 3 to exit
if ( choice == 1 ) Enter your choice
{ 3
c.real = a.real + b.real;
c.img = a.img + b.img;
if ( c.img >= 0 )
printf("Sum of two complex numbers = %d + %di", c.real, c.img);
else
printf("Sum of two complex numbers = %d %di",c.real,c.img);
}
else if ( choice == 2 )
{
c.real = a.real - b.real;
c.img = a.img - b.img;
if ( c.img >= 0 )
printf("Difference of two complx no = %d + %di",c.real, c.img);
else
printf("Difference of two complex no = %d %di", c.real, c.img);
}
printf("\nPress any key to enter choice again...\n");
}
}
3. Define a structure called student that would contain name, regno and marks of five
subjects and percentage. Write a C program to read the details of name, regno and marks of five subjects for 30 students and calculate
the percentage and display the name, regno, marks of 30 subjects and percentage of each student.( AssignmentQuestion)
I YEAR/I SEM
Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers – Example Program: Sorting of names –
Parameter passing: Pass by value, Pass by reference – Example Program: Swapping of two numbers and changing the value of a variable
using pass by reference.
POINTERS:
Apointerisavariablethatholdstheaddressofavariableor afunction.
It is a derived data type in c language.
Onlyaddresscanbeassignedtoapointervariable
Pointer variable is declared with * symbol.
Advantages:
Pointer reduces the code and improves the performance, because it direct access the address of variable.
Pointerscanbeusedtoreturnmultiple valuesfromafunctionviaarguments.
It allowsdynamic memory allocation.
Declarationofavariable:
Pointer_variable=&variable_name; p=&a;
Function Output
printf(“%d”,a); 50
printf(“%u”,&a); 1001
printf(“%u”,p); 1001
printf(“%u”,&p); 2047
printf(“%d”,*p); 50
Pointer Operators:
I YEAR/I SEM
Simply, To create pointer to a variable we use “*” operator and to find the address of variable we use “&” operator. Eg,
Note:
All the arithmetic operations can be performed on values. But only subtraction, increment and decrement can be performed on
address.
Addition:
We cannot add two pointers.
This is because pointers contain addresses, adding two addresses makes no sense, because you have no idea what address would
address it would point to. It may go beyond the limit also. Eg, p1+p2
Subtraction:
We can subtract two pointers.
This is because difference between two pointers gives the number of elements of its data type that can be stored between the two
pointers. Eg, p2-p1
Increment:
If the pointer p1 points to an integer whose address is 1000 , after this increment operation, p1 will point to the location 1002
because each time p1 is incremented, it will point to the next integer location which is 2 bytes next to the current location for
integer data type.
If p1 points to a character whose address is 1000, then the above operation will point to the location 1001 because the next
character will be available at 1001. Eg, p1++;
Decrement:
Similarly, depending upon the size of data type, the position is decremented Eg, p1--;
Operators Arithmetic operators on value Arithmetic operators on address
Example
Subtraction(-) *p1-*p2 p2-p1(legal)
5-6=-1 1002-1000=1(2 bytes of data)
c = *p1+*p2;
printf("*p1+*p2 = %d\n", c);
p3 = p1-p2;
printf("p1 - p2 = %u\n", p3);
p1++;
printf("p1++ = %u\n", p1);
p2--;
printf("p2-- = %u\n", p2);
Pointer initialization:
int a[5]={10,20,30,40,50};
int *p;
p=a;
here, pointer variable ‘p’ points only to the base address(starting address) of array.
So, p=a ;
is same as p=&a[0];
TYPES OF POINTERS:
NULL pointer:
1. When a null pointer is compared with a pointer to any object the result of comparison is always false.
2. Two null pointers always compares equal.
I YEAR/I SEM
I YEAR/I SEM
3. Dereferencing null pointer leadsto error.
Void pointer:
NULL vs Void Pointer – Null pointer is a value, while void pointer is a type
Declaration:
int **ptr; // declaring double pointers
I YEAR/I SEM
Initialization:
int a= 78;
int *ptr2; // pointer for variable a
int **ptr1; // double pointer for ptr2
ptr2 = &a; // storing address of a in ptr2
ptr1 = &ptr2;
Call by Value:
Actual and formal arguments will be created in different Actual and formal arguments will be created in same memory
memory location location
Slow processing because new address are created. Fast because existing address are used.
Illustrative Program( Swapping of two numbers and changing the value of a variable using pass by value and reference)
Swapping of 2 vaues(Exchanging) using call by reference: Swapping of 2 values(Exchanging) using call by Reference:
#include<stdio.h> #include<stdio.h>
void swap(int, int); void swap(int *x, int*y);
int main() int main()
{ {
int a=5,b=10; int a=5,b=10;
printf("Before Swap values of a and b is %d %d\n", a, b); printf("Before Swap values of a and b is %d %d\n", a, b);
swap(a, b); swap(&a, &b);
return(0); printf("After Swap values of a and b is %d %d\n", a, b);
} return(0);
}
void swap(int x, int y)
{ void swap(int *x, int *y)
int temp; {
temp = int temp;
x; x = y; temp = *x;
y = temp; *x = *y;
printf("after Swap values of a and b is %d %d\n", x, y); *y =
} temp;
Output: return;
before swap,value of an and b is 5 10 }
after swap,value of a and b is 10 5
Output:
Before Swap values of a and b is 5 10
After Swap values of a and b is 10 5
I YEAR/I SEM
I YEAR/I SEM
Preprocessor directives are commands in C and C++ that instruct the compiler to
preprocess the source code before actual compilation begins. They begin with a `#`
symbol and are processed by the preprocessor, which is a part of the compiler.
Macros defined using `#define` are simple text replacements performed by the
preprocessor. They are typically used to define constants or simple functions.
```c
#include <stdio.h>
#define PI 3.14159
#define SQUARE(x) ((x) * (x))
int main() {
double radius = 2.0;
double area = PI * SQUARE(radius);
return 0;
}
```
In this example:
- `PI` is a constant macro for the value of pi.
- `SQUARE(x)` is a macro that computes the square of `x`.
I YEAR/I SEM
```c
#include <stdio.h>
#define DEBUG 1
int main()
{ #ifdef
DEBUG
printf("Debugging information\n");
#else
printf("No debugging information\n");
#endif
return 0;
}
```
In this example:
- `#ifdef DEBUG` checks if the macro `DEBUG` is defined. If it is defined (`#ifdef`),
the code block between `#ifdef` and `#else` (or `#endif`) is included in the compiled
code.
- `#else` specifies what to do if `DEBUG` is not defined.
- `#endif` marks the end of the conditional directive block.
defined:
```c
I YEAR/I SEM
#ifndef DEBUG
printf("No debugging information\n");
I YEAR/I SEM
#else
printf("Debugging information\n");
#endif
```
Additionally, `#elif` can be used to provide an "else if" condition within a sequence of
`#ifdef` or `#ifndef` checks:
```c
#if defined(DEBUG_LEVEL) && DEBUG_LEVEL == 2
printf("Debugging level 2 information\n");
#elif defined(DEBUG_LEVEL) && DEBUG_LEVEL == 1
printf("Debugging level 1 information\n");
#else
printf("No debugging information\n");
#endif
```
### Summary
These preprocessor directives provide flexibility and control over how the source
code is processed and compiled, allowing for conditional compilation and defining
macros for code simplification and abstraction.
File handling
File: the file is a permanent storage medium in which we can store the data
I YEAR/I SEM
permanently.
Types of file can be handled
If fopen() unable to open a file than it will return NULL to the file pointer.
File-pointer: The file pointer is a pointer variable which can be store the address
of a special file that means it is based upon the file pointer a file gets opened.
Declaration of a file pointer:-
FILE* var;
Modes of open
puts(character-var,file-ptr);
CLOSING A FILE
File Operation
If fopen() unable to open a file then it will return NULL to the file-pointer.
fputc(character,file_pointer);
{
I YEAR/I SEM
FILE *fs,*fd;
char ch;
If(fs=fopen(“scr.txt”,”r”)==0)
If(fd=fopen(“dest.txt”,”w”)==0)
while(ch=fgets(fs)!=EOF)
fputc(ch,fd);
fcloseall();
gets(file pointer);
Syntax:
fputs(integer,file_pointer);
#include<stdio.h>
#include<stdlib.h>
void main()
FILE *fp;
int word;
/*place the word in a file*/
I YEAR/I SEM
fp=fopen(“dgt.txt”,”wb”);
If(fp==NULL)
{
word=94;
putw(word,fp);
If(ferror(fp))
printf(“Error writing to file\n”);
else
printf(“Successful write\n”);
fclose(fp);
/*reopen the file*/
fp=fopen(“dgt.txt”,”rb”);
If(fp==NULL)
{
/*clean up*/
fclose(fp);
}
Syntax:
fputs(string,file_pointer);
#include<string.h>
#include<stdio.h>
void main(void)
{
FILE*stream;