0% found this document useful (0 votes)
8 views

Complete C Notes

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Complete C Notes

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 142

Computer Language

 In 1972, C was developed by Dennis M. Ritchie at Bell Labs (AT&T) in USA.


 Robust: C is a robust language with rich set of built-in functions and operators to write
any complex programs.
 Efficient and Fast
 Portable: C program written on one computer can also run on the other computer with
small or no modification. Example: C program written in windows can also run on the
Linux operating system.
 A program’s instructions need to be written in a programming language that the
computer can understand.
 The first programming language is machine language.
 Computer languages were evolved from machine language to natural language (like
English language).
 Computer Languages are basically divided into three categories:
 Machine language
 Symbolic language
 High level languages

Machine Language
 Machine language was the first programming language in the early days of computers.
 The language which is understand by the computer hardware is called machine
language.
 It consists of 0’s and 1’s.
 Internally the computer consists of circuits which are made up of switches, transistors and
other electronic devices that can be in one of the two states: off or on, where off is
represented by 0 and on is represented by 1.
Assembly Language
 Writing program in machine language is difficult.
 The language which is represented using symbols or mnemonics is called as symbolic
language.
 This language is not understandable by the computer. Hence, it must be translated to the
machine language using the assembler.
High Level Language
 It is like natural language which can understandable by the programmer i.e., user.
 The High-Level Language instructions are not understandable by the machine.
 Compiler is used to convert High Level Language instructions into the Machine
Language instructions.
 First High-Level Language is FORTRAN. Examples for High Level Languages are: C,
C++, JAVA, COBOL etc.,
Steps to Solve Logical and Numerical Problems
It is a multistep process that requires that:
1. Understand the problem
2. Develop Solution
 Structure Chart
 Algorithm / Pseudo code
 Flowchart
3. Write the program
4. Test the program
Understand the problem
 The first step in solving any problem is to understand it.
 To solve any problem first you must understand the problem by reading the requirements
of the problem.
 Once you understand it, review with user(customer) and system analyst.
Develop Solution
To develop a solution to a problem the following tools are needed.
1) Structure Chart:
It is also known as a hierarchy chart, shows the functional flow through your program.
It shows how the problem is broken into logical steps; each step will be a separate module.
It also shows the interaction between all the parts of your program. It is like the architect’s
blueprint.
The below two are used to design the individual parts of the program.
Algorithm / Pseudo Code
Flowchart
2) Algorithm: It is an ordered sequence of unambiguous and well-
defined instructions that perform some task and halts in finite time
Let's examine the four parts of this definition more closely.
1. Ordered Sequence: You can number the step.
2. Unambiguous and well-defined instructions: Each instruction should be clear, understand
without difficulty. Performs some task
3. Halts in finite time: Algorithm must terminate at some point.
Pseudo Code
Definition: English-like statements that follow a loosely defined syntax and are used to convey
the design of an algorithm.
Pseudo-code and Algorithm Construction
3) Assignment:
variable = "expression"
4) Input/Output:
5) Get/enter/read “variable", "variable", ...
6) Display/print "variable", "variable", ...
7) Conditional:
8) 1. if “condition"
1.1 (subordinate) statement 1
1.2 etc ...
9) 2. else
2.1 (subordinate) statement 2
2.2 etc ...
10) Iterative:
11) 3. while "condition"
3.1 (subordinate) statement 1
3.2 etc ...
Example1: To determine whether a student is passed or not

Pseudo Code: Algorithm:


Begin
1. If student's grade is greater than or equal to 60
1. If grade >= 60
1.1 Print "passed"
1.1 Print "passed"
2. else
2. else
2.1 Print "failed"
2.1 Print "failed”
End

Example 2: Write an algorithm to determine a student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as the average of four marks.

Pseudo Code: Algorithm:


1. Input set of 4 marks Begin
2. Calculate their average by summing and dividing by 4 Step 1: Input M1, M2, M3, M4
3. if average is below 50 Step 2: GRADE 
(M1+M2+M3+M4)/4
4. Print “FAIL”
Step 3: if (GRADE < 50) then
5. else
Step 4: Print “FAIL”
Flowchart
6. Print “PASS ” Step 5: else
Step 6: Print “PASS”
Step 7: endif
End
 Pictorial representation of an algorithm is called flowchart. Or A diagram that uses
graphic symbols to depict the nature and flow of the steps in a process.

Flowchart to find the addition of two numbers Flowchart to find whether a given
year is a leap year or not

Start Start

Accept a, b Accept year

c=a+b

if (year%4 = = 0)

Display C
Display non
Display leap year leap year
End

End
Syntax Errors
1) Spelling mistakes. 2) Missing out a colon or semicolon at end of a statement.
3) Missing out brackets. 4) Using upper case characters in key words e.g., IF
instead of if.
5) Missing out quotes. 6) Using tokens in the wrong order
Logical Errors
 A logic error (or logical error) is a ‘bug’ or mistake in a program’s source code that
results in incorrect or unexpected behavior.
 It is a type of runtime error that may simply produce the wrong output or may cause a
program to crash while running.
Creating and Running Programs
Creating and running programs takes place in 4 steps.
1. Writing and Editing the program.
2. Compiling.
3. Linking the program with the required library functions.
4. Executing the program.
2. Building a C Program

1) Writing and Editing the program


 Software used to write programs is known as a text editor, where you can type, edit and
store the data.
 You can write a C program in text editor and save that file on to the disk with “.c”
extension. This file is called source file.
2) Compiling Program
 Compiler is used to convert High Level Language instructions into the Machine
Language instructions.
 It could complete its task in two steps. i) Preprocessor ii) Translator
Preprocessor:
 It reads the source file and checks for special commands known as preprocessor
commands (instructions which starts with # symbols).
 The result of preprocessor is called as translation unit.
 Preprocessor processes the source file before compilation only.
Translator:
 It is a program which reads the translation unit and converts the program into
machine language and gives the object module.
 This module is not yet ready to run because it does not have the required C and
other functions included.
3) Linking a program with required library functions
 C program is made up of different functions in which some functions can be
written by the programmer, other functions like input/output functions and
mathematical library functions, that exist elsewhere and must be attached to our
program.
 The linker assembles all of these functions and produces the executable file
which is ready to run on the computer.
4) Executing the program
 Once a program has been linked, it is ready for execution.
 Now, you can execute the program by using the run command.
 Loader is a program which is used to load the program from the disk to main
memory.
Writing and Running Programs
1. Write a program (source code) using vi editor and save it with .c extension. Ex: $vi
sample.c
2. Run the compiler to convert a program into to “binary” code. Ex: $cc sample.c
3. Compiler gives errors and warnings if any, then edit the source file, fix it, and re-
compile.
4. . Run it and see the output. Ex: $ ./a.out
Structure of C Program

Example

Preprocessor Directives
⮚ The preprocessor directives provide instructions to the preprocessor, to include
functions from the system library, to define the symbolic constants and macro.
⮚ The preprocessor command always starts with symbol #. Example: #include<stdio.h>
⮚ Header file contains a collection of library files.
⮚ #include<stdio.h> includes the information about the standard input/output library.
⮚ The variables that are used in common by more than one function are called Global
Variables and are declared in global declaration section.
⮚ Every C program must have one main () function. All the statements of main are
enclosed in braces.
⮚ The program execution begins at main () function and ends at closing brace of the main
function.
⮚ C program can have any number of user-defined functions and they are generally placed
immediately after the main () function, although they may appear in any order.
⮚ All sections except the main () function may be absent when they are not required.
⮚ In the previous program, main () function returns an integer value to the operating
system.
⮚ Each statement in C program must end with; specifies that the instruction is ended.
⮚ A function can be called by its name, followed by a parenthesized list of arguments and
ended with semicolon.
⮚ In previous program main () function calls printf () function. Example: printf (“Hello
World! \n”);
Comments
⮚ To make the program more readable use the comments.
1)Block Comment:
/* Write a program to add two integer numbers */
 Any characters between /* and */ are ignored by the compiler.
 Comments may appear anywhere in a program.
 /* and */ is used to comment the multiple lines of code which is ignored by the compiler.
 Nested block comments are invalid like /* /* */
2)Line Comment:
⮚ To comment a single line, use two slashes //
/* Write a program to add two integer numbers */
#include<stdio.h> // It includes input, output header file
main ()
{
int a=10, b=20, c; // Variables declaration & initialization
c=a+b; // Adding two numbers
printf (“Sum of a and b=%d”, c);
return 0;
}

C Tokens:
In a passage of text, individual words and punctuation marks are called as tokens.
The compiler splits the program into individual units, are known as C tokens. C has six types of
tokens.

Character Set
⮚ Characters are used to form words, numbers and expressions.
⮚ Characters are categorized as
1)Letters 2) Digits 3) Special characters 4) White spaces.
Letters: (Upper Case and Lower Case)
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
Digits: 0123456789
Special Characters: ’"()*+-/:= !&$;<>%?,. ˆ#@˜‘{}[]\|
White Spaces: Blank Space, Horizontal Space, Carriage Return.
Identifiers
⮚ Identifiers are names given to various programming elements such as variables,
constants, and functions.
⮚ It should start with an alphabet or underscore, followed by the combinations of
alphabets and digits. ex: a=10 or _a=10valid, 1a=10 0r $a=10 invalid
⮚ No special character is allowed except underscore.
⮚ An Identifier can be of arbitrarily long. Some implementation of C recognizes only the
first 8 characters and some other recognize first 32 Characters.
The following are the rules for writing identifiers in C:
⮚ First character must be alphabetic character or underscore.
⮚ Must consist only of alphabetic characters, digits, or underscore.
⮚ Should not contain any special character, or white spaces. ex sum of invalid,
sum_ofvalid
⮚ Should not be C keywords.
⮚ Case matters (that is, upper and lowercase letters). Thus, the names count and Count
refer to two different identifiers. Because C is case sensitive.
Variables
Variable is a valid identifier which is used to store the value in the memory location, that
value varies during the program execution
⮚ When you create variables, the declaration gives them a symbolic name and the definition
reserves memory for them.
⮚ A variable’s type can be any of the data types, such as character, integer or real except
void.
⮚ C allows multiple variables of the same type to be defined in one statement. Example:
int a, b;
⮚ There are some restrictions on the variable names (same as identifiers):
Types of variables:
⮚ Global Variables: The variables which are declared at the starting of the
program are called as global variable. They are visible to all the parts of
the program.
⮚ Local Variables: The variables which are declared in a function are called
local variables to that function. These variables visible only within the
function
⮚ Variable declaration and definition:
⮚ Example: int a; a Variable name

23456 Garbage value


Address of the variable
1000
Variable initialization:
datatype identifier = initial value;
Examples: 1) int a=10; 2) float b=2.1; 3) float pi=3.14; 4) char ch=‘A’;

#include<stdio.h>

main ()

int a=10, b=20, c;

c=a+b;

Constants
printf (“sum of a and b=%d\n”, c);

⮚ Constants
return 0; are data values that cannot be changed during the program execution.

} ⮚ Like variables, constants have a type.

Types of constants:
⮚ Character constants
1)Single character constants 2) string constants.
⮚ Numeric constants.
1)integer constant 2) real constants.
Type qualifier const
⮚ One way to use the constant is with memory constants. Memory constants use a C type
qualifier; const. This indicates that the data cannot be changed.
const type identifier= value;
const float pi=3.14;

#include<stdio.h>
void main ()
{
float area, radius=3.0;
const float pi=3.14;
area=pi*radius*radius;
printf (“area of a circle= %f”, area);
}

Single character constants


⮚ A single character constant are enclosed in single quotes.
Example: ‘1’ ‘X’ ‘%’ ‘‘
⮚ Character constants have integer values called ASCII values.
char ch=‘A’;
printf (“%d”, ch); Output: 65
similarly, printf(“%c”,65); Output =A

String constants
⮚ String is a collection of characters or sequence of characters enclosed in double
quotes.
⮚ The characters may be letters, numbers, special characters and blank space.
Example: “snist” “2011” “A”.
Backslash \escape characters

⮚ Backslash characters are used in output functions.


⮚ These backslash characters are preceded with the \

symbol .

Numeric Constants
integer constant: It is a sequence of digits that consists numbers from 0to 9.
Example: 23 -678 0 +78
Rules:
1. integer constant have at least one digit.
2. No decimal points.
3. No commas or blanks are allowed.
4. The allowable range for integer constant is -32768 to 32767.
To store the larger integer constants on 16-bit machine use the qualifiers such as U, L, UL.
Real constants: The numbers containing fractional parts like 3.14
Example:1.9099 -0.89 +3.14
Real constants are also expressed in exponential notation.Mantissa e exponent
⮚ A number is written as the combination of the mantissa, which is followed by
the prefix e or E, and the exponent.
Example: 87000000 = 8.7e7
- 550 = -5.5e2
0.00000000031 = 3.1e-10
Examples of real constants

Coding Constants: Different ways to create constants.


Literal constants: A literal is an unnamed constant used to specify data. Example: a = b + 5;
Defined constants: By using the preprocessor command you can create a constant.
Example: #define pi 3.14
Memory constants:
Memory constants use a C type qualifier, const, to indicate that the data cannot be changed.
Its format is: const type identifier = value; Example: const float PI = 3.14159;
Key Words
⮚ C word is classified as either keywords or identifiers.
⮚ Keywords have fixed meanings, these meanings cannot be changed.
⮚ Keywords must be in lowercase.
Key Words in C

Data types in C
⮚ Data types are used to indicate the type of value represented or stored in a variable, the
number of bytes to be reserved in memory, the range of values that can be represented in
memory, and the type of operation that can be performed on a particular data value.
⮚ ANSI C supports 3 categories of data types:
1)Built-in data types 2) Derived data types 3) User Defined data types
Built-in data types:
Built-in data types are also known as primitive data types. C uses the following
primitive data types.
int integer quantity
char character (stores a single character)
float floating point number
double floating-point number
Integer data type:
⮚ An integer number (also called whole number) has no fractional part or decimal point.
⮚ The keyword int is used to specify an integer variable.
⮚ It occupies 2 bytes (16 bits) or 4 bytes (32 bits), depending on the machine architecture.
⮚ 16-bit integer can have values in the range of -32768 to 32767
⮚ One bit is used for sign.
void data type:
⮚ Defines an empty data type which can then be associated with some data types. It is
useful with pointers.

Note: sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long)
Character Data Type:
⮚ The shortest data type is character.
⮚ The keyword char is used to declare a variable of a character type.
⮚ It is stored in 1 byte in memory.
⮚ Corresponding integer values for all characters are defined in ASCII (American Standard
Code for Information Interchange).
⮚ Example: character constant ‘a’ has an int value 97, ‘b’ has 98, ‘A’ has 65 etc.
⮚ Character can have values in the range of -128 to 127.
Float datatype:
⮚ The keyword float is used to declare a variable of the type float.
⮚ The float type variable is usually stored in 32 bits, with 6 digits of precision.
⮚ A float variable can have values in the range of 3.4E-38 to 3.4 E+38.
double data type:
⮚ A floating point number can also be represented by the double data type.
⮚ The data type double is stored on most machines in 64 bits which is about 15 decimal
places of accuracy.
⮚ To declare a variable of the type double, use the keyword double.
⮚ A double variable can have values in the range of 1.7E-308 to +1.7E+308.

Note: sizeof (float) ≤ sizeof (double) ≤ sizeof (long double)

Type Modifiers:
⮚ The basic data types may have various modifiers (or qualifiers) preceding them, except
type ‘void’.
⮚ A modifier is used to alter the meaning of the base data type to fit the needs of various
situations more precisely.
⮚ The modifiers signed, unsigned, long, short may be applied to integer base types.
⮚ The modifiers unsigned and signed may be applied to characters.
⮚ The modifier long may also be applied to double.
⮚ The difference between signed and unsigned integers is in the way high-order bit (sign
bit) of the integer is interpreted.
⮚ If sign bit is 0, then the number is positive; if it is 1, then the number is negative.
Derived data types and User defined data types are the combination
of primitive data types. They are used to represent a collection of data.
They are: 1) Arrays 2) Pointers 3) Structures 4) Unions 5) Enumeration
Note: Number of bytes and range given to each data type is platform
dependent.

Data types in c
Formatted input/output
⮚ The data is to be arranged in a particular format. The data is input to and output from a
stream.
⮚ A stream is a source or destination of the data, it is associated with a physical device such
as terminals (keyboard, monitor).
⮚ C has two forms of streams: Text Stream and Binary Stream.
⮚ Text Stream consists of sequence of characters.
⮚ Binary Stream consists of a sequence of data in 0’s and 1’s.
⮚ A terminal keyboard and monitor can be associated only with a text stream.
⮚ A keyboard is a source for a text stream; a monitor is a destination for a text stream.
⮚ The data is formatted using the printf and scanf functions.
⮚ scanf () converts the text stream coming from the keyboard to data values (char, int, etc.,)
and stores them in the program variables.
⮚ printf () converts the data stored in variables into the text stream for output the keyboard.
printf () takes the set of data values and converts them to text stream using formatting
instructions contained in a format control string.

⮚ Format specifier specifies the data values type, size and display position.
⮚ Printf statement takes two arguments
1. Control String and
2. Data Values (Variables)
⮚ Control string contains the format specifiers and some text.
Syntax: printf (“control string”, var1, var2…, varn);
Example: int a=10, b=20;
printf (“a=%d b=%d”, a,b);
scanf(“control string”,&var1,&var2.. &varn);
⮚ control string includes format specifiers and specifies the field width.
⮚ scanf requires variable addresses in the address list.
Operators
⮚ C supports a rich set of operators.
⮚ An operator is a symbol that tells the computer to perform mathematical or logical
operations.
Operators are used in C to operate on data and variables.

expressio
Operators: Operands: x, y, z
X=Y+Z =, +

⮚ Unary operators are used on a single operand (- -, +, ++, --)


⮚ Binary operators are used to apply in between two operands (+, -, /,*, %)
⮚ Conditional (or ternary) operator can be applied on three operands. ( ?: )
Types of Operators
C operators can be classified into a number of categories.
They include:
⮚ Arithmetic Operators
⮚ Relational Operators
⮚ Logical Operators
⮚ Assignment Operator
⮚ Increment and Decrement Operators
⮚ Conditional Operators
⮚ Bitwise Operators
⮚ Special Operators
Arithmetic Operators

Syntax: operand1 arithmetic operator operand2


Examples:
10 + 10 = 20 (addition on integer numbers)
10.0 + 10.0 = 20.0 (addition on real numbers)
10 + 10.0 = 20.0 (mixed mode)
14 / 3 = 4 (ignores fractional part)

Relational Operators:
⮚ Relational operators are used to compare the relationship between two operands.
Syntax: exp1 relational operator exp2
⮚ The value of a relational expression is either one or zero.
⮚ It is one if the specified relation is true and zero if the relation is false.
⮚ Relational operators are used by if, while and for statements.

Logical Operators
⮚ Logical operators used to test more than one condition and make decision. Yields a value
either one or zero.
⮚ Syntax: operand1 logical operator operand2 or
logical operator operand
⮚ Example: (x<y) && (x= = 8)
Assignment Operators
⮚ Assignment operators are used to assign the result of an expression to a variable.
⮚ Assignment Operator is =
Syntax: variable = expression;
⮚ Types of assignment:
– Single Assignment Ex: a = 10;
– Multiple Assignment Ex: a=b=c=0;
– Compound Assignment Ex: c = a + b;

Increment and Decrement Operators


⮚ We can add or subtract 1 to or from variables by using increment (++) and decrement
(--) operators.
⮚ The operator ++ adds 1 to the operand and the operator – – subtracts 1.
⮚ They can apply in two ways: postfix and prefix.
⮚ Syntax: increment or decrement operator operand
operand increment or decrement operator
⮚ Prefix form: Variable is changed before expression is evaluated
⮚ Postfix form: Variable is changed after expression is evaluated.
Conditional (ternary)Operators (?: )
⮚ C’s only conditional (or ternary) operator requires three operands.
Syntax: conditional expression? expression1: expression2;
⮚ The conditional expression is any expression that results in a true
(nonzero) or false (zero).
⮚ If the result is true then expression1 executes, otherwise expression2 executes.
Example: a=1; b=2;
x = (a<b)? a: b;
This is like-- if(a<b)
x=a;
else
x=b;
Bitwise Operators
⮚ C has a special operator known as Bitwise operator for manipulation of data at bit level.
⮚ Bitwise operator may not be applied for float and double.
⮚ Manipulates the data which is in binary form.
Syntax: operand1 bitwise operator operand2
⮚ Examples:
 & Bitwise AND 0110 & 0011 🡺 0010
 | Bitwise OR 0110 | 0011 🡺 0111
 ^ Bitwise XOR 0110 ^ 0011 🡺 0101
 << Left shift 01101110 << 2 🡺 10111000
 >> Right shift 01101110 >> 3 🡺 00001101
 ~ One's complement ~0011 🡺 1100
⮚ Don't confuse bitwise & | with logical && ||
 >> is a binary operator that requires two integral operands. the first one is value to
be shifted, the second one specifies number of bits to be shifted.
⮚ The general form is as follows:
variable >> expression;
⮚ When bits are shifted right, the bits at the rightmost end are deleted.
⮚ Shift right operator divides by a power of 2. I.e., a>>n results in a/2n, where n is number
of bits to be shifted.
Example: a=8;
 << is a binary operator that requires two integral operands. the first one is value to
be shifted, the second one specifies number of bits to be shifted.
⮚ The general form is as follows:
variable << expression;
⮚ When bits are shifted left, the bits at the leftmost end are deleted.
Example: a=8;
b=a<<1; // assigns 16 after left shift
operation
⮚ Shift left operator multiply by a power of 2, a<<n results in a*2n, where n is number of
bits to be shifted.

Special Operators
⮚ C supports the following special category of operators.
& Address operator
* Indirection operator
, Comma operator
sizeof () Size of operator
. and 🡪 Member selection Operators
comma operator:
⮚ It doesn’t operate on data but allows more than one expression to appear on the same
line.
Example: int i = 10, j = 20;
printf (%d %.2f %c”, a, f, c);
j = (i = 12, i + 8); //i is assigned 12 added to 8 produces 20
sizeof Operator:
⮚ It is a unary operator (operates on a single value).
⮚ Produces a result that represent the size in bytes.
Syntax: sizeof(datatype);

Example: int a = 5;
sizeof (a); //produces 2
sizeof(char); // produces 1
sizeof(int); // produces 2
Precedence and Association rules among operators
⮚ Precedence is used to determine the order in which different operators in a complex
expression are evaluated.
⮚ Associativity is used to determine the order in which operators with the same precedence
are valuated in a complex expression.
⮚ Every operator has a precedence.
⮚ The operators which has higher precedence in the expression is
evaluated first.
Example: a=8+4*2; a=?

Precedence and Associativity of Operators in C (from higher lower)


Example program to illustrate operator precedence
Post fix expression:
⮚ It is an expression which contains operand followed by one operator.
Example: a++; a- -;
⮚ The operand in a postfix expression must be a variable.
⮚ (a++) has the same effect as (a = a + 1)
⮚ If ++ is after the operand, as in a++, the increment takes place after the expression
is evaluated.

In the following figure:


1. Value of the variable a is assigned to x 2) Value of the a is
incremented by 1.

Result value of a: 4, Value of a++: 4 , New Value of a : 5


#include<stdio.h>
void main ()
{
a=10;
x=a++;
printf (“x=%d, a=%d”,x,a); output : x= 10
a= 11
}
Pre fix expression:
⮚ It is an expression which contains operator followed by an operand.
Example: ++a; - -a;
⮚ The operand of a prefix expression must be a variable.
⮚ (++a) has the same effect as (a = a + 1)
⮚ If ++ is before the operand, as in ++a, the increment takes place before the expression is
evaluated.

#include<stdio.h>
void main ()
{ Output: x=11, a=11
a=10;
x=++a;
printf (“x=%d, a=%d”, x, a);
}
Unary expression: It is an expression which consists of unary operator followed by the operand
Binary Expressions:
⮚ In binary expression operator must be placed in between the two operands.
⮚ Both operands of the modulo operator (%) must be integral types.
The left operand in an assignment expression must be a single variable.

Expansion of Compound Expressions


Evaluating Expressions
Type Conversion
⮚ Up to this point, we have assumed that all of our expressions involved data of the same
type.
⮚ But what happens when we write an expression that involves two different data types,
such as multiplying an integer and a floating-point number?
⮚ To perform these evaluations, one of the types must be converted.
⮚ Type Conversion: Conversion of one data type to another data type.
⮚ Type conversions are classified into:
1) Implicit Type Conversion 2) Explicit Type Conversion (Cast)
Implicit Conversion:
⮚ In implicit type conversion, if the operands of an expression are of different types, the
lower data type is automatically converted to the higher data type before the operation
evaluation.
⮚ The result of the expression will be of higher data type.
⮚ The final result of an expression is converted to the type of the variable on the LHS of
the assignment statement, before assigning the value to it.
⮚ Conversion during assignments:
char c = 'a';
int i;
i = c; /* i is assigned by the ascii of ‘a’ */
⮚ Arithmetic Conversion: If two operands of a binary operator are not the same type,
implicit conversion occurs:
int i = 5 , j = 1;
float x = 1.0, y;
y = x / i; /* y = 1.0 / 5.0 */
y = j / i; /* y = 1 / 5 so y = 0 */
Explicit Conversion or Type Casting:
⮚ In explicit type conversion, the user has to enforce the compiler to convert one data type
to another data type by using typecasting operator.
⮚ This method of typecasting is done by prefixing the variable name with the data type
enclosed within parenthesis. (data type) expression
⮚ Where (data type) can be any valid C data type and expression is any variable, constant
or a combination of both. Example: int x;
x=(int)7.5;

Conversion Rank (C Promotion Rules)


Statements

⮚ Compound statements are used to group the statements into a single executable unit.
⮚ It consists of one or more individual statements enclosed within the braces { }
Decision Control Structures
⮚ The decision is described to the computer as a conditional statement that can be answered
either true or false.
⮚ If the answer is true, one or more action statements are executed.
⮚ If the answer is false, then a different action or set of actions is executed.
Types of decision control structures:
1) If 2) if..else 3) nested if…else 4) else if ladder
5) dangling else 6) switch statement
Decision Control Statement: if
The general form of a simple if statement is:

if (condition)

statement-block;

Following are the properties of an if statement:


⮚ If the condition is true then the statement-block will be executed.
⮚ If the condition is false it does not do anything ( or the statement is skipped)
⮚ The condition is given in parentheses and must be evaluated as true (nonzero value)
or false (zero value).
⮚ If a compound statement is provided, it must be enclosed in opening and closing
braces.
Flow Chart

Enter Example:

main ()

{
F
Conditi int a=10, b=20;
on
if(a>b)
T {

Body of the IF Statement printf(“%d”,a);

printf(“%d”,b);

Exit }
Decision Control Statement: if..else

Syntactical Rules for if…else Statements


⮚ The expression or condition which is followed by if statement must be enclosed in
parenthesis.
⮚ No semicolon is needed for an if…else statement.
⮚ Both the true and false statements can be any statement (even another if…else).
⮚ Multiple statements under if and else should be enclosed between curly braces.
⮚ No need to enclose a single statement in curly braces.
⮚ Decision Control Statement: if..else
Decision Control Statement: nested if…else
#include <stdio.h>
void main()
{
int a=10,b=20,c=30;
if(a>b) {
if(a>c)
printf(“a is greatest”);
else
printf(“c is greatest”);
}
else {
If(b>c)
printf(“b is greatest “);
else
printf(“c is greatest”);
}
}
else if ladder

if (condition1)

statements1;

else if (condition2)

statements2;

else if (condition3)

statements3;

else if (condition4)

statements4;

……

else if (condition n)

statements n;

else

default statement;

statement x;

⮚ The conditions are evaluated from the top to down.


⮚ As soon as a true condition is found the statement associated with it is executed
and the control is transferred to the statement x by skipping the rest of the ladder.
⮚ When all n conditions become false, final else containing default statement
that will be executed.
Example program for else if
main ()
{
float m1, m2, m3, m4;
float perc;
printf (“enter marks\n”);
scanf (“%f%f%f%f”, &m1,&m2,&m3,&m4);
perc=(m1+m2+m3+m4)/4;
if(perc>=75)
printf(“\nDistinction”);
else if (per<75 && per>=60)
printf (“\nFirst Class”);
else if (per<60 && per>=50)
printf(“\nSecond Class”);
else if(per<50 && per>=40)
printf(“\nThird Class”);
else
printf(“\nFail”);
}//main

Dangling else
To avoid dangling else problem place the inner if statement with in the curly braces.

⮚ A simple if…else can be represented using the conditional (ternary)


expression.
Example program for nested if…else
main () {
float m1, m2, m3, m4;
float perc;
printf (“Enter marks\n”);
scanf (“%f%f%f%f”, &m1, &m2, &m3, &m4);
perc=(m1+m2+m3+m4)/4;
if(perc>=75)
printf(“\nDistinction”);
else {
if (per<75 && per>=60)
printf (“\nFirst Class”);
else {
if (per<60 && per>=50)
printf (“\nSecond Class”);
else {
if (per<50 && per>=40)
printf (“\nThird Class”);
else
printf(“\nFail”);
}//else
}//else
}//else
}//main
Switch case
⮚ It is a multi-way conditional statement generalizing the if…else statement.
⮚ It is a conditional control statement that allows some particular group of statements to be
chosen from several available groups.
⮚ A switch statement allows a single variable to be compared with several possible case
labels, which are represented by constant values.
⮚ If the variable matches with one of the constants, then an execution jump is made to that
point.
⮚ A case label cannot appear more than once and there can only be one default expression.
⮚ Note: switch statement does not allow less than (<), greater than (>).
⮚ ONLY the equality operator (==) is used with a switch statement.
⮚ The control variable must be integral (int or char) only.
⮚ When the switch statement is encountered, the control variable is evaluated.
⮚ Then, if that evaluated value is equal to any of the values specified in a case clause, the
statements immediately following the colon (“:”) begin to run.
⮚ Default case is optional and if specified, default statements will be executed, if there is no
match for the case labels.
⮚ Once the program flow enters a case label, the statements associated with case have been
executed, the program flow continues with the statement for the next case. (If there is no
break statement after case label.)
⮚ The following results are possible, depending on the value of print Flag.
⮚ If print Flag is 1, then all three printf statements are executed.
⮚ If printFlag is 2, then the first print statement is skipped and the last two are executed.
⮚ Finally, if printFlag is neither 1 nor 2, then only the statement defined by the default is
executed

general format of switch:

Example1
⮚ If you want to execute only one case-label, C provides break statement.
⮚ It causes the program to jump out of the switch statement, that is go to the closing
braces (}) and continues the remaining code of the program.
⮚ If we add break to the last statement of the case, the general form of switch case is
as follows:
Example2 for switch statement:

Concept of a loop
⮚ The real power of computers is in their ability to repeat an operation or a series of
operations many times.
⮚ This repetition, called looping, is one of the basic structured programming concepts.
⮚ Each loop must have an expression that determines if the loop is done.
⮚ If it is not done, the loop repeats one more time; if it is done, the loop terminates.

Pretest and Post-test Loops


⮚ We need to test for the end of a loop, but where should we check it—before or after each
iteration? We can have either a pre- or a post-test terminating condition.
⮚ In a pretest loop, the condition is checked at the beginning of each iteration.
⮚ In a post-test loop, the condition is checked at the end of each iteration.
Pretest Loop
⮚ In each iteration, the control expression is tested first. If it is true, the loop continues;
otherwise, the loop is terminated. Example: while loop, for loop
Post-test Loop
⮚ In each iteration, the loop action(s) are executed. Then the control expression is tested. If
it is true, a new iteration is started; otherwise, the loop terminates ex: do -while loop

While loop
⮚ The "while" loop is a generalized looping structure that employs a variable or expression
for testing the condition.
⮚ It is a repetition statement that allows an action to be repeated while some conditions
remain true.
⮚ The body of while statement can be a single statement or compound statements.
⮚ It doesn’t perform even a single operation if condition fails.

Example 1: To print 1 to 10 natural numbers


#include<stdio.h>
void main ()
{
int i; output:1
i=1; 2
while (i<=10) { till 10 it prints
printf(“%d\n”,i);
i++;
}
}

Example 2: To print the reverse of the given number.

#include<stdio.h>

void main ()

int n, rem, rev = 0;

printf ("\n Enter a positive number: ");

scanf("%d",&n);

while (n! = 0)
do while
⮚ The “do while" loop is a repetition statement that allows an action to be done at least
once and then condition is tested.
⮚ On reaching do statement, the program proceeds to evaluate the body of the loop first.
⮚ At the end of the loop, condition statement is evaluated.
⮚ If the condition is true, it evaluates the body of the loop once again.
⮚ This process continues up to the condition becomes false.
Example 3: To print Fibonacci sequence for the given number.

#include<stdio.h>

void main ()

int a=0, b=1, c, i;

i=1;

printf ("%d%d”, a, b);

do

c=a+b;

i++;

printf ("%3d”, c);

a=b;

b=c;multiplication table for 5.


Example 4: To print

#include} <stdio.h>
while(i<=10);

}void main ()

int i = 1, n=5;

do

printf (“ %d * %d = %d “, n, i, n*i);

i = i + 1;
} while ( i<= 5);

//Program to print 5 4 3 2 1 using while and do…while


for
⮚ A for loop is used when a loop is to be executed a known number of times.
⮚ We can do the same thing with a while loop, but the for loop is easier to read and more
natural for counting loops.
General form of the for is:
for( initialization; test-condition; updation)
{
Body of the loop
}
A Simple Nested for Loop

We can write the for loop in the following ways:


Option 1:
for (k= 1; k< = 10 ;)
{
printf (“%d”, k);
k = k + 1;
}
Here the increment is done within the body of the for loop and not in
the for statement. Note that the semicolon after the condition is
necessary.
Option 2:
int k = 1;
for (; k< = 10; k++);
{
printf (“, k);
}
Here the initialization is done in the declaration statement itself, but
still the semicolon before the condition is necessary.
Option 3: The infinite loop
One of the most interesting uses of the for loop is the creation of the infinite loop. Since none of
the three expressions that form the for loop are required, it is possible to make an endless loop by
leaving the conditional expression empty.
For example: for (; ;)
printf (“The loop will run forever\n”);
Actually, the for (; ;) construct does not necessarily create an infinite loop because C’s break
statement, when encountered anywhere inside the body of a loop, causes immediate termination
of the loop.
Program control then picks up the code following the loop, as shown here:
for (; ;)
{
ch = getchar (); /* get a character */
if (ch = = ‘A’)
break;
}
printf (“you typed an A”);
This loop will run until A is typed at the keyboard
Option 3: For loop with no body
A statement, as defined by the C syntax, may be empty.
This means that the body of the for may also be empty.
This fact can be used to improve the efficiency of certain algorithms as well as to create time
delay loops.
The following statement shows how to create a time delay loop using a for loop:
for (t = 0; t < SOME _VALUE; t++);

break
⮚ When a break statement is enclosed inside a block or loop, the loop is immediately
exited and program continues with the next statement immediately following the loop.
⮚ When loop are nested break only exit from the inner loop containing it.
The format of the break statement is:

Example 6: Program to demonstrate break statement.


#include<stdio.h>
void main ()
{
int i;
i=1;
while(i<=10)
{
if(i==8)
break;
printf(“%d\t”,i); output :1 2 3 4 5 6 7
i=i+1;
}
printf (“\n Thanking You”); Thanking you
}

continue
⮚ When a continue statement is enclosed inside a block or loop, the loop is
to be continued with the next iteration.
⮚ The continue statement tells the compiler, skip the following statements
and continue with the next iteration.
⮚ The format of the continue statement is:
Example 5: Program to demonstrate continue statement.
#include<stdio.h>
void main ()
{
int i;
for (i=1; i<=5; i++)
{
if (i = = 3)
continue;
printf (" %d”, i); output: 1 2 4 5
}
}

ARRAY

 Array is the collection of similar data types or collection of similar entity stored in
contiguous memory location. Array of character is a string. Each data item of an array is
called an element. And each element is unique and located in separated memory location.
Each of elements of an array share a variable but each element having different index no.
known as subscript.
 An array can be a single dimensional or multi-dimensional and number of subscripts
determines its dimension. And number of subscripts is always starts with zero. One
dimensional array is known as vector and two-dimensional arrays are known as matrix.

ADVANTAGES: array variable can store more than one value at a time where
other variable can store one value at a time.
Example: int a[100];
One Dimensional Arrays:
 One dimensional array is a linear list consisting of related and similar data items.
 In memory all the data items are stored in contiguous memory locations one after the
other.
Syntax for declaring One Dimensional Arrays:
elementType arrayName[size];
 To declare an array, we just add an array size.
Example: int temp [5]; //Creates an array of 5 integer elements.
Example: double stockprice [31];
//Creates an array of 31 double elements.
Total size in byte for 1D array is:
Total bytes=size of (data type) * size of array.
Example: if an array declared is:
int [20];
Total byte= 2 * 20 =40 byte.
Initializing One Dimensional Arrays
Option 1: Initializing all memory locations:
 If you know all the data at compile time, you can specify all your data within brackets:
int temp [5] = {75, 79, 82, 70, 68};
 During compilation, 5 contiguous memory locations are reserved by the compiler for the
variable temp and all these locations are initialized as
shown below.
 If the size of integer is 2 bytes, 10 bytes will be allocated for the variable temp.
Option 2: Initialization without size:
 If you omit the size of an array, but specify an initial set of data, then the
compiler will automatically determine the size of an array.
int temp [] = {75, 79, 82, 70, 68};
Option 3 Partial Array Initialization:
 If the number of values to be initialized is less than the size of the array, then the
elements are initialized in the order from 0th location.
 The remaining locations will be initialized to zero automatically.
int temp [5] = {75, 79, 82};

Option 4: Initializing an entire array with zero:


 If you do not know any data ahead of time, but you want to initialize everything to 0, just
use 0 within { }. For example: int temp [5] = {0};
 This will initialize every element within the array to 0 as shown below.
ACCESSING OF ARRAY ELEMENT:
/*Write a program to input values into an array and display them*/
#include<stdio.h>
int main ()
{
int arr [5],i;
for (i=0; i<5; i++)
{
printf (“enter a value for arr[%d] \n”, i);
scanf (“%d”, &arr[i]);
}
printf (“the array elements are: \n”);
for (i=0; i<5; i++)
{
printf(“%d\t”,arr[i]);
}
return 0;
}
OUTPUT:
Enter a value for arr [0] = 12
Enter a value for arr [1] =45
Enter a value for arr[2] =59
Enter a value for arr [3] =98
Enter a value for arr [4] =21
The array elements are 12 45 59 98 21
Example: From the above example value stored in an array are and occupy its
memory addresses 2000, 2002, 2004, 2006, 2008 respectively.
a [0] =12, a [1] =45, a [2] =59, a [3] =98, a [4] =21
a [0] a [1] a [2] a [3] a [4]
12 45 59 98 21

2000 2002 2004 2006 2008


//Program to calculate sum of all the array elements.
#include <stdio.h>
void main ()
{
int a [10];
int i, size, total=0;
printf ("\n Enter the size of the array: ");
scanf ("%d", &size);
printf ("\n Enter the elements of an array: ");
for (i = 0; i < size; i++)
scanf ("%d”, &a[i]);
for (i = 0; i < size; i++)
total += a[i];
printf (“Sum of all array elements: %d", total);
}
Single dimensional arrays and functions
/*program to pass array elements to a function*/
#include<stdio.h>
void main ()
{
int arr [10], i;
printf (“enter the array elements\n”);
for (i=0; i<10; i++)
{
scanf (“%d”, &arr[i]);
check(arr[i]);
}
}
void check (int num)
{
if(num%2=0)
{
printf (” %d is even \n”, num);
}
else
{
printf (” %d is odd \n”, num);
}
}
Two dimensional arrays
Two-dimensional array is known as matrix. The array declaration in both the array
i.e.in single dimensional array single subscript is used and in two dimensional
array two subscripts are is used.
Its syntax is Data-type array name[row][column];
Initialization of Two-Dimensional Arrays:
 An array may be initialized at the time of declaration as follows:
char names [3][4] = {
{‘J’, 'o', 'h', 'n'},
{‘M’, 'a', 'r', 'y'},
{‘I’, 'v', 'a', 'n'}
};
 An integer array may be initialized to all zeros as follows
int nums [3][4] = {0};
 An integer array may be initialized to different values as follows
int nums [3][4] = {
{1,2,3,4},
{5,6,7,8},
{9,0,10,11}
};
 To access an element of a 2D array, you need to specify both the row
and the column:
printf ("%d", nums [1][2]);
Example:
int c [2][3] = {
{1,3,0},
{-1,5,9}
};

OR
int c [][3] = {
{1,3,0},
{-1,5,9}
};
OR

int c [2][3] = {1,3,0, -1,5,9};


//Program to print sum of elements of a matrix.
#define M 3 /* Number of rows */
#define N 4 /* Number of columns */
main () {
, int a [ M] [ N], i, j, sum = 0;
for (i = 0; i < M; ++i) {
for (j = 0; j < N, ++j) {
scanf (%d”, &a [i] [j]);
}
}
for (i = 0; i < M; ++i) {
for (j = 0; j < N, ++j) {
printf (“a [ %d] [ %d] = %d “, i, j, a [ i] [ j]);}
printf (“\n”);
}
for (i = 0; i < M; ++i) {
for (j = 0; j < N, ++j) {
sum += a [ i] [ j];
}
printf(“\nsum = %d\n\n”);
}
}
Multi-Dimensional Arrays:
 C allows three or more dimensions. The exact limit is determined by the compile.
 The general form of multidimensional array is element Type array Name [s1] [s2] [s3]
…[sm];
 Where si is the size of the ith dimension. Array declarations read right-to-left
 For Example: int a [3][5][4];
 It is represented as “an array of ten arrays of three arrays of two ints”
 In memory the elements are stored as shown in below figure.
Inter-function communication (Functions with Arrays):
 Like the values of variable, it is also possible to pass values of an array to a function.
 There are two types of passing an array to the function:
1. Passing Individual Elements 2. Passing the whole array
1. Passing Individual Elements:

int a; int a [10];


fun(a); fun (a [3]);

void fun (int x)

-------

-------

2. Passing the whole array:


 To pass an array to a called function, it is sufficient to list the name of the array, without
any subscripts, and the size of the array as arguments.
 For example, the function call findMax (a, n); will pass all the elements contained in the
array a of size n.
 The called function expecting this must be appropriately defined.
 The findMax function header looks like: int findMax (int x [], int size)
 The pair of brackets informs the compiler that the argument x is an array of numbers. It
is not necessary to specify the size of the array here.
 The function prototype takes of the form
int findMax (int [], int);
int findMax (int a [], int);

//Program to read an array of elements and find


max value.

#include<stdio.h> int findMax (int x [], int size)

int findMax (int [], int); {

void main () int temp;

{ temp=x [0];

int a [10], n, i, max; for (i=1; i<size; i++)

printf (“\n Enter the size of the array “); {

scanf (“%d”, &n); if(x[i]>temp)

printf (‘\n Enter the elements of the array: “); {

for (i=0; i<n;i++) temp=x[i];

scanf (“%d”, &a[i]); }

max=findMax (a, n); }

printf (“\n The Maximum value =%d”, max); return temp;

} }
Character Arrays and Strings:
 String is a sequence of characters.
 If ‘\0’ is present after a series of characters in an array, then that array becomes a string
otherwise it is a character array.
Example:
char arr[] = {'a', 'b', 'c'}; //This is an array
char arr [] = {'a', 'b', 'c', '\0'}; //This is a string
Ragged Arrays
Each row in a two-dimensional array is itself an array. So, the rows can
have different lengths. Such an array is known as a ragged array.
For example,
int [][] matrix = {
{1, 2, 3, 4, 5},
{2, 3, 4, 5},
{3, 4, 5},
{4, 5},
{5}
};
Searching and Sorting
 Searching is the process of finding a particular element in an array.
 Sorting is the process of rearranging the elements in an array so that they are stored in
some well-defined order.
Linear Search:
A linear or sequential search of an array begins at the beginning of the array and
continues until the item is found or the entire array has been searched.
1)It is the basic searching technique 2) Very easy to implement
3)The array DOESN’T have to be sorted 4) Could be very slow.
5) All array elements must be visited if the search fails.
//Program to find a number in the array using sequential search.
main () {
int a [10], i, n, m, c=0;
printf ("Enter the size of an array: ");
scanf ("%d”, &n);
printf ("Enter the elements of the array: ");
for (i=0; i<=n-1; i++) {
scanf ("%d”, &a[i]);
}
printf ("Enter the number to be search: ");
scanf ("%d”, &m);
for (i=0; i<=n-1; i++) {
if(a[i]==m) {
c=1; Output:

break; Enter the size of an array: 5

} Enter the elements of the array: 4 6 8 0 3

} Enter the number to be search: 0

The number is found


if(c==0)
printf ("The number is not in the list");
else
printf ("The number is found");
}
Binary Search: The search starts at the center of a sorted array, if center is equal to target
element search is successful otherwise it determines which half to continue to search on that
basis.
 The algorithm starts searching with the mid element. mid= (first + last)/2
 If the item is equal to mid then search is successful.
 If the item is less than the mid element, it starts over searching the first half of the list.
 If the item is greater than the mid element, it starts over searching the second half of the
list. It then continues halving the list until the item is found.
 Each iteration eliminates half of the remaining elements.
 It is faster than the linear search.
 It works only on SORTED array.
 Thus, there is a performance penalty for sorting the array.
/* C program that use recursive function to perform the Binary Search for a Key value in a
given list of integers*/
#include <stdio.h> #define SIZE 8
int binary search (int list [], int low, int high, int target);
void main () {
int list [SIZE], target, index, i;
printf ("Enter %d elements in ascending or descending order: “, SIZE);
for (i=0; i<SIZE; i++)
scanf ("%d”, &list[i]);
printf ("Enter an element that is to be searched: ");
scanf ("%d", &target);
index = binary search (list, 0, SIZE-1, target);
if (index! = -1)
printf ("\nTarget was found at index: %d ", index);
else
printf ("Sorry, target item was not found");
getch ();
}
int binary search (int list [], int low, int high, int target) {
int middle;
if (low > high)
return -1;
middle = (low + high)/2;
if (list[middle] == target)
return (middle);
else
if (list[middle] < target)
return binary search (list, middle+1, high, target);
else
return binary search (list, low, middle-1, target);
}
Bubble Sort Algorithm
 The idea of Bubble (or exchange) sort is to scan through the list and swap each pair of
adjacent elements that are in the wrong order.
 The process is repeated each time from index zero to one less than the previous limit until
either the list is exhausted or until a pass that involve no swap is encountered.
 At the end of first pass, the largest element will move (or bubble up) to the end of the list.
 At the end of the second swap, the second largest will move to its right place, etc.
Suppose the following numbers are stored in an array: 32,51,27,85,66,23,13,57

Pass-1

32 51 27 85 66 23 13 57
no swap

32 27 51 85 66 23 13 57

32 27 51 85 66 23 13 57
no swap

32 27 51 66 85 23 13 57

32 27 51 66 23 85 13 57

32 27 51 66 23 13 85 57

32 27 51 66 23 13 57 85

Pass-2

27 32 51 66 23 13 57 85

27 32 51 66 23 13 57 85
no swap

27 32 51 66 23 13 57 85
no swap

27 32 51 23 66 13 57 85

27 32 51 23 13 66 57 85

27 32 51 23 13 57 66 85
//C program to sort the numbers using bubble sort
main() {
int arr[50],temp,i,j,n;
printf("\nEnter any Value less Than 50:");
scanf("%d",&n);
printf("\n\tEnter The Values into ARRAY: ");
Output:
for(i=0;i<n;i++)
scanf("%d",&arr[i]); Enter any Value less Than 50: 5
for(i=1;i<n;i++) {
Enter The Values into ARRAY: 1 5 0 3 2
for(j=0;j<n-i;j++) {
if(arr[j] >arr[j+1]) { Sorted Series: 0 1 2 3 5
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf(“\nSorted Series:");
for(i=0;i<n;i++) {
printf("\n %d",arr[i]);
}
}
Selection Sort
Procedure:
 Selection sort involved scanning through the list to find (or select) the smallest element
and swap it with the first element.
 The rest of the list is then search for the next smallest and swap it with the second
element.
 This process is repeated until the rest of the list reduces to one element, by which time the
list is sorted.
The following table shows how selection sort works.
Example:

Elements in the array before swapping: 77 33 44 55 88 66 22 11

pass-1 11 33 44 55 88 66 22 77

pass-2 11 22 44 55 88 66 33 77

pass-3 11 22 33 55 88 66 44 77

pass-4 11 22 33 44 88 66 55 77

pass-5 11 22 33 44 55 66 88 77

pass-6 11 22 33 44 55 66 88 77

pass-7 11 22 33 44 55 66 77 88

pass-8 11 22 33 44 55 66 77 88

Elements in the array before swapping: 11 22 33 44 55 66 77 88

/* Write a c program to implement the selection sort*/


#include<stdio.h>
void select_sort (int x [], int size); void selection_sort(int,int);
int n, size, a [10], i, j, x, k, pass, temp, min, loc;
void main () {
printf ("\nEnter the size of array: ");
scanf ("%d”, &n);
printf ("\nEnter the array elements: ");
for (i=0; i<n; i++)
scanf ("%d”, &a[i]);
printf ("\nElements in array before swapping: ");
for (i=0; i<n; i++)
printf ("\t%d”, a[i]);
printf("\n");
select_sort (a, n);
printf ("\n\n\tElements after swapping: ");
for (i=0; i<n; i++)
printf ("\t%d”, a[i]);
getch ();
int find_min (int x [], int k, int size)
}
{
void select_sort (int x [], int size)
min=x[k];
{
loc=k;
for (k=0; k<n; k++)
for (j=k+1; j<=size-1; j++)
{
{
loc = find_min (x, k, size);
if(min>x[j])
temp=x[k];
{
x[k]=x[loc];
min=x[j];
x[loc]=temp;
loc=j;
}
}
}
}

return loc;

}
Insertion Sort
Using insertion sort an element is inserted in correct location.
Procedure:
 Begin with a sequence of n elements in arbitrary order
 Initially assume the sorted segment contains the first element.
 Let x be the next element to be inserted in sorted segment, pull x “out of the
way”, leaving a vacancy.
 Repeatedly compare x to the element just to the left of the vacancy, and as long as
x is smaller, move that element into the vacancy, else put x in the vacancy.
 Repeat the next element that has not yet examined.

Example:
Elements in array before swapping: 77 33 44 11 88 22 66 55
pass-1 77 33 44 11 88 22 66 55
pass-2 33 77 44 11 88 22 66 55
pass-3 33 44 77 11 88 22 66 55
pass-4 11 33 44 77 88 22 66 55
pass-5 11 33 44 77 88 22 66 55
pass-6 11 22 33 44 77 88 66 55
pass-7 11 22 33 44 66 77 88 55
pass-8 11 22 33 44 55 66 77 88
Elements in array after sorting: 11 22 33 44 55 66 77 88

/*Write a program to implement the insertion sort*/


#include<stdio.h>
void insertionsort (int a [], int size); void insertionsort (int a [], int n)
void main () { {

int n, a [10], i, x; int k, j, temp, x;

printf ("\nEnter the size of array: "); for (k=0; k<n; k++)

scanf ("%d”, &n); {

printf ("\nEnter the array elements: "); temp=a[k];

for (i=0; i<n; i++) j=k-1;

scanf ("%d”, &a[i]); while((j>=0) &&(temp<=a[j]))

printf ("\elements in array before swapping: "); {

for (i=0; i<n; i++) a[j+1] =a[j];

printf (" %d”, a[i]); a[j]=temp;

printf("\n"); j=j-1;

insertionsort (a, n); }

printf ("\n\nElements in array after sorting: "); }

for (x=0; x<n; x++) }

printf (" %d”, a[x]);


getch ();
}
Quicksort
 In this method, an element called pivot is identified and that element is fixed in its place
by moving all the elements less than that to its left and all the elements greater than that
to its right.
Procedure:
1. If array only contains one element, return it.
2. Else
1. Pick one element to use as pivot.
2. Partition elements into two sub-arrays
a) Elements less than or equal to pivot b) Elements greater than pivot
c)Quicksort two sub-arrays. d)Return results

Recursive implementation with the left most array entry selected as the pivot element
/*Write a c program to implement the quick sort*/
#include<stdio.h>
void quicksort (int [10], int, int);
int main () {
int x [20], size, i;
printf ("\nEnter size of the array: ");
scanf ("%d”, &size);
printf ("\nEnter %d elements: “, size);
for (i=0; i<size; i++)
scanf ("%d”, &x[i]);
quicksort (x,0, size-1);
printf ("\nSorted elements: ");
for (i=0; i<size; i++)
printf (" %d”, x[i]);
getch ();
return 0;
}
void quicksort (int x [10], int first, int last) {
int pivot, j, temp, i;
if(first<last) {
pivot=first; i=first; j=last;
while(i<j) {
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j) {
temp=x[i]; x[i]=x[j]; x[j]=temp;
}
}
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort (x, first, j-1);
quicksort (x, j+1, last);
}
}
Merge Sort
 In this method, the elements are divided into partitions until each partition has sorted
elements.
 Then, these partitions are merged and the elements are properly positioned to get a fully
sorted list.
Procedure/Algorithm:
1. Split array A [0.n-1] into about equal halves and make copies of each half in arrays B and C.
2. Sort arrays B and C recursively.
3. Merge sorted arrays B and C into array A as follows:
3.1. Repeat the following until no elements remain in one of the arrays:
3.1.1 Compare the first elements in the remaining unprocessed portions of the arrays.
3.1.2 Copy the smaller of the two into A, while incrementing the index indicating the
unprocessed portion of that array.
3.2 Once all elements in one of the arrays are processed, copy the remaining unprocessed
elements from the other array into A.
Program
/*Program for merge sort*/
#include <stdio.h>
#include <conio.h>
void main ()
{
int i, n, a [100];
clrscr ();
printf ("\n Enter the size of the array:");
scanf ("%d”, &n);
printf ("\n Enter the elements:\n");
for (i = 0; i < n; i++)
scanf ("%d”, &a[i]);
mergesort (a,0, n-1);
printf ("\n Elements in sorted order:\n");
for (i = 0; i < n; i++)
printf ("%5d”, a[i]);
getch ();
}
void merge (int [], int, int, int);
void mergesort (int a [], int low, int high)
{
int mid;
if (low < high)
{
mid = (low + high)/2;
mergesort (a, low, mid);
mergesort (a, mid+1, high);
merge (a, low, high, mid);
}
}
void merge (int a [], int l, int h, int m) {
int c [100], i, j, k;
i = l; j = m + 1; k = l;
while (i <= m && j <= h) {
if(a[i] < a[j]) {
c[k] = a[i];
i++; k++;
}
else {
c[k] =a[j];
j++; k++;
}
}
while (i <= m)
c[k++] = a[i++];
while (j <= h)
c[k++] = a[j++];
for (i = l; i < k; i++)
a[i] = c[i];
}
 Big O Notation Indicates, how hard an algorithm has to work to solve a problem.

Best Average Worst


Case Case Case

Linear O (1) O(n) O(n)


Search

Binary O (1) O (log n) O (log n)


Search

Bubble Sort O(n2) O(n2) O(n2)

Selection O(n2) O(n2) O(n2)


Sort

Insertion O(n2) O(n2) O(n2)


Sort
Merge Sort O(n log O(n log n) O(n log
n) n)

Quick Sort O(n log O(n log n) O(n2)


n)

Example 1:

C Strings
A string is a sequence of characters. A string literal is enclosed in double quotes.
Declaring a String:
The general form of declaration of a string variable is,
char string_name [size];
 The size determines the number of characters in the string_name.
 When the compiler assigns a character string to a character array, it automatically
supplies a null character (‘\0’) at the end of the string.
 The size should be equal to the maximum number of characters in the string plus one
Initializing a String: This can be done in two ways.
1.char str1[7] =“Welcome”; 2.char str2[8]={‘W’,’e’,’l’,’c’,’o’,’m’,’e’,’\0’};

String Literal References

Memory for strings must be allocated before the string can be used.
Formatted input and output functions: scanf () and printf ()
scanf (): The string can be read using the scanf function with the format specifier %s.
Syntax for reading string using scanf function is scanf (“%s”, string_name);
printf (): The string can be print using printf () function with the format specifier %s
syntax: printf (“%s”, string_name);
Character I/O from keyboard:
To read characters from the keyboard and write to the screen, it takes the following form:
char c = getchar (); //reads one character from the keyboard
putchar(c); // display the character on the monitor
Un-formatted input functions: gets () and puts ()
C provides easy approach to read a string of characters using gets () function.
Syntax: gets (string_name);
The function accepts string from the keyboard. The string entered includes the white spaces. The
input will terminate only after pressing <Enter Key>.
Once the <Enter key > is pressed, a null character (\0) appended at the end of the string.
Advantage: It is capable of reading multiple words from the keyword.
To display the string on the screen we use a function puts ().
Syntax: puts(str);
Where str is a string variable containing a string value.
Print Days of the Week
String Handling library function
There are several string library functions used to manipulate string and the prototypes for these
functions are in header file “string.h”. Several string functions are.
strlen ()
This function return the length of the string. i.e., the number of characters in the string excluding
the terminating NULL character. It accepts a single argument which is pointer to the first
character of the string. For example, strlen(“suresh”); It return the value 6.

strcmp ()
This function is used to compare two strings. If the two-string match, strcmp () return a value 0
otherwise it returns a non-zero value. It compare the strings character by character and the
comparison stops when the end of the string is reached or the corresponding characters in the two
string are not same.
strcmp (s1, s2) return a value:
<0 when s1<s2
=0 when s1=s2
>0 when s1>s2
The exact value returned in case of dissimilar strings is not defined. We only know
that if s1<s2 then a negative value will be returned and if s1>s2 then a positive
value will be returned.

Strcpy ()
This function is used to copying one string to another string. The function strcpy (str1, str2)
copies str2 to str1 including the NULL character. Here str2 is the source string and str1 is the
destination string.
The old content of the destination string str1 are lost. The function returns a pointer
to destination string str1.

Strcat ()
This function is used to append a copy of a string at the end of the other string. If
the first string is “”Purva” and second string is “Belmont” then after using this function the
string becomes “PusvaBelmont”. The NULL character from str1 is moved and str2 is added at
the end of str1. The 2nd string str2 remains unaffected. A pointer to the first string str1 is
returned by the function.

/*Define functions- length of a string, copy, concatenate, convert into


uppercase letters, compare two strings for alphabetical order- over strings
and implement in a program*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
main () {
char str1[15], str2[15], str3[10];
int n, c, len, i;
printf ("\n Enter the string1 ");
gets(str1);
puts(str1);
printf ("\n Enter the string2 ");
gets(str2);
puts(str2);
printf ("Enter the string 3 ");
scanf ("%s”, str3);
printf ("%s”, str3);
printf("\n***************************");
printf ("\n 1. String Length ");
printf ("\n 2. String Copy ");
printf ("\n 3. String Comparison ");
printf ("\n 4. String Concat ");
printf ("\n 5. UpperCase ");
printf("\n***************************");
printf ("\n Enter the choice u want to perform");
scanf ("%d”, &n);
switch(n)
{
case 1: len=strlen(str1);
printf ("\n The length of the string entered is %d”, len);
break;
case 2: strcpy (str1, str2);
printf ("\n 1st string =%s,2nd string=%s”, str1, str2);
break;
case 3: c=strcmp (str1, str2);
if(c==0)
printf ("\n Both are equal");
else
printf ("\n Both are different");
break;
case 4: printf ("\n The resultant string is: %s”, strcat (str1, str2));
break;
case 5: for (i=0; i<strlen(str1); i++)
str1[i]=toupper(str1[i]);
printf ("%s”, str1);
break;
default: printf ("\n Enter correct choice");
}
}
OUTPUT:
Enter the string1: abcd
abcd
Enter the string2: efgh
efgh
Enter the string3: pqr
pqr
***************************
1. String Length
2. String Copy
3. String Comparison
4. String Concat
5. UpperCase
***************************
Enter ur choice 4
The resultant string is: abcdefgh

FUNCTION
 A function is a self-contained block of codes or sub programs with a set of statements
that perform some specific task or coherent task when it is called.
 It is something like to hiring a person to do some specific task like, every six months
servicing a bike and hand over to it.
Any ‘C’ program contain at least one function i.e., main ().
There are basically two types of function those are
1. Library function
Example: abs (a) function gives the absolute value of a, available in
<math.h>
pow (x, y) function computes x power y. available in <math.h>
printf () and scanf () performs I/O functions and etc..,
System defined function can’t be modified, it can only read and can be used. These functions are
supplied with every C compiler Source of these library function are pre complied and only object
code get used by the user by linking to the code by linker

2. User defined function


 The user defined functions defined by the user according to its requirement.
Example: main (), sum (), fact (), show (), display () and etc.,
Advantages of User-defined Functions
1)Modular Programming: It facilitates top-down modular programming.
2)Reduction of Source Code: The length of the source program can be reduced by using
functions at appropriate places.
3)Easier Debugging: It is easy to locate and isolate a faulty function for further investigation.
4)Code Reusability: A program can be used to avoid rewriting the same sequence of code at
two or more locations in a program.
5)Function Sharing: Programming teams does a large percentage of programming. If the
program is divided into subprograms, each subprogram can be written by one or two team
members of the team rather than having the whole team to work on the complex program.

The general form of a C user-defined function:


return_type function_name (argument declaration)
{

//local declarations

……

//statements

……

return (expression);

return-type:
 Specifies the type of value that a function returns using the return statement.
 It can be any valid data type. If no data type is specified the function is assumed to return
an integer result.
function-name:
 Must follow same rules of variable names in C.
 No two functions have the same name in a C program.
argument declaration:
 It is a comma-separated list of variables that receive the values of the argument when
function is called. If there is no argument declaration the bracket consists of keyword
void.
Function Declaration (or) Prototype:
 Function declaration is also known as function prototype. It informs the
compiler
about three thing, those are name of the function, number and type of
argument
received by the function and the type of value returned by the function.
 While declaring the name of the argument is optional and the function
prototype
always terminated by the semicolon.
Function definition: -
Function definition consists of the whole description and code of the function. It tells about what
function is doing what are its inputs and what are its output. It consists of two parts function
header and function body
Syntax: -
return type function (type 1 arg1, type2 arg2, type3 arg3) /*function header*/
{
Local variable declaration;
Statement 1;
Statement 2;
Return value
}
The arguments of the function definition are known as formal arguments.
Function Call
When the function gets called by the calling function then that is called, function
call. The compiler execute these functions when the semicolon is followed by the
function name.
Example: -
function (arg1, arg2, arg3);
The argument that are used inside the function call are called actual argument
Ex: -
int S=sum (a, b); //actual arguments
Category of User –Defined Functions:
Category 1: Functions with no arguments and no return values
/*Example for Functions with no arguments and no return values
to print addition of sum of two numbers*/
#include<stdio.h>
void sum (); /* function prototype */
void main ()
{
sum (); /* function calling*/
}
void sum () /* Function Definition */
{
int x, y, z;
printf (“\n Enter the values of x and y: “);
scanf (“%d%d”, &x, &y);
z=x+y;
printf (“\n The sum = %d”, z);
}
Category 2: Functions with no arguments and with return values
/*Example for Functions with no arguments and with return values
to print addition of sum of two numbers*/
#include<stdio.h>
int sum (); /* function prototype */
int main ()
{
int c;
c = sum (); /*function calling */
printf (“\n The sum = %d”, c);
}
int sum () /* Function Definition */
{
int x, y;
printf (“\n Enter the values of x and y: “);
scanf (“%d%d”, &x, &y);
/* return value to the calling function */
return x+y;
}
Category 3: Functions with arguments and no return values
/*Example for Functions with arguments and no return values
to print addition of sum of two numbers*/
#include<stdio.h>
void sum (int, int); /* function prototype */
void main ()
{
int a, b;
printf (“\n Enter the values of a and b: “);
scanf (“%d%d”, &a, &b);
sum (a, b); /*calling function */
}
void sum (int x, int y) /* function definition */
{
int z;
z=x+y;
printf (“\n The Sum =%d”, z);
}
Category 4: Functions with arguments and return values
#include<stdio.h>
void sum (int, int); /* function prototype */
void main ()
{
int a, b, c;
printf (“\n Enter the values of a and b: “);
scanf (“%d%d”, &a, &b);
c = sum (a, b); /*calling function */
printf (“\n The Sum =%d”, c);
}
void sum (int x, int y) /* function definition */
{
int z;
z=x+y;
return z;
}
Passing Parameters to Functions
1)call by value:
 When a function is called with actual parameters, the values of actual parameters are
copied into the formal parameters.
 If the values of the formal parameters changes in the function, the values of the actual
parameters are not changed.

include <stdio.h>
void swap (int, int); //prototype of the function
int main ()
{
int a = 10;
int b = 20;
printf ("Before swapping the values in main a = %d, b = %d\n”, a, b);
swap (a, b);
printf ("After swapping values in main a = %d, b = %d\n”, a, b);
}
void swap (int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
printf ("After swapping values in function a = %d, b = %d\n”, x, y); // Formal parameters
} efore swapping the values in main a = 10, b = 20
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function x = 20, y = 10
After swapping values in main a = 10, b = 20

Call by reference
 Instead of passing the value of variable, address or reference is passed and the function
operate on address of the variable rather than value.
 Here formal argument is alter to the actual argument, it means formal arguments calls the
actual arguments.
include <stdio.h>
void swap (int *x, int *y); //prototype of the function
int main ()
{
int a = 10;
int b = 20;
printf ("Before swapping the values in main a = %d, b = %d\n”, a, b);
swap (&a, &b);
printf ("After swapping values in main a = %d, b = %d\n”, a, b);
}
void swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("After swapping values in function a = %d, b = %d\n",*x,*y); // Formal parameters
} efore swapping the values in main a = 10, b = 20
Output
Before swapping the values in main a = 10, b = 20
After swapping values in function x = 20, y = 10
After swapping values in main a = 20, b = 10

Recursion
When function calls itself (inside function body) again and again then it is called as recursive
function. In recursion calling function and called function are same. It is powerful technique of
writing complicated algorithm in easiest way.
According to recursion problem is defined in term of itself. Here statement with in
body of the function calls the same function and same times it is called as circular
definition. In other words, recursion is the process of defining something in form of
itself.
Syntax:
Ex: - /*calculate factorial of a no. using recursion*/
int fact(int);
void main ()
{
int num;
printf (“enter a number”);
scanf (“%d”, &num);
f=fact(num);
printf (“factorial is =%d\n”, f);
}
fact (int num)
{
If (num==0||num==1)
return 1;
else
return(num*fact(num-1));
}

Storage Classes
 Storage class in c language is a specifier which tells the compiler where and how to store
variables, its initial value and scope of the variables in a program. Or attributes of
variable is known as storage class or in compiler point of view a variable identify some
physical location within a computer where its string of bits value can be stored is known
as storage class.
 The kind of location in the computer, where value can be stored is either in the memory
or in the register. There are various storage class which determined, in which of the two-
location value would be stored.
Syntax of declaring storage classes is: - storage class datatype variable name;
There are four types of storage classes and all are keywords: -
1) Automatic (auto)
2) Register (register)
3) Static (static)
4) External (extern)
Examples: -
auto float x; or float x;
extern int x;
register char c;
static int y;
Compiler assume different storage class based on: -
1) Storage class: - tells us about storage place (where variable would be stored).
2) Intial value: -what would be the initial value of the variable. If initial value not assigned, then
what value taken by uninitialized variable.
3) Scope of the variable: -what would be the value of the variable of the program.
4) Life time: - It is the time between the creation and distribution of a variable or how long
would variable exist.
1. Automatic storage class
The keyword used to declare automatic storage class is auto.
Its features: -
Storage-memory location
Default initial value: -unpredictable value or garbage value.
Scope: -local to the block or function in which variable is defined.
Life time: -Till the control remains within function or block in which it is defined.
It terminates when function is released.
The variable without any storage class specifier is called automatic variable.
Example: -
main ()
{
auto int i;
printf (“i= %d”, i);
}
2. Register storage class
The keyword used to declare this storage class is register. The features are: -
Storage: -CPU register.
Default initial value: -garbage value
Scope: -local to the function or block in which it is defined.
Life time: -till controls remains within function or blocks in which it is defined. Register
variable don’t have memory address so we can’t apply address operator on it. CPU register
generally of 16 bits or 2 bytes. So, we can apply storage classesonly for integers, characters,
pointer type.
 Variable stored in register storage class always access faster than, which is always stored
in the memory. But to store all variable in the CPU register is not possible because of
limitation of the register pair.
 And when variable is used at many places like loop counter, then it is better to declare it
as register class.
Example: -
main ()
{
register int i;
for (i=1; i<=12; i++)
printf (“%d”, i);
}

3 Static storage class


The keyword used to declare static storage class is static.
Its feature are: -
Storage: -memory location
Default initial value: - zero
Scope: - local to the block or function in which it is defined.
Life time: - value of the variable persist or remain between different function call.
Example: -
main ()
{
reduce ();
reduce ();
reduce ();
}
reduce ()
{
static int x=10;
printf (“%d”, x);
x++;
}
Output: -10,11,12

External storage classes: The keyword used for this class is extern.
Features are: -
Storage: - memory area
Default initial value: -zero
Scope: - global
Life time: -as long as program execution remains it retains. Declaration does not create
variables, only it refers that already been created at somewhere else. So, memory is not allocated
at a time of declaration and the external variables are declared at outside of all the function.
Example: -
int i, j;
void main ()
{
printf (“i=%d”, i);
receive ();
receive ();
reduce ();
reduce ();
}
receive ()
{
i=i+2;
printf (“on increase i=%d”, i);
}
reduce ()
{
i=i-1;
printf (“on reduce i=%d”, i);
}
Output: -i=0,2,4,3,2.
When there is large program i.e., divided into several files, then external variable should be
preferred. External variable extends the scope of variable.

Pointers
Pointer variable is a variable which stores the address of another variable and it points indirectly
to the value of that variable.
Syntax: Data type *pointer name;
Example
Two operators are used in the pointer i.e., address operator (&) and indirection
operator or dereference operator (*).
Indirection operator gives the values stored at a particular address.
Address operator cannot be used in any constant or any expression.
Example:
void main ()
{
int i=105;
int *p; 104 i 2000 *p
p=&i;
t 2000 3000
printf (“value of i=%d”, *p); output i=104
printf (“address of i=%d”, &i); output i= 2000
printf (“address of i=%d”, p); output I = 2000
printf (“address of p=%u”, &p); output p = 3000
}

Pointers to Pointers
Pointer vs array
Example :-
void main ()
{
static char arr [] =” Rama”;
char*p=” Rama”;
printf (“%s%s”, arr, p);
}
In the above example, at the first time printf (), print the same value array and pointer. Here array
arr, as pointer to character and p act as a pointer to array of character. When we are trying to
increase the value of arr it would give the error because it’s known to compiler about an array
and its base address which is always printed to base address is known as constant pointer and the
base address of array
which is not allowed by the compiler.
printf (“size of (p)”, size of (ar));

size of (p) 2/4 bytes


size of(ar) 5 byes
Structure
It is the collection of dissimilar data types or heterogenous data types grouped together. It means
the data types may or may not be of same type.
Structure declaration struct
tagname
{
Data type member1;
Data type member2;
Data type member3;
………
………
Data type member n;
};
OR
struct
{
Data type member1;
Data type member2;
98 *Under revision
Data type member3;
………
………
Data type member n;
};
OR
struct tagname
{
struct element 1;
struct element 2;
struct element 3;
………
………
struct element n;
};
Structure variable declaration;
struct student
{
int age;
char name [20];
char branch [20];
}; struct student s;
Initialization of structure variable-
Like primary variables structure variables can also be initialized when they are
declared. Structure templates can be defined locally or globally. If it is local, it can
be used within that function. If it is global, it can be used by all other functions of
the program.
We can’t initialize structure members while defining the structure
struct student
{
int age=20;
char name [20] =” sona”;
} s1;
The above is invalid.
A structure can be initialized as
struct student
{
int age, roll;
char name [20];
} struct student s1={16,101,” sona”};
struct student s2= {17,102,” rupa”};
If initializer is less than no. of structure variable, automatically rest values are taken
as zero. Memory organization of structure
10 Bytes 2 Bytes 4 Bytes

Accessing structure elements-


Dot operator is used to access the structure elements. Its associativety is from left
to right.
structure variable;
s1.name [];
s1. roll;
s1.age;
Elements of structure are stored in contiguous memory locations. Value of structure variable can
be assigned to another structure variable of same type using assignment operator.
Example:
#include<stdio.h>
#include<conio.h>
void main ()
{
int roll, age;
char branch;
} s1, s2;
printf (“\n enter roll, age, branch=”);
scanf (“%d %d %c”, &s1. roll, &s1.age, &s1. branch);
s2. roll=s1.roll;
printf (“students’ details=\n”);
printf (“%d %d %c”, s1. roll, s1.age, s1. branch);
printf (“%d”, s2. roll);
}

Unary, relational, arithmetic, bitwise operators are not allowed within structure
variables.
Size of structure-
Size of structure can be found out using sizeof () operator with structure variable
name or tag name with keyword.
sizeof (struct student); or
sizeof(s1);
sizeof(s2);
Size of structure is different in different machines. So, size of whole structure may
not be equal to sum of size of its members.

Array of structures
When database of any element is used in huge amount, we prefer Array of
structures.
Example: suppose we want to maintain data base of 200 students, Array of
structures are used.
#include<stdio.h>
#include<string.h>
struct student
{
char name [30];
char branch [25];
int roll;
};
void main ()
{
struct student s [200];
int i;
s[i]. roll=i+1;
printf ("\nEnter information of students:");
for (i=0; i<200; i++)
{
printf ("\nEnter the roll no: %d\n”, s[i]. roll);
printf ("\nEnter the name:");
scanf ("%s”, s[i].name);
printf ("\nEnter the branch:");
scanf ("%s”, s[i]. branch);
printf("\n");
}
printf ("\nDisplaying information of students:\n\n");
for (i=0; i<200; i++)
{
printf ("\n\information for roll no%d:\n”, i+1);
printf("\nName:");
puts(s[i].name);
printf("\branch:");
puts(s[i]. branch);
}
}
In Array of structures each element of array is of structure type as in above
example.
Array within structures
struct student
{
char name [30];
int roll, age, marks [5];
}; struct student s [200];
We can also initialize using same syntax as in array.

Nested structure
When a structure is within another structure, it is called Nested structure. A
structure variable can be a member of another structure and it is represented as
struct student
{
element 1;
element 2;
………
………
struct student1
{
member 1;
member 2;
} variable 1;
……….
……….
element n;
} variable 2;
It is possible to define structure outside & declare its variable inside other
structure.
struct date
{
int date, month;
};
struct student
{
char nm[20];
int roll;
struct date d;
}; struct student s1;
struct student s2, s3;
Nested structure may also be initialized at the time of declaration like in above
example.
struct student s={“name”,200, {date, month}};
{“ram”,201, {12,11}};
Nesting of structure within itself is not valid. Nesting of structure can be
extended to any level.
struct time
{
int hr, min;
};
struct day
{
int date, month;
struct time t1;
};
struct student
{
char nm [20];
struct day d;
}stud1, stud2, stud3;

Passing structure elements to function


We can pass each element of the structure through function but passing individual
element is difficult when number of structure element increases. To overcome this,
we use to pass the whole structure through function instead of passing individual
element.
#include<stdio.h>
#include<string.h>
void main ()
{
struct student
{
char name [30];
char branch [25];
int roll;
} struct student s;
printf (“\n enter name=”);
gets(s.name);
printf ("\nEnter roll:");
scanf ("%d”, &s. roll);
printf ("\nEnter branch:");
gets (s. branch);
display (name, roll, branch);
}
display (char name, int roll, char branch)
{
printf (“\n name=%s, \n roll=%d, \n branch=%s”, s.name, s. roll. s. branch);
}

Passing entire structure to function


#include<stdio.h>
#include<string.h>
struct student
{
char name [30];
int age, roll;
};
display (struct student); //passing entire structure
void main ()
{
struct student s1= {” sona”,16,101};
struct student s2= {” rupa”,17,102};
display(s1);
display(s2);
}
display (struct student s)
{
printf (“\n name=%s, \n age=%d, \n roll=%d”, s.name, s.age, s. roll);
}
Output: name=sona
roll=16
UNION
 Union is derived data type contains collection of different data type or dissimilar
elements. All definition declaration of union variable and accessing member is similar to
structure, but instead of keyword struct the keyword union is used, the main difference
between union and structure is
 Each member of structure occupy the memory location, but in the unions, members share
memory. Union is used for saving memory and concept is useful when it is not necessary
to use all members of union at a time. Where union offers a memory treated as variable of
one type on one occasionwhere (struct), it read number of different variables stored at
different place of memory.
Syntax of union:
union student
{
datatype member1;
datatype member2;
};
Like structure variable, union variable can be declared with definition or separately
such as
union union name
{
Datatype member1;
} var1;
Memory organization in union

Example: - union student s;


Union members can also be accessed by the dot operator with union variable and if
we have pointer to union then member can be accessed by using (arrow) operator
as with structure.
Example: - struct student
struct student
{
int i;
char ch [10];
}; struct student s;
Here datatype/member structure occupy 12 byte of location is memory, where as in
the union side it occupy only 10 byte.

Nested of Union
When one union is inside the another union it is called nested of union.
Example:-
union a
{
int i;
int age;
};
union b
{
char name[10];
union a aa;
}; union b bb;
There can also be union inside structure or structure in union.

Example:-
void main ()
{
struct a
{
int i;
char ch [20];
};
struct b
{
int i;
char d [10];
};
union z
{
struct a a1;
struct b b1;
}; union z z1;
z1.b1. j=20;
z1. a1. i=10;
z1.a1.ch [10] = “i “;
z1.b1.d[0] =” j “;
printf (“ “);
Dynamic memory Allocation
 The process of allocating memory at the time of execution or at the runtime, is called
dynamic memory location.
 Two types of problem may occur in static memory allocation. If number of values to be
stored is less than the size of memory, there would be wastage of memory.
 If we would want to store more values by increase in size during the execution on
assigned size then it fails.
 Allocation and release of memory space can be done with the help of some library
function called dynamic memory allocation function. These library functions are called as
dynamic memory allocation function. These library function prototypes are found in
the header file, “alloc.h” where it has defined.
 Function take memory from memory area is called heap and release when not required.
 Pointer has important role in the dynamic memory allocation to allocate memory.
malloc ():
This function use to allocate memory during run time, its declaration is
void*malloc(size);
malloc ()
returns the pointer to the 1st byte and allocate memory, and its return type is void,
which can be type cast such as:
int *p=(datatype*) malloc(size)
 If memory location is successful, it returns the address of the memory chunk that was
allocated and it returns null on unsuccessful and from the above declaration a pointer of
type(datatype) and size in byte.
 datatype pointer used to typecast the pointer returned by malloc and this typecasting is
necessary since, malloc () by default returns a pointer to void.
Example int*p=(int*) malloc (10);
So, from the above pointer p, allocated IO contigious memory space address of 1st
byte and is stored in the variable. We can also use, the size of operator to specify the size, such
as
*p=(int*) malloc (5*size of int) Here, 5 is the no. of data.
Moreover , it returns null, if no sufficient memory available, we should always
check the malloc return such as, if(p==null)
printf (“not sufficient memory”);
Example:
/*calculate the average of mark*/
void main ()
{
int n, avg, i, *p, sum=0;
printf ("enter the no. of marks”);
scanf (“%d”, &n);
p= (int *) malloc(n*size(int));
if(p==null)
printf (“not sufficient”);
exit ();
}
for (i=0; i<n; i++)
scanf (“%d”, (p+i));
for (i=0; i<n; i++)
printf (“%d”, *(p+i));
sum=sum+*p;
avg=sum/n;
printf (“avg=%d”, avg);

calloc ()
Similar to malloc only difference is that calloc function use to allocate multiple
block of memory.
two arguments are there
1st argument specify number of blocks
2nd argument specify size of each block.
Example: -
int *p= (int*) calloc (5, 2);
int*p= (int *) calloc (5, size of (int));
Another difference between malloc and calloc is by default memory allocated by
malloc contains garbage value, whereas memory allocated by calloc is initialized
by zero (but this initialisation) is not reliable.

realloc ()
The function realloc use to change the size of the memory block and it alter the size of the
memory block without losing the old data, it is called reallocation of memory.
It takes two argument such as;
int *ptr= (int *) malloc(size);
int*p= (int *) realloc (ptr, new size);
The new size allocated may be larger or smaller. If new size is larger than the old size, then old
data is not lost and newly allocated bytes are uninitialized. If old address is not sufficient then
starting address contained in pointer may be changed and this reallocation function moves
content of old block into the new block and data on the old block is not lost.
Example:
#include<stdio.h>
#include<alloc.h>
void main ()
int i, *p;
p=(int*) malloc (5*size of (int));
if(p==null)
{
printf (“space not available”);
exit ();
printf (“enter 5 integers”);
for (i=0; i<5; i++)
{
scanf (“%d”, (p+i));
int*ptr=(int*) realloc (9*size of (int));
if(ptr==null)
{
printf (“not available”);
exit ();
}
printf (“enter 4 more integer”);
for (i=5; i<9; i++)
scanf (“%d”, (p+i));
for (i=0; i<9; i++)
printf (“%d”, *(p+i));
}

free ()
Function free () is used to release space allocated dynamically, the memory released by free () is
made available to heap again. It can be used for further purpose.
Syntax for free declaration.
void(*ptr)
Or
free(p)
When program is terminated, memory released automatically by the operating system. Even we
don’t free the memory, it doesn’t give error, thus lead to memory leak. We can’t free the
memory, those didn’t allocated.

Dynamic array
Array is the example where memory is organized in contiguous way, in the dynamic memory
allocation function used such as malloc (), calloc (), realloc () always made up of contiguous way
and as usual we can access the element in two ways as:
Subscript notation
Pointer notation
Example:
#include<stdio.h>
#include<alloc.h>
void main ()
{
printf (“enter the no. of values”);
scanf (“%d”, &n);
p=(int*) malloc (n*size of int);
If(p==null)
printf (“not available memory”);
exit ();
}
for (i=0; i<n; i++)
{
printf (“enter an integer”);
scanf (“%d”, &p[i]);
for (i=0; i<n; i++)
{
printf (“%d”, p[i]);
}
}

File handling
File: the file is a permanent storage medium in which we can store the data permanently.
Types of files can be handled
we can handle three types of file as
(1) sequential file
(2) random access file
(3) binary file
File Operation

opening a file:
Before performing any type of operation, a file must be opened and for this
fopen () function is used.
syntax:
file-pointer=fopen (“FILE NAME”,” Mode of open”);
example:
FILE *fp=fopen (“ar.c”,” r”);
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
The file can be open in three different ways as
Read mode’ r’/rt
Write mode ’w’/wt
Appened Mode ’a’/at
Reading a character from a file
getc () is used to read a character into a file
Syntax:
character variable=getc(file_ptr);
Writing a character into a file
putc () is used to write a character into a file
puts (character-var, file-ptr);

ClOSING A FILE
fclose () function close a file.
fclose(file-ptr);
fcloseall () is used to close all the opened file at a time
File Operation
The following file operation carried out the file
(1) creation of a new file
(3) writing a file
(4) closing a file
Before performing any type of operation, we must have to open the file.c, language
communicate with file using A new type called file pointer.
Operation with fopen ()
File pointer=fopen (“FILE NAME”,”mode of open”);
If fopen () unable to open a file then it will return NULL to the file-pointer.

Reading and writing a character from/to a file


fgetc () is used for reading a character from the file
Syntax:
character variable= fgetc (file pointer);
fputc () is used to writing a character to a file
Syntax:
fputc (character, file pointer);

/*Program to copy a file to another*/


#include<stdio.h>
void main ()
{
FILE *fs, *fd;
char ch;
If (fs=fopen (“scr.txt”,” r”) ==0)
{
printf (“sorry….The source file cannot be opened”);
return;
}
If (fd=fopen (“dest.txt”,” w”) ==0)
{
printf (“Sorry…..The destination file cannot be opened”);
fclose(fs);
return;
}
while(ch=fgets(fs)! =EOF)
fputc (ch, fd);
fcloseall();
}

Reading and writing a string from/to a file


getw () is used for reading a string from the file
Syntax:
gets (file pointer);
putw () is used to writing a character to a file
Syntax:
fputs (integer, file_pointer);
#include<stdio.h>
#include<stdlib.h>
void main ()
{
FILE *fp;
int word;
/*place the word in a file*/
fp=fopen (“dgt.txt”,” wb”);
If(fp==NULL)
{
printf (“Error opening file”);
exit (1);
}
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)
{
printf (“Error opening file”);
exit (1);
}
/*extract the word*/
word=getw(fp);
If(ferror(fp))
printf (“Error reading file\n”);
else
printf (“Successful read: word=%d\n”, word);
/*clean up*/
fclose(fp);
}

Reading and writing a string from/to a file


fgets () is used for reading a string from the file
Syntax:
fgets (string, length, file pointer);
fputs () is used to writing a character to a file
Syntax:
fputs (string, file_pointer);
#include<string.h>
#include<stdio.h>
void main(void)
{
FILE*stream;
char string [] =” This is a test”;
char msg [20];
/*open a file for update*/
stream=fopen (“DUMMY.FIL”,” w+”);
/*write a string into the file*/
fwrite (string, strlen(string),1, stream);
/*seek to the start of the file*/
fseek (stream,0, SEEK_SET);
/*read a string from the file*/
fgets (msg, strlen(string)+1, stream);
/*display the string*/
printf (“%s”, msg);
fclose(stream);
}
Programs
FACTORIAL OF A NUMBER RECURSSIVE
include<stdio.h>
int factorial (int n);
int main ()
{
int number;
printf ("Enter an integer number: ");
scanf ("%d”, &number);
int result = factorial(number);
printf ("Factorial of %d = %d", number, result);
return 0;
}
int factorial (int n)
{
if(n==0) return 1;
else return (n*factorial(n-1));
}

FIBONACCI NUMBER USING RECURSSION


#include<stdio.h>
void fib (int n) {
int fno;
if(n==1)
return 1;
else if(n==2)
return 1;
else
fno=fib(n-1) +fib(n-2);
return fno;
}
int main () {
int n;
printf ("Enter the number of elements: ");
scanf ("%d”, &n);
for (i=0; i<n; i++)
printf ("Fibonacci Series: %d”, fib(i));
return 0;
}

Output:

Enter the number of elements: 15

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

BUBBLE SORT
//C program to sort the numbers using bubble sort
main() {
int arr[50],temp,i,j,n;
printf("\nEnter any Value less Than 50:");
scanf("%d",&n);
printf("\n\tEnter The Values into ARRAY: ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=1;i<n;i++) {
for(j=0;j<n-i;j++) {
if(arr[j] >arr[j+1]) {
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
printf(“\nSorted Series:");
for(i=0;i<n;i++) {
printf("\n %d",arr[i]);
}

STRINGS
/*Define functions- length of a string, copy, concatenate, convert into
uppercase letters, compare two strings for alphabetical order- over strings
and implement in a program*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
main () {
char str1[15], str2[15], str3[10];
int n, c, len, i;
printf ("\n Enter the string1 ");
gets(str1);
puts(str1);
printf ("\n Enter the string2 ");
gets(str2);
puts(str2);
printf ("Enter the string 3 ");
scanf ("%s”, str3);
printf ("%s”, str3);
printf("\n***************************");
printf ("\n 1. String Length ");
printf ("\n 2. String Copy ");
printf ("\n 3. String Comparison ");
printf ("\n 4. String Concat ");
printf ("\n 5. UpperCase ");
printf("\n***************************");
printf ("\n Enter the choice u want to perform");
scanf ("%d”, &n);
switch(n)
{
case 1: len=strlen(str1);
printf ("\n The length of the string entered is %d”, len);
break;
case 2: strcpy (str1, str2);
printf ("\n 1st string =%s,2nd string=%s”, str1, str2);
break;
case 3: c=strcmp (str1, str2);
if(c==0)
printf ("\n Both are equal");
else
printf ("\n Both are different");
break;
case 4: printf ("\n the resultant string is: %s”, strcat (str1, str2));
break;
case 5: for (i=0; i<strlen(str1); i++)
str1[i]=toupper(str1[i]);
printf ("%s”, str1);
break;
default: printf ("\n Enter correct choice");
}
}

MULTIPLICATION OF MATRIX (product of matrix)


#include<stdio.h>
#include<stdlib.h>
int main () {
int a [10][10], b [10][10], mul [10][10], r, c, i, j, k;
system("cls");
printf ("enter the number of row=");
scanf ("%d”, &r);
printf ("enter the number of columns=");
scanf ("%d”, &c);
printf ("enter the first matrix element=\n");
for (i=0; i<r; i++)
{
for (j=0; j<c; j++)
{
scanf ("%d”, &a[i][j]);
}
}
printf ("enter the second matrix element=\n");
for (i=0; i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
}

printf("multiply of the matrix=\n");


for(i=0;i<r;i++)
{
for(j=0; j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
}

Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
1 1 1
2 2 2
3 3 3
enter the second matrix element=
1 1 1
2 2 2
3 3 3
multiply of the matrix=
6 6 6
12 12 12
18 18 18

COPYING CONTENT OF ONE FILE TO ANOTHER FILE


#include <stdio.h>
#include <stdlib.h> // For exit ()

int main ()
{
FILE *fptr1, *fptr2;
char filename [100], c;

fprintf ("Enter the filename to open for reading \n");


fscanf ("%s", filename);

// Open one file for reading


fptr1 = fopen (filename, "r");
if (fptr1 == NULL)
{
fprintf ("Cannot open file %s \n", filename);
exit (0);
}

fprintf ("Enter the filename to open for writing \n");


fscanf ("%s", filename);

// Open another file for writing


fptr2 = fopen (filename, "w");
if (fptr2 == NULL)
{
fprintf ("Cannot open file %s \n", filename);
exit (0);
}

// Read contents from file


c = fgetc(fptr1);
while (c! = EOF)
{
fputc (c, fptr2);
c = fgetc(fptr1);
}

fprintf ("\nContents copied to %s", filename);

fclose(fptr1);
fclose(fptr2);
return 0;
}

Output:
Enter the filename to open for reading
a.txt
Enter the filename to open for writing
b.txt
Contents copied to b.txt

MAX N MIN OF AN ARRAY ELEMENTS


#include <conio.h>
#include<stdio.h>
int main()
{
int a[1000],i,n,min,max;
printf("Enter size of the array : ");
scanf("%d",&n);

printf("Enter elements in array : ");


for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}

min=max=a[0];
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);
printf("\nmaximum of array is : %d",max);

return 0;
}
Output:
Enter size of the array :5
Enter elements in array : 1
32
43
54
65
Minimum of an array is :1
Maximum of an array is :5
PALINDROME OR NOT\
#include<stdio.h>
int main ()
{
int n, r, sum=0, temp;
printf ("enter the number=");
scanf ("%d”, &n);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10) +r;
n=n/10;
}
if(temp==sum)
printf ("palindrome number ");
else
printf ("not palindrome");
return 0;
}

Output :
enter the number=151
palindrome number

enter the number=5621


not palindrome number

MACROS IN C
What is a Macro in C?

You can say that macro is a piece of code that is replaced by the value of the macro
throughout the program. You can define a macro with #define directive. At the end of
defining a macro, you don’t have to put a semicolon(;) to terminate it.

Example:-
#define PI 3.14
Example:- Object-like Macros
#include <stdio.h>
#define PI 3.142
Void main()
{
int area,r;
printf(“Enter the radius”);
scanf(“%d”, &r);
area = PI *r*r;
printf("Area is: %d", area);
}

TRANSPOSE OF A MATRIX

#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

// asssigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// printing the matrix a[][]


printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
if (j == c - 1)
printf("\n");
}

// computing the transpose


for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}

// printing the transpose


printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}

Output :

Enter rows and columns: 2


3
Enter matrix elements:
Enter element a11: 1
Enter element a12: 4
Enter element a13: 0
Enter element a21: -5
Enter element a22: 2
Enter element a23: 7

Entered matrix:
1 4 0
-5 2 7

Transpose of the matrix:


1 -5
4 2
0 7

You might also like