0% found this document useful (0 votes)
182 views178 pages

Raghusir Notes

The document provides an overview of C language basics. It discusses compilers, source code, header files, functions like printf(), main(), comments, data types, variables, expressions, statements, constants, operators, preprocessor directives, and more. It also explains the compilation process involving preprocessing, compilation, assembly, and linking stages to create an executable file.

Uploaded by

BATLE KALYANI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
182 views178 pages

Raghusir Notes

The document provides an overview of C language basics. It discusses compilers, source code, header files, functions like printf(), main(), comments, data types, variables, expressions, statements, constants, operators, preprocessor directives, and more. It also explains the compilation process involving preprocessing, compilation, assembly, and linking stages to create an executable file.

Uploaded by

BATLE KALYANI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 178

C-LANGUAGE BASICS

-> compiler
1. source code - c language - test.c //input file
2. compiler //processor
3. executable file -> .exe -> a.exe //windows //output

/*
instruction or line or statement
# : Pre-Processor
include : Folder
<> : Tags(Predefined)
stdio : standard input output
.h : header file
; : Not Applicable

printf(): printf function


() : paranthesis
"" : Double quotes(group of characters - string)
; : instruction or line or statement

main() : main function


{ } : Curly braces(block - group of instructions)
// : Single line Comments

/*..* : Double line Comments


*/
#include<stdio.h> //instruction or line or statement
main()
{
printf("welcome"); //instruction or line or statement
printf("welcome to C\n");
}

cmd : command prompt


MISRA C : Motor Industry Software Reaability Association
\t : Tab space - Indentation(alignment or order)
void : nothing is returning (Primitive data type)
\n : new line

#include<stdio.h>

void main()
{
printf("Dennis\n");
}
1. web -> gcc for windows filehippo -> download -> install
2. Run (window+r) -> control -> Programs -> uninstall a program -> search
3. create a folder
4. in path type cmd
5. notepad
6. write the code
7. save as temp.c
8. cmd -> gcc temp.c
9. auto executable file will generate(a.exe)
10. a.exe
Task:
1. write a c-program using 10 printf functions.
Types of languages

Low level language Middle level language High level language

Low level language:

 It is fast
 Platform dependent
 In this language there is no need of translation
 It has little bit of more memory

Middle level language:

 Faster
 Platform dependent

High level language:

 Equally faster
 Platform independent

BCPL: Basic computer programming language

B has 4bytes

C has 2bytes

Program: Set of instructions is called program.

Compiler: Converting high level language into low level language


editor:

1. notepad

2. notepad++

3. IDE

4. Linux

OS:

1. Android

2. IoS

3. Windows

4. Blackberry
Programming Languages[C, C++, C#, Java, .net, Python..etc]

1. Standalone (Platform dependent)

2. Web (Platform independent)

Compilation Process:

Source file

Preprocessor

Expanded code
Compiler

Assembler code

Assembler

Object file

Object file Object file


Linker

Executable file(a.exe)

Compilation process

Preprocessor(#): It will translate the code.

Compiler: Converting human readable language to machine language.

Assembler: Assembler is a program that converts assembly level language to machine level
language.
Linker: A linker takes one or more object files generated by a compiler and combines them
into a single executable file, library file or another object file.

IDE: Integrated Development Environment

 Editor notepad
 Compiler Translation of high level to low level language
 Execution Loading program from hard disc to RAM
 Debugger Analyzing the applications

SDLC : Software Development Life Cycle


Compiler – gcc

Execution – (a.exe)

Header file – (.h)

C:\MinGW\include

Source file - (.c)

Object file – (.o)

.o

.o Libraries

.o

gcc: GNU is ‘c’ compiler

GNU: It is an organization where they develop open tools

GNU- NOT UNIX

GCC – GNU C Compiler

Compilation Process or stages:

Source file(test.c)

1. Preprocessor -> Expanded code //gcc -E test.c -o stage1_prep.I


2. Compiler -> Assembly code //gcc -S stage1_prep.I -o stage2_Cmp.S

3. Assembler -> Object files //gcc -C stage2_Cmp.S -o stage3_Asm.O

4. Linker //gcc test.c -o output.exe

Executable file(.exe)

Variable: A value which can change variable during program execution is called variable.

Expression: Set of operators and operands is called expression.

Ex: V1*V2

* Operator

V1&V2 Operands

Statement: One complete or full instruction is called statement.

Ex: V1=10; Statement

V1=10 Expression

Types of statements:

1. Simple statement
2. Compound statement
3. Null statement
1. Simple statement: It has only one statement

Ex : {

V1=10;

2. Compound statement: It has two or more statement

Ex: {

V1=10;

V2=20;

}
2. Null statement: It has zero statements

C PROGRAMMING

C language is structure/procedure oriented, high level programming language developed at


Bell laboratories in 1972 by DENNIS RITCHIE.

C TOKENS:

C tokens are of 6 types

1. Keywords

2. Identifiers

3. Constants

4. Strings

5. Special symbols

6. Operators

1. KEYWORDS:

Keywords are the predefined words in a C compiler. Each keyword is meant to perform a
specific function in a C program.

 There are 32 keywords.

2. IDENTIFIER: Each program elements in a C program are given a name called identifiers.

RULES OF IDENTIFIER:

1. Start with any alphabet or (-)

2. Should not be a keyword.

3. Should be 32 characters.

4. No special symbols.

3. CONSTANT: A value which can’t change variable during program execution is called
constant.
CONSTANTS

Numeric Character String

Integer Real/Float

Binary (0, 1)

Octal (%o) (0-7)

Decimal (%d) (0-9)

Hexadecimal (%x) (0-9, A-F)

Character: Any character within ‘a’, ‘1’, ‘$’

String: Any character within “a” = a\o //\o : NULL character

Number systems:

bin 0 and 1

oct 0 to 7

dec 0 to 9

hex 0 to 9 and A to F

Number system

bin 0 to 1

ex_1 : 0 //bit

ex_2 : 0110 //nibble

ex_3 : 0000 0001 //byte = 2 nibbles = 8bits //1B = 8 bits = character = 'A'
oct 0 to 7

ex: 01237

dec 0 to 9

ex: 01346794877383749373873983

hex 0 to 9 and A to F

ex: 01AF BCA0

Tasks:

1. Write examples for invalid Number systems

DATA TYPES: Allocation of memory to variables

Types Bytes

1. Char 1 byte

2. Int 2 or 4 bytes

3. Float 4 bytes

4. Double 8 bytes

Size Qualifiers: Short, long

Ex: Int - 4bytes

Short int - 2bytes

Long double - 10bytes

Sign Qualifiers: Signed, Unsigned


Int value;

Signed int value;

Unsigned int value;

Class programs

1. Write a C program of basic data type instructions.

#include<stdio.h>

int main ( )

int integer type;

float float type;

double double type;

char chartype;

Printf (“ sizeof(int) “);

Printf (“ sizeof(char) “);

Printf (“ sizeof(float) “);

Printf (“ sizeof(double) “);

Printf (“ sizeof(short int) “);

Printf (“ sizeof(long double) “);

Printf (“ sizeof(long int) “);

Printf (“ sizeof(signed int) “);

Printf (“ sizeof(unsigned int) “);

return 0;

2. Write a C program for 1byte character.


#include<stdio.h>

int main( )

char ch;

ch=100;

Printf(“ %d\n”, ch);

Printf(“%c\n”, ch);

return 0;

ASCII: American Standard Code Information Interchange

Char ASCII
0 48
1 49
. .
. .
. .
. .
A 65
. .
. .
. .
. .
Z 90
. .
. .
. .
. .
a 97
. .
. .
. .
z 122
Character Range:

Bits Unsigned Signed

0000 0000 0 0

0111 1111 127 127

1000 0000 128 -128

1000 0001 129 -127

1111 1110 254 -2

1111 1111 255 -1

Unsigned: 0 to 2^n – 1
Signed: -2^(n-1) to 2^(n-1) – 1
n is the number of bits

CLASS PROGRAMS

1. Write a C program for signed qualifier.


#include<stdio.h>

Main()

Char ch;

Ch=100;

Printf(“%d\n”,ch);

Ch=300;

Printf(“%d\n”,ch);

Ch=150;

Printf(“%d\n”,ch);

Ch=400;

Printf(“%d\n”,ch);

Ch=1000;

Printf(“%d\n”,ch);

Return 0;

2. Write a C program for unsigned qualifier.


#include<stdio.h>

Main()

{
unsigned char;

Ch=100;

Printf(“%d\n”,ch);

Ch=300;

Printf(“%d\n”,ch);

Ch=150;

Printf(“%d\n”,ch);

Ch=400;

Printf(“%d\n”,ch);

Ch=1000;

Printf(“%d\n”,ch);

Return 0;

S. KARUNAKAR

Definition: Allocating memory to the variable

Declaration: Using already allocated memory

Initialization: Allocating memory + assigning values

Assignment: Assigning RHS value to the LHS variable

1) Write a C program to add two numbers.


Program:

#include<stdio.h>

void main ()

{
int v1,v2;

int sum; //declaration

v1=10; //assignment

v2=20; //assignment

Sum=v1+v2; //assignment

printf(“value of sum is %d\n”, sum);

2) Multiplication of two variables when range is exceeded.


#include<stdio.h>

void main( )

short int v1,v2;

short int sum;

v1=0x123;

v2=0x123;

sum= v1+v2;

printf(“%d”,sum);

Operators:
1. Arithmetic operators
2. Assignment operators
3. Increment Decrement operators
4. Relational operator
5. Logical or Boolean operators
6. Conditional operator
7. Comma operator
8. Size of() operator
9. Bitwise operator
10. Implicit/Explicit
1. Arithmetic operators : ( +, -, *, /, %)

Program:

#include<stdio.h>

void main ( )

int v1, v2;

int sum, mul, div, per;

sum= v1+v2;

mul= v1*v2;

div= v1/v2;

per= v1%v2;

printf(“value of sum is %d\n”, sum);

2. Assignment operators:(=, +=, -=, *=, /=, %=)

Program:

#include<stdio.h>

void main( )

int a, b, sum, mul, div, per;

a= 10;

b= 20;

a= a+b;

sum += var1; \\ sum = sum + var1;


sum= (a+=b); // sum = (a = (a+b))

sub= (a-=b);

mul= (a*=b);

div= (a%=b);

printf(“%d %d %d %d %d”, a, sum, mul, div, per);

3. Increment and Decrement:(++, --)

Types:

 Pre increment (++a)


 Post increment (a++)
 Pre decrement (--a)
 Post decrement (a--)

Program:

#include<stdio.h>

void main( )

int v1,v2,v3,v4,v5;

v1= 10;

v2= v1++;

v3= (++v1);

v4= v1--;

v5= (--v1);

printf(“%d %d %d %d”, v2,v3,v4,v5);

}
4. Relational operators: (<, <=, >, >=, ==, !=)

Program:

#include<stdio.h>

void main( )

int v1,v2;

int result;

v1= 10;

v2= 20;

result= (v1<v2);

printf(“%d”, result);

result= (v1<=v2);

printf(“%d”, result);

result= (v1>v2);

printf(“%d”, result);

result= (v1>=v2);

printf(“%d”, result);

result= (v1==v2);

printf(“%d”, result);

result= (v1!=v2);

printf(“%d”, result);

}
k.sai harshitha

Logical operator: logical operators are used for combining multiple expressions in a single
expression.

Example:
#include<stdio.h>

void main()

int v1,v2,v3;

int result;

v1=10,v2=30,v3=25; //assigning the values to v1,v2,v3//

result=(v1<v2)&&(v2<v3); //in this (AND) operation if expression1 is false then the


expression 2 is not Evaluated//

printf(“\n %d”,result);

result=(v1<v2)||(v2<v3); // in OR exp1 is true then the exp2 is evaluated//

Printf(“\n %d”,result);

result=(v1<v2)&&(v2=40);

printf(“\n %d”,result); // print the result//

Conditional operators: conditional operators are used for single statements either true or false.

Example:
#include<stdio.h>

Void main()

{
int v1,v2,v3; //assigning the values to v1,v2,v3//

int result;

v1=10,v2=30,v3=25;

result=(v1<v2)? v2:v1; // the result is stored in v2//

Printf(“\n result:%d”, result);

result=(v1>v2)? v1:v2; // the result is stored in v1//

printf(“\n result:%d”, result);

Comma operator: comma operator is used to combine the multiple statements to a single
statement.

Example:
#include<stdio.h>

void main()

int v1,v2; //assigning the values to v1,v2//

int result;

result= (v1=10,v2=30,v1+v2);

printf(“\n result:%d”, result);

Implicit operator: Here ,we are declaring required data types.


int v1=10,v2=20;

float result;

result=v1/v2; //float = int;

Explicit operator: Here, we are explicitly converting v1/v2 variables into float.
int v1,v2;

float result;
result= (float ) v1/v2;

Example1:
#include<stdio.h>

void main()

Int v1,v2;

int result;

V1=10; //assigning the values to v1,v2//

V2=3;

result=v1/v2;

printf(“%d/n”,result); .......in this case result will be 3

Example2:
#include<stdio.h>

void main()

float v2 result;

V1=10;

V2=3; //assigning the values to v1,v2//

result=v1/v2;

printf(“%d/n”,result); .....in this case result will be 3.33

}
Table:
Numerator Denominator Result
Integer integer integer
Integer float Float
Float integer Float
Float float Float

Example3:
#include<stdio.h>

Void main()

Float result;

Result =10/3;

Printf(“%d/n”,result); .....in this case result will be 3.000

Float result;

result=10/3.0;

Printf(“%d/n”,result); ......in this case result will be 3.33

result=10.0/3;

Print(“%d/n”,result); .....in this case result will be 3.33

Result=10.0/3.0;

Printf(“%d/n”,result); .....in this case result will be 3.33

}
L.ROOPAVATHI

BITWISE OPERATORS

DEFINITION: Bitwise operators are used to perform logical operations (AND, OR, X-OR,
NOT) and shift operations (right-shift and left-shift) on single bit.

The truth table for logical operations is as follows:

A B AND OR X-OR
0 0 0 0 1
0 1 0 1 0
1 0 0 1 0
1 1 1 1 1

Logical AND:
The Logical AND operation is used to check the condition between two values or
variables, the result will be zero if any one of the input is zero and the result will be with high
inputs i.e. 1.

The following examples explains the operation of logical AND.

#include<stdio.h>

Int main() // execution starts //

Int v1,v2,result; // declaration of variables//

v1=10, v2=20; // initialising v1 and v2//

result = (v1&v2);

printf(“\n logical AND:%d”, result);

}
Logical OR: The logical OR operator is used to check the condition between two values or
variables, the result will be high if any one of the input is high i.e. 1.

The following examples explains the operation of logical OR.

#include<stdio.h>

Int main() // execution starts //

Int v1,v2,result; // declaration of variables//

v1=10, v2=20; // initialising v1 and v2//

result = (v1||v2);

printf(“\n logical OR:%d”, result);

X-OR: The Logical X-OR operation is used to check the condition between two values or
variables, the result will be zero if both the inputs are same.

The following examples explains the operation of logical X-OR.

#include<stdio.h>

Int main() // execution starts //

Int v1,v2,result; // declaration of variables//

v1=10, v2=20; // initialising v1 and v2//

result = (v1^v2);

printf(“\n logical OR:%d”, result);

}
Left-shift operator: The left-shift operator is used to shift values to left until overflows.
Formulae: result= value*2^n

Where n = number of bits

The following examples explains the left-shift operation

#include<stdio.h>

Int main() // execution starts //

Int v1,result; // declaration of variables//

v1=10; // initialising v1//

result = (v1<<2); // v1 is shifted to L.H.S for 2-bits

printf(“\n leftshift:%d”, result);

Right-shift operator: The right-shift operator is used to shift values to right until it
overflows. In case of odd numbers the fractional number will be truncated.

Formulae: result= value/2^n

Where n = number of bits

The following examples explains the left-shift operation

#include<stdio.h>

Int main () // execution starts //

int v1, result; // declaration of variables//

v1=10; // initializing v1//


result = (v1>>2); // v1 is shifted to RHS for 2-bits

printf(“\n leftshift:%d”, result)

K.SHIVANI

Bitwise complement operator

Introduction: The compliment operator is explained as whenever the input is high then the
output will be zero, similarly when the input is low then the output is zero.

The following example can be explained better

#include<stdio.h>

Void main()

Int v1=10; //assigning value of v1=10//

Int result;

Result =~v1; //complement of v1//

Printf(“%d\n”,result);

DESCRIPTION: V1=10

Converting the v1=10 to binary

V1=10=0000 0000 …………0000 1010 //int size is 4byte so 32 bit range//

1111 1111 …………1111 0101 //result =~v1.so, complementing v1 value//

//Msb bit=1, so the given number is –ve, so we have to do the 2’s complement//

0000 0000…………..0000 1010 //1’s complement//

1 //adding 1 to 1’s complement is 2’s


complement//
0000 0000…………. . 0000 1011 //2’scomplement of ~v1//

Output of above one is -11 //because of msb bit =1, we get –ve sign in output//

Precedence:-In this operators are in different priorities those are higher priority, lower
priority. It always chooses the higher priority.

Example:-
#include<stdio.h>

Void main()

Int result=20;

Result+=5*3;

Printf(“%d\n”,result);

} //output=28//

Type casting: - Conversion of data from one data type to another data type either implicitly
or explicitly.

#include<stdio.h>

Void main()

Float result1,v1=20,v2=3;

result1= (float) 20/3;

printf(“%f\n”,result1); //

result2=20/ (float)3;

printf(“%f\n”,result2);

Ex:2
#include<stdio.h>

Void main()

Char ch1=200;

Unsigned char ch2;

Ch2=(unsigned char ch1);

Printf(“%d%d\n”,ch1,ch2);

Output:-56,200;

Ex:2 for signed int

#include<stdio.h>

Void main ()

Signed int v1=35000;

Unsigned int v2;

V2 = (unsigned int) v1;

Printf(“%d%d\n”,v1,v2);

NAME: P. Srilatha
CONDITIONAL STATEMENTS

 Expressional statements will perform different computations depending on whether a


programmer specified Boolean expression is true or false.
 Expressional statements are two types.

1. If expressional statement
a. If
b. If – else
c. Else – if ladder/Nested if
2. Switch expressional statement

If expressional statement: If the expression is true, set of statements within if block will be
executed. If the expression is false, statements within if block will not be executed and control
will be transferred to next statement.
Syntax: if(expression){
Statements;
}

Condi
t-ion

Condition block

Next Set of statements

If – Else expressional statement: If the expression is true, set of statements with


in if block will be executed. If the expression is false, the set of statements within
else block will be executed.
Syntax: if(expression){
Statements;
}
else
{
Statements; }

Else – If ladder expressional statement: If 1stexpression is true, set of statements


within if block will be executed. If 1 stexpression is false, 2ndexpression will be
executed. If 2ndexpression is true, set of statements within else – if block will be
executed. If 2ndexpression is false, 3ndexpression will be executed. If 3rdexpression
is true, set of statements within next else – if block will be executed. This process
continues till the last expression. If the last expression is false, control will come
out of the block and next statement will be executed.
Syntax:If(expression1){
Statements;
}
else if(expression2){
statements;
}
elseif(expression3){
statements;
}
.. . . . . ….
else if(expression N){
statements;
}
Condi Condi Condi
-- tion2 tion3
tion1

Statement `1 Statement `2 Statement `3


Statement `4

Next set of statement


Program1:
//Example program for if conditional statement//
#include<stdio.h>
int main(){
int value
printf(“enter a value\n”);
scanf(“”%d”,&value);
if(value>0)
printf(“value is positive\n”);
printf(“end of the program\n”);
return 0;
}

Input: enter a value


10
Output: value is positive.
end of the program.
Input: enter a value
-10
Output: end of the program

Program 2:
//Example program for if-else conditional statement//
#include<stdio.h>
int main(){
int value
printf(“enter a value\n”);
scanf(“”%d”,&value);
if(value>0)
printf(“value is positive\n”);
else
printf(“value is negative”);
return 0;
}

Input: enter a value


10
Output: value is positive
Input: enter a value
-10
Output: value is negative

Program4:

//Even number / Odd number


#include<stdio.h>
int main(){
int value, rem;
printf(“enter a value”);
sacnf(“%d”,&value);
rem=value%2;
if(rem==0)
printf(“value is even”);
else
printf(“value is odd’);
return 0;
}
Input: enter a value
4
Output: value is even
Input: enter a value
3
Output: value is odd

Program 5:

#include<stdio.h>
int main(){
if(20)
printf(“20\n”);
if(-20)
printf(“-20\n”);
else
printf(“not -20\n”);
if(0)
printf(“zero\n”);
else
printf(“not zero\n”);
return 0;
}

Output: 20
Not -20
Not zero
Program 6:

#include<stdio.h>
int main(){
unsignedint v1;
v1=5*20-120;
if(v1<0);
printf(“-ve number”);
else
printf(“+ve number”);
if(v1>0);
printf(“+ve number”);
else
printf(“-ve number”);
printf(“%d\n”,v1);
return 0;
}

Output: +ve number


+ve number
-20

Program 7:

//Even number /Odd number with and operator


#include<stdio.h>
int main(){
int v1;
printf(“enter v1 value”);
scanf(“%d”,&v1);

res=v1&1;
if(res==1)
printf(“odd number”);
else
printf(“even number”);
return 0;
}
Input: enter v1 value
3
Output: odd number
Or
#include<stdio.h>
int main(){
int v1;
printf(“enter v1 value”);
scanf(“%d”,&v1);
res=v1&1;
if(res==0)
printf(“even number”);
else
printf(“odd number”);
return 0;
}
Input: enter v1 value
3
Output: odd number

Switch conditional statement :


Program 8:

#include<stdio.h>
int main(){
int v1;
printf(“enter v1 value”);
scanf(“%d”,&v1);
switch(value){
case 10:
printf(“10\n”);
break;//if this break statement is not given,output:10 20//
case 20:
printf(“20\n”);
break;
default:
printrf(“neither 10 nor 20”);
break;
}
return 0;
}

Input: enter value


10
Output: 10

Program 9:

#include<stdio.h>
int main(){
int v1;
printf(“enter v1 value”);
scanf(“%d”,&v1);
switch(value){
case 10:
printf(“10\n”);
case 20:
printf(“20\n”);
default:
printrf(“neither 10 nor 20”);
break;
}
return 0;
}

Input:10
Output:10
20
Neither 10 nor 20
Program 10

#include<stdio.h>
int main(){
int v1;
printf(“enter v1 value”);
scanf(“%d”,&v1);
switch(value){
default:
printrf(“neither 10 nor 20”);
break;
case 10:
printf(“10\n”);
break;
case 20:
printf(“20\n”);
break;
}
return 0;
}

Input: Enter a value


10
Output: 10

Note:
 Placement of default does not effect the output of the program.
 Absence of break will continue until break (or) until end of switch
statement
 Default is option in switch conditional statement
 We can give character, int data type as switch values. We cannot
givefloat, string as switch values.

Program 11:
#include<stdio.h>
int main(){
int v1=10,v2=20,v3=30;
if((v1<v2)||(v3=40)
printf(“%d\n%d\n%d\n”,v1,v2,v3);
if((v1<v2)&&(v3=40)
printf(“%d\n%d\n%d\n”,v1,v2,v3);
return 0;
}

Output: 10
20
30
10
20
40

Program 12:

#include<stdio.h>
int main(){
if(0)
Printf(“20\n”);
else
if(10)
Printf(“20\n”);
else
printf(“not 10\n”);
return 0;
}

Output:10

Program 13:
#include<stdio.h>
int main(){
if(10)
printf(“10\n”);
else
printf(“1:not 10\n”);
printf(“2:not 10\n”);
return 0;
}

Output: 10
2:not 10

Classwork programs
Total 8
N.PRASHANTH

REPETATIVE OR ITERATIVE OR LOOP STATEMENTS

 Loop statements are used to repeat the process again and again.

Loop statements

For While Do while

1. For: It is for known number of iterations.

Syntax: for (Initialization; condition; updated expression)

Initialization

F
?

Set of statements

Updated
expression

Next set of
statements
2. While: It is for unknown number of iterations.
F

?
T

Set of statements

Syntax: while (exp) {


…….
Next set……..
of
……..
statements
}

3. Do while: It is for to execute at least one process.

Syntax: do {
…….
……..
……..
} while (exp)

Flow chart

Set of statements

?
F

Next statement
Class programs

1) For:
#include<stdio.h>
Void main ( )
{
Int v1;
For (v1=1;v1<=10;++v1)
Printf(“%d”,v1);
}

2) #include<stdio.h>
Void main ( )
{
Int v1;
For (v1=1;v1<=10;++v1)
Printf(“%d”,v1);
Printf(“%d”,v1);
}

3) While:
#include<stdio.h>
Void main ( )
{
Int v1;
v1=10;
printf(“while loop”);
While (v1<=10)
{
Printf(“%d \n”,v1);
v1++;
}
}

4) Do while:
#include<stdio.h>

Void main ( )

Int v1;

Printf(“do while”);

V1=1;

Do{

Printf(“%d \n”,v1);

V1++;

}while(v1<=10);

Printf(“\n”);

5) Write a program to print even numbers upto 100.

Using for loop :

#include<stdio.h>

Void main ( )
{
Int v1,rem;
Printf(“even numbers between 1 &100”);
For (v1=1;v1<=100;v1++)
{
Rem=v1%2;
If(rem==0)
Printf(“%d \n”,v1);
}
}

Using while loop:


#include<stdio.h>
Void main ( )
{
Int v1,rem;
V1=1;
Printf(“while loop”);
While(v1<=100)

Rem=v1%2;

If(rem==0)

Printf(“%d \n”,v1);

6) #include<stdio.h>
Void main( )
{
Short int v1=0;
For( ;v1>=0;v1++);
Printf(“%d \n”,v1);
}
Output : -32768

7) Using comma operator:


#include<stdio.h>
Void main( )
{
Int v1,v2;
For(v1=1,v2=20;v1<v2;v1++,v2--)
Printf(“%d\n %d\n”,v1,v2);
}

8) Prime number:
 Divisible by 1 and itself.
 1,2,3,4,……..n.
 Number of times you got reminder 0.
 If number is divisible by two times then it is a prime number.

Algorithm:
 Accept a number from user.
 Divide number by 1.
 Take reminder.
 If reminder is 0 increment count.
 Repeat steps 2 to 4 until number.
 If count is 2 then it is prime number.
 If count is not !2 then it is not prime number.
 End of the program.

Program:
#include<stdio.h>
Void main( )
{
Int v1, divisor, counter, rem;
Printf(“enter number”);
Scanf(“%d”,&v1);
Divisor=1;
Counter=0;
While(divisor<=v1)
{
Rem=v1%divisor;
If(rem==0)
Counter++;
Divisor++;
}
If(counter==2)
Printf(“prime number”);
else
Printf(“not prime number”);
}

Classroom Programs Total


8

P. Rajesh Date-29/01/2018
Embedded_1

Nested loop

Algorithm:

1.Any loop with in any loop

2.Any number of levels

Syntax:-

For(condition){

For(condition){

For(condition){

..........

...........//statements

............

 Example:

#include<stdio.h>

Void main()

Int v1,v2,v3;

For(val1=1;val1<=5;val1++)

For(val2=6;val2<=10;val2++)

For(val3=11;val3<=15;val3++)
{

Printf(“%d\n%d\n%d\n”,val1,val2,val3);

Output:

1,6,11

1,6,12

1,6,13

1,6,14

1,6,15

1,7,11

 Example2:

#includde<stdio.h>

Int main()

For(printf(“A”);printf(“B”);printf(“c”))

Sleep(1);

Printf(“D”);

Output:

A,B,D,C,B,D,C,B,D,C,B,D,C.....

 Loop control statements:

1.Break
2.Continue

 Break: End of compilation, no need to further. Ie.,comes out of the loop.

Continue: Ignore current iteration but proceed with next iteration.

 Example1:

#include<stdio.h>

Int main()

Int v1=16;

If(v1>3)

Printf(“%d\n”,v1);

Break;

return 0;

Output: Error

From above example we can use break in conditional statements.

Example Syntax:

While(condition)

Printf(“A statement”);

If(condition)

Printf(“B statement”);

If(condition)
{

Printf(“C statement”);

Break;

Printf(“D statement”);

Printf(“E statement”);

From above example it iterates loop and comes out of inner loop.

 Example2:

#include<stdio.h>

Int main()

Int start, end, rem, prime, num;

Printf(“enter any value”)

Scanf(“%d”,&num);

Printf(“%d\n”,num);

Start=2;

end=num/2;

prime=1;

while(start<=end)

Rem=num%start;

If(rem==0)

Prime=0;
Break;

Start++;

If (prime==1)

Printf(“not a prime);

else

printf(“is a prime number”);

 Example3:

#include<stdio.h>

Int main()

Int num, sum;

Sum=0;

Printf(“enter the numbers(end with 0):”);

Scanf(“%d”,&num);

While(num!=0)

If (num>0)

Sum+=num;

Printf(“enter the number(end with 0):”);

Scanf(“%d”,&num);

}
Printf(“%d\n”,sum);

 Example4:

#include<stdio.h>

Int main()

Int sum,num;

Sum=0;

do

Printf(“enter a value”);

Scanf(“%d”,&num);

If(num>0)

Sum+=num;

While(num!=0)

Printf(“%d\n”, sum);

note:- from example 3 and 4 we can notice that, by using do -while loop we can reduce our
program.

 Example4:

#include<stdio.h>

Int main()
{

Int num ,sum;

Sum=0;

do

Printf(“enter a value”);

Scanf(“%d”,&num);

If(num==0)

Break;

If(num<0)

Continue;

Sum+=num;

While(1);

Printf(“%d\n”,sum);

................................................................................................................................

Classroom Programs Total


7

K.LAKSHMAN
FUNCTIONS

A function is self -contained sub program that performs some specific and well defined task.
Every c program consists at least one function that is main( ).It is first function to be executed
when the program starts, all other functions are called eithter directly or indirectly for main( ).

Main( ) function has only two return types: int and void.

Advantages of functions

 The use of functions modularizes and divides the work of a program


 The program becomes easily understandable,modifiable and easy to debug and test

C programs have two types of functions

 Library functions
 User-defined functions

Library functions

The C standard library provides numerous built-in functions that your program can call. For
example, sqrt ( )is a mathematical library function which is used to find square root of a
number, memcpy () to copy one memory location to another location, and many more
functions.

Ex:printf(),scanf()

User-defined functions

Programmers can create their own functions for performing any specific task of program

Every function has 3 parts

 Function declaration
 Function definition
 Function call

Function Declaration
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts

return_type function_name( parameter list );


Function declaration is required when you define a function in one source file and you
call that function in another file. In such case, you should declare the function at the top of the
file calling the function.

Functional declaration is optional i.e, a function without a declaration has to be defined before it
is called.

Function Definition
The general form of a function definition in C programming language is as follows

return_type function_name( parameter list )

body of the function

A function definition in C programming consists of a function header and a function body.

Calling a Function

While creating a C function, you give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task.

When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement is executed or
when its function-ending closing brace is reached, it returns the program control back to the
main program.

To call a function, you simply need to pass the required parameters along with the
function name, and if the function returns a value, then you can store the returned value.

Function

input Processing output


 Not every function requires input or output
 Function can also be defined without any input or output
 For a program with many functions (main function not necessarily at the beginning)
execution start at main and compilation starts at first line of the program.
Main ()function

Every C program has a primary (main) function that must be named main.

. The main function serves as the starting point for program execution. It usually


controls program execution by directing the calls to other functions in the program. A
program usually stops executing at the end of main, although it can terminate at other
points in the program for a variety of reasons. At times, perhaps when a certain error is
detected, you may want to force the termination of a program.

Main function is declared in the “stdio” header file.

It is defined by the user. The program we write is the definition of the main() function.

Main function is called by the operating system.

Syntax

main( int argc, char *argv[ ], char *envp[ ] )

printf() and scanf() functions are present in the library. The files related to them are
libc.aarchive and static library
libc.soshared object or dynamic library
The alternate math library, `libm.a', provides versions of mathematical functions which
comply to several different standards of behavior in abnormal cases, and are sometimes more
accurate than those included in the default `libc.a' library.

N. SOUJANYA

FUNCTIONS

Function: A function is a self contained subprogram that performs some specific,


Well defined task.
Or
A processing unit that process statements.
ADVANTAGES OF FUNCTIONS:
 To reduce the length of the program.
 To avoid repetation of the code.
 Code reusability.
TYPES OF FUNCTIONS:

1. Library functions.
2. User-Defined functions.

1. Library functions:

Library functions are also called as Pre-defined functions or built in functions. These
functions are defined by system. These functions can have specific meaning, that meaning
provided by the system.

Ex: sqrt( ), scanf( ), printf( ).......etc.

2. User-Defined functions:

These functions can be defined by user for performing any specific task of the program.

To create and use these functions, user should know about three parts:

1. Function definition.

2. Function declaration.

3. Function call.

1. Function definition:

It consists of whole description and code of a function. It has two parts- a function header
and a function body.

Syntax:

returntype fun_name( parameter declaration)


{
------------
------------
return (expression);
}
2. Function declaration:
A function declaration is used to give specific information to the compiler about the
function.
Syntax:
return_type fun_name( parameter declaration)
{
-----------
-----------
}
int main( )
{
------------
fun_name(arguments);
------------
}
3. Function call:

A function is called by simply writing its name followed by the argument list inside the
parenthesis.
Syntax:
func_name(arg1,arg2,arg3………);
Categories of functions into four types depending on the return value and arguments.
1. Functions with no arguments and no return value.
2. Functions with no arguments but a return value.
3. Functions with arguments but no return value.
4. Functions with arguments and return value.
1. functions with no arguments and no return value:

Syntax:

void func(void);
int main(void)
{
--------------
---------------
func( );
--------------
}
void func(void)
{
-----------
-----------
}

2. functions with no arguments but a return value:

syntax:

int func(void);
int main(void)
{
--------------
---------------
func( );
--------------
return 0;

}
int func(void)
{
-----------
return expression;
}

3. Functions with arguments but no return value:

syntax:

void func( int, int );


int main(void)
{
--------------
func( a, b);
--------------
return 0;

}
void func( int c, int d )
{
-----------
-----------
}
4. functions with arguments and return value:

syntax:

int func( int, int );


int main(void)
{
--------------
func( a, b);
--------------
return 0;

}
int func( int c, int d )
{
-----------
return expression;
}

Example program: 1
no arguments and no return value:
#include<stdio.h>
void first_ten_primes( );
int main( )
{
first_ten_primes( );
return 0;
}
void first_ten_primes( )
{
int counter ,isprime, start, end, num, rem ;
printf(“first ten primes\n”);
while(counter<10)
{
isprime=0;
end=num/2;
start=2;
while(start<=end)
{
rem = num % start;
if( rem==0)
{
isprime=0;
break;
}
else
{
isprime = 1;
}
start++;
}
if(isprime==1)
{
counter++;
printf(“%d\t”,num);
}
num++;
}
}

program: 2
no arguments but a return value:
#include<stdio.h>
int main( )
{
int res;
res= my_random_num( );
printf(“%d\n”,res);
return 0;
}
int my_random_num( )
{
int num ;
num=rand( );
num+=2;
return num;
}

program: 3
with arguments but no return value:
#include<stdio.h>
Void fibo_series(int count);
int main( )
{
int res;
res= my_random_num( );
printf(“%d\n”,res);
return 0;
}
int my_random_num( )
{
int num ;
num=rand( );
num+=2;
return num;
}

program: 4
with arguments with return value:
#include<stdio.h>
int main( )
{
int nth_num, res;
printf(“enter prime number of required location\n”);
scanf(“%d”,&nth_num);
res=nth_prime_number(nth_num);
printf(“%d”,res);
return 0;
}
int nth_prime_number(int nth_num )
{
int nth_num,c1=0, c=0, rem, i=1, v1;
printf(“enter nth number”);
scanf(“%d”,nth_num);
for(v1=1;v1!=0;v1++)
{
for(i=1;i<=v1;i++)
{
num=v1%i;
if(rem==0)
++c;
}
if(c==2)
c1++;
c=0;
if(c1==nth_num){
res=v1;
break;
}
}
return res;
}

Class Room Programs Total


4

S.Pravalika

STORAGE CLASSES
There are 3 types
1. Automatic storage class:

Auto is the default storage class for all local variables.


Ex:
{
int count;
auto int month;
}
The above example defines two variables with same storage class. Auto can only be used with in
functions.i.e.local variables.
2. Register-storage class:

Register is used to define local variables that should be stored in a register instead of RAM.
This means that the variable has a maximum size equal to the register size
Ex:
{
register int Miles;
}
Register should only be used for variables that require quick access-such as counters. It should also be
noted that defining 'register'.

3. static-storage class:

Static is the default storage class for global variables. The two variables below both have static
storage class
Ex:
static int count;
int road;
{
printf("%d\n",road);
}

Static can also be defined with in a function. If this is done the variable is initialized at run time but is not
reinitialized when the function is called. This inside a function static variable retains its value during
various calls.
Ex:
void func(void)
static count=10; /*Global variable-static is the default */
main()
{
while(count--)
{
Func ();
}
}
Void func (void)
{
Static i=5;
i++;
printf ("i is %d and count is %d\n",i,count);
}
Result:
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0

Note:

Here key word void means function does not return anything and it does not take any parameter. You can
memoriese void as nothing .Static variables are initialized to 0 automatically.

4. Extern-storage class:

Extern is used to give a reference of a global variable that is visible to all the program files. When
you use 'extern' the variable cannot be initialized as all it does is point the variable
Or function. Just for understanding, extern is used to declare global variable or function in another files.

Ex:

File 1:main.c
int count=5;
man()
{
write_extern();
}
File2:write.c
void write_extern(void);
extern int count;
void write_extern(void)
{
printf("count is %i\n",count);
}

Here extern is keyword

Storage class scope life time initial value

1. Automatic block block garbage value


2. Register block block garbage value
3. Static
[a] local block external
program 0
[b] Global program program 0
4. Extern external
program program 0
Examples of storage classes:
Class programs:

1. Write a program for auto storage class

#include<stdio.h>
int main()
{
int v1;
v1=5;
{
int v1;
v1=10;
printf("%d",v1);
{
int v1;
v1=20;
printf("%d",v1);
}
}
}

output:
66
67
68
~
2. Check a program is there any error

#include<stdio.h>
void myfunc();
int main()
{
myfunc();
myfunc();
myfunc();
printf("%d%d\n",v1,v2);
}
void myfunc()
{
int v1=5;
static int v2=5;
v1++;
v2++;
printf("%d%d\n",v1,v2);
return;
}
~
output:
error
note: each undeclared identifier is reported only once for each function it appears

3.write a program for static storage class(local variables)


~
#include<stdio.h>
static int v1;
void myfunc1();
void myfunc2();
void myfunc3();
int main()
{
myfunc1();
myfunc2();
myfunc3();
return 0;
}
void myfunc1()
{
//int v2;
v1=v1*2;
printf("%d",v1);
return;
}
void myfunc2()
{
v1=v1*3;
printf("%d",v1);
return;
}
void myfunc3()
{
v1=v1*4;
printf("%d",v1);
return;
}
output:
0
0
0
0
Note:initial value of storage classes is '0'
~
4.write a program for static classes(global variables)

~ #include<stdio.h>
static int v1;
void myfunc1();
void myfunc2();
void myfunc3();
int main()
{
myfunc1 ();
myfunc2 ();
myfunc3 ();
return 0;
}
Void myfunc1 ()
{
//int v2;
v1=v1+2;
Printf ("%d",v1);
return;
}
void myfunc2()
{
v1=v1*3;
printf("%d",v1);
return;
}
void myfunc3()
{
v1=v1*4;
printf("%d",v1);
return;
}
output:
2
6
2
4
~
5.write a program for static variables

#include<stdio.h>
static int v1;
void myfunc1();
void myfunc2();
void myfunc3();
int main()
{
myfunc1();
myfunc2();
myfunc3();
return 0;
}
void myfunc1()
{
int v1=5;
v1=v1+2;
printf("%d",v1);
return;
}
void myfunc2()
{
v1=v1+3;
printf("%d",v1);
return;
}
void myfunc3()
{
v1=v1*4;
printf("%d",v1);
return;
}
output:
7
3
12

6.write a program for static variable

#include<stdio.h>
int v1;
void myfunc1();
void myfunc2();
void myfunc3();
int main()
{
myfunc1();
myfunc2();
myfunc3();
return 0;
}
void myfunc1()
{
v1=v1+2;
printf("%d",v1);
return;
}
void myfunc2()
{
v1=v1+3;
printf("%d",v1);
return;
}
extern int v1;
void myfunc3()
{
v1=v1*4;
printf("%d",v1);
return;
}
output:
2
5
20

7.write a program for static sorage classes

#include<stdio.h>
int v1;
void myfunc1();
void myfunc2();
void myfunc3();
int main()
{
myfunc1();
myfunc2();
myfunc3();
return 0;
}
void myfunc1()
{
int v1=5;
v1=v1+2;
printf("%d",v1);
return;
}
void myfunc2()
{
v1=v1+3;
printf("%d",v1);
return;
}
extern int v1;
void myfunc3()
{
v1=v1*4;
printf("%d",v1);
return;
}

output:
7
3
12
8.//file name as global_test1.c
#include<stdio.h>
int v1;
void myfunc1();
void myfunc2();
int main()
{
myfunc1();
myfunc2();
myfunc3();
return 0;
}
void myfunc1()
{
int v1=5;
v1=v1+2;
printf("%d",v1);
return;
}
void myfunc2()
{
v1=v1+3;
printf("%d",v1);
return;
}

//file name as global_test2.c


#include<stdio.h>
extern int v1;
void myfunc3();
void main(){
void myfunc3();
}
void myfunc3()
{
v1=v1*4;
printf("%d",v1);
return;
}
compile this two files as "gcc global_test1.c global_test2.c
o/p: 7 3 12

Classroom Programs Total


10
MD ANKUSHAVALI
DATE:06-02-2018
RECURSION

Recursion is a powerful technique of writing a complicated algorithm in an easy way.


Accordingto this technique a problem is defined in terms of itself. The problem is solved by dividing it
into smaller problems, whichare similar in nature to the original problem. These smaller problems are
solved their solutions are applied to get the final solution of our original problem.
To implement recursion technique in programming, a function should be capable of calling
itselfthis facility is available in C.

For example:
main()
{
..........
rec ( ) ;
.........
}
rec( )
{
.........
...........
rec( ); --------recursive call
..............
}

Before writing a recursive function for aproblem we should consider these points
1. We should be able to define the solution of theproblem in terms of a similar type of smaller problem.
At each step we get closer to' the final' solution of our original problem.
2. There should be a terminating condition to stop recursion.

Program : Factorial by using recursion


#include<stdio.h>
int main()
{
intnum,res;
printf(“enter the number:”);
scanf(“%d”,&num);
res=fact_recursion(num)
printf(“%d”,res);
}
intfact_recursion(intnum)
{
int res=1;
if (num==1)
return res;
else
res=num*fact_recursion(num-1);
retunn res;
}

Input:5
Output:120
Program : Printing the numbers

#include<stdio.h>
void print_numbers(intnum);
intmain()
{
intnum;
printf(“enter a num:”);
scanf(“%d”,&num);
printf_numbers(intnum);
return 0;
}
void print_numbers(intnum)
{
if(num==0)
return;
print_num(num-1); //interchange these two lines and check
printf(“%d”,num); //the output
return;
}
Output:
5,1
2
3
4
5

ENUM (Enumeration)
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to
integral constants, the names make a program easy to read and maintain.
// an example program to demonstrate working
// of enum in C
#include<stdio.h>

enumweek{Mon, Tue, Wed, Thur, Fri, Sat, Sun};

Int main ()
{
Enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Bitwise operators Significance

Bit Operator Bit Result


X & 1 X
X | 1 1
X ^ 1 X’

Setting a single bit


#include<stdio.h>
Short intset_bit(int pos);
Int main()
{
Short int va1,res;
V1=0x4567;
Res=Short intset_bit (int pos); Return 0;
}
Short intset_bit(int pos)
{
Res=val|(1<<pos);
Return res;
}

Clearing a single bit


Res=val&(~(1<<pos))
Complementing a single bit
Use XOR (^)
Check the status
AND operation with 1

No of Class room programs Total


7 7

S.SHESHUKUMAR DATE 7:02:2018

LINUX BASIC CAMMANDS:


1 /bin

Unlike /sbin, the bin directory contains several useful commands that are of use to both the
system administrator as well as non-privileged users. It usually contains the shells like bash, csh,
etc. and commonly used commands like cp, mv, rm, cat, ls.

2 /lib

The /lib directory contains kernel modules and those shared library needed to boot the system
and run the commands in the root filesystem, ie. by binaries in /bin and /sbin.

3 cd .

Current directory

4 cd ..

Parent directory

5 ls-l

list with long format - show permissions

6 ls

ls is a Linux shell command that lists directory contents of files and directories.

7 ls- |wc-l

wc command to count the number of lines, words, and bytes in the files specified by the File
parameter.

8 $ cd

a command-line OS shell command used to change the current working directory in operating
systems 

9 cd ~

To go to home directory

10 cd ~directoryname

To go directly existing directory

11 $ head file.txt

It opens the file and shown on the screen


12 $ head –n5.file.txt

It open the file(n5- with only 5 lines from head).

13 $ tail file.txt

It open the file from buttom.

14 $ ls-file.txt

File is an argument

15 $ ls-file1.txt file2.txt

File with multiple arguments

16 $ ls/bin |more

It shows the number of files

17 $ ls/bin |page

18 cat<binaryfiles.txt

Apand the data

19 cat>>file.txt:To append (add data to existing) data to a file called file.txt

20 $ echo”sbin files”>binaryfiles.txt

Truncated already existing file. If the file does not exist it create the file.

NAME: B.BALA JYOTHI LINUX COMMANDS

When you create a program, three files are created by default. They are
1. Standerd input(0)

2. Standerd output(1)

3. Standerd error(2)

META CHARECTERS: *? Are Meta characters

$touch file1.txt file2.txt file3.txt

$touch file12.txt file23.txt file31.txt

$touch file123.txt file321.txt

$touch file 12.tmp

$ ls file*.txt -> displays all files

$ ls file1*.txt -> displays file12.txt ,file 1.txt,file123.txt

$ ls -l file12* ->which displays file123.txt,file 12.tmp,file12.txt

ls -l file123 * . txt –> displays file123.txt

ls -l file?.txt ->displays file1.txt file2.txt file3.txt

ls -l file?? .txt –> displays file12.txt file23.txt file31.txt

ls -l file???.txt -> file123.txt file321.txt

$ ls /bin/a* // list of command starts with ‘a’

$ ls /bin //shows all commands .

$ ls /bin / a* > bin-witha. txt //output of ‘ls/bin/a*’ is directed to ‘bin-witha.txt’

$ ls / bin /b * 1 > bin-with b.txt // output of ‘ls / bin /b *’ is directed to ‘bin-with b.txt’

$ ls *.txt>txt-file.txt //gives all txt files to txt-file.txt

$ ls *py (ensure there is no py files to displayed as out)

$ ls*.py >error_py.txt //error because “no such files are there”&we are
trying to give

it through Std.out(2)

$ ls*.py2>error_py.txt //’no such files are there’ is displayed in error_py.txt


$ ls*.txt*.py1>txt_file.txt2>error_py.txt

//Here 1&2are the file descriptive id for standard input and standard
output

(discripter id’s 012)

Whenever we open a files the discripter is ‘3’

When we close, close(std .in) or

close(0)

LINKS:

There are two types of links:

1. Hard Link

2. Soft Link

HARD LINK:

It will link to the inode

INODE: Itwill give the information of file

->used to store the file

->will not suppot with in the file system

->same inode numbers

SOFT LINK:

->different inode numbers

->across file system

->linked to file

Hard link:

$ mkdir links-txt //created directory

$ cd links-txt //opened directory

$ vi file1.txt //opened file1.txt and write text in file1.txt


$ ln file1.txt file1_link.txt //created hard link. Ensure that ‘file1_link.txt’ file is not there
before .

$ cat file1.txt //displays content in file1.txt

$cat file1_link.txt // displays content in file1_link.txt

$ls -i file1.txt //displays inode number of file1.txt

$ls -i file1_link.txt //displays inode number of file1_link.txt

$ rm file1.txt //removes file1.txt

$ cat file1_link.txt //we can see the content in file1_link.txt

SOFT LINK:

$vi file1.txt // open file1.txt and write text in the file

$ ln -s file1.txt file2_link.txt //created hard link. Ensure that ‘file2_link.txt’ file is not there
before .

$ cat file1.txt //displays content in file1.txt

$cat file2_link.txt // displays content in file2_link.txt

$ls -i file1.txt //displays inode number of file1.txt

$ls -i file2_link.txt //displays inode number of file2_link.txt

$ rm file1.txt //removes file1.txt

$ cat file2_link.txt //we can not see the content in file2_link.txt

K.PRAVEEN KUMAR Linux commands:

Home

Jagruthi
Linux samples

permissions

$vi file1.txt

The above command shows the creation of file and opens, to write data into file in EDIT mode.

$ls –l

The above command gives the information about file1.txt i.e. no of lines in file1, is it directory
or file.? , last modified time, date and permissions of that file.

-rw-rw-r-- 1 praveen007 praveen007 216 Feb 10 14:32

user ID user name Date Last modified time

$touch file1.txt

Touch command creates an empty file, If file is already created then it will open .

Permissions:

 rw- rw- r--

Directory,/Files user group others

Types of files:

1.Normal file----------------------------------------------------------

2.Directory (d) user/owner(u) group others

3.Charactor (c)

4.Block (b)

Permissions can be changed through

1. Symbols

2. Numbers

1. Symbols:
(+) Add permissios.

(-) Remove permission.

$chmod u-r file1.txt

Read permission for user is removed.

$ls -l file1.txt

The permission changes from -rw-rw-r-- to --w- rw- r--

$chmod u+r file1.txt

Giving read permission to user.

$ls -l file1.txt

Again the permission changes from --w- rw- r-- to -rw- rw- r--

$chmod ugo+r file1.txt

Giving read permission to user ,group and others.

$ls file1.txt

We see like this -rw- rw- r--

$chmod ug+x file1.txt

Giving execution permission to user and group.

$ls -l file1.txt

We see like this -rwxrwxr--

$chmod u-x,g-w

Removing execution permission to user and write permission to group.

$ls -l file1.txt

We see like this -rw-r--r--

2.Number

r w x

4 2 1
r---read

w---write

x---execute

$chmod 664 file1.txt

$ls -l file1.txt

We see like this -rw- rw- r--

$chmod 775 file1.txt

$ls -l -lfile1.txt

We see like -rwxrwxr-x

Changing permissions through numbers is not preferred, because there is a high probability of
getting error. which is not acceptable in bigger applications.

$vi helloworld.c

Creating helloworld file and opining it.

$ls -l helloworld.c

We see like this -rw-rw-r--

$gcc helloworld.c

$ls -l a.out

We see like this -rwxrwxr-x

$./a.out

helloworld

$chmod u-x a.out

$./a.out

Permission denied.

$mkdir temp1

$ cp file1.txt temp1/myfile1.txt
We are copying the data from file1.txt to myfile1.txt in new directory temp1.

$cd temp1

$cat myfile.txt

Above command is used to display the data in COMMAND window which is there in myfile.txt

$cd ..

$ls -l

We see like this -rwxrwxr-x

$chmod u-x temp1

We are removing execution permission to user.

$cd temp1

Permission denied

$chmod u-r temp1

We are removing read permission to user.(It goes to directory but it not shows any content.)

In Directory:

 When read permission is removed.

It doesn’t allow ‘ls’ command.

 When write permission is removed.

‘Touch’ command not allowed.

 When execute permission is removed.

‘Cd’ command not allowed.

$umask

000?

0-octal

0-owner

0-group
?-others

By default the umask has a number as ‘0002’

The minimum and maximum range of file is 000 to 666.

T he minimum and maximum range of directory is 000 to 777.

$md5sum file1.txt

It checks file integrity, it gives 128 bit no. It is like finger print to that file or directory.

B.VAMSHI KRISHNA

ARRAYS
DEFINITION:
An array is a collection of similar data type items and each data item is called as an
element of an array.
 An array contains any valid data type like char, int or float.
 Each element has different index number known as “subscript”.
 An array can be single dimensional or multi dimensional. The number of subscripts
determines the dimensions of array.

Syntax for declaration an array:

Data type array name[size];

Ex: int age[100];

Here age is array of type int, which can store 100 elements of type int.

Syntax for initialization of an array:

Data type array name[size]={val1,val2,.....}

Ex: int marks[5]={50,85,70,65,95}

The values of array elements after this initialization is


marks[0]=50, marks[1]=85, marks[2]=70, marks[3]=65, marks[4]=95

Note:

If we enter the elements more than the size, The application will be crashed.

Example programs:

 Short int sints[5];

int myints[5]; 0 1 2 3 4

Printf(“%ld %ld\n”,size of(sints),size of(myints)); 1000 1002 1004 1006 1008

Output:
size of (sints)=10
size of (myints)=20

 Short int sints[5]={10,20,30,40,50};


int count;
for(count=0;count<5;count++)
{
Printf(“%p %d\n”,&sints[count],sints[count]); 0 1 2 3 4
10 20 30 40 50
} 1000 1002 1004 1006 1008

Output:
&sints[0]=1000 sints[0]=10
&sints[1]=1002 sints[1]=20
&sints[2]=1004 sints[2]=30
&sints[3]=1006 sints[3]=40
&sints[4]=1008 sints[4]=50

 int myints[6],count;
printf(“%d\n”,size of(myints));
for(count=0;count<6;count++)
{ 0 1 2 3 4 5

1 2 3 4 5 6
myints[count]=(count+1); 1000 1004 1008 1012 1016 1020

for(count=0;count<6;count++)

{
Printf(“%d\n”,myints[count]);
}

Output:
size of (myints)=24
myints[0]=1
myints[1]=2
myints[2]=3
myints[3]=4
myints[4]=5
myints[5]=6

user input:

 int sints[5],count;
printf(“enter elements into array\n”);
for(count=0;count<5;count++)
{ 0 1 2 3 4

1 2 3 4 5
Printf(“enter element %d”,count+1); 2000 2004 2008 2012 2016

Scanf(“%d”,&sints[count]);
}
for(count=0;count<5;count++)
{
Printf(“%d”,sints[count]);
}

Output:
Enter elements into array
enter element 1
enter element 2
enter element 3
enter element 4
enter element 5
sints[5]={1,2,3,4,5}

 short int sints[5]={10,20,30,40,50};


int count,sum=0;
for(count=0;count<5;count++)
{ 0 1 2 3 4

10 20 30 40 50
Sum+=sints[count]; 3000 3002 3004 3006 3008

}
Printf(“%d\n”,sum);

Output:
Sum=150

 short int sints[9];


int count,value=2;
for(count=0;count<9;count++)
{
Sints[count]=value; 0 1 2 3 4 5 6 7 8
2 4 6 8 10 12 14 16 18
Value+=2; 1000 1002 1004 1006 1008 1010 1012 1014 1016

}
Printf(“%d\n”,value);
for(count=0;count<9;count++)
{
Printf(“%d\n”,sints[count]);
}

Output:
Value=22
sints[9]={2,4,6,8,10,12,14,16,18}
 short int sints[5],jint[5];

int count,value=10;

for(count=0;count<5;count++)

{ sints[4] : 0 1 2 3 4

10 20 30 40 50
Sints[count]=value; 1000 1002 1004 1006 1008

Value+=10;
} jints[4]: 0 1 2 3 4

10 20 30 40 50
for(count=0;count<5;count++) 2000 2002 2004 2006 2008

{
jints[count]=sints[count];
Printf(“%d %d\n”,sints[count],jints[count]);
}
Output:
sints[5]={10,20,30,40,50}
jints[5]={10,20,30,40,50}

Class Room Programs Total


7
Nothing like easy or hard, it’s just a matter you feel about it
Gayithri surishetty

12-2-2018.

Syntax for array: data types val_name [limit] ;

 Char mychars[10]; // char=1byte,limit=10 1*10=10 bytes //

0 1 2 3.........................................9

10 20 30 40 50 0 0 0 0 0

 Int myints[ ]; // syntax error //


 Int myints[ ]={10,20,30,40,50}; // int=4bytes,array limit =5

4*5=20 bytes //

 Int myints[20]={1,2,3} // int=4bytes,array size=20

4*20=80bytes //

 Int myint[20]={0} // int =4bytes,array size=20

4*20=80bytes //

Eg : char mystr[10];

Char value;

Value=’a’;

For (count=0; count<5;count++) assigning

Mystr [count] =value;

Value++;

Mystr [count] =’\0’;


Char mystr[10];

Printf(“enter string: “):

Scanf(“%S”,&mystr[0]); (or) scanf(“%S”,mystr);

Printf(“%S”,mystr); user inputs

Gets ( )

Puts ( )

Char mystr1[10]={‘a’, ‘b’, ‘c’}; initialisation

(Or)

Char mystr2 [10]= “abcdef”; // 10bytes........if you are not initialising null

Character filled by default //

Char mystr3 [ ]= “abcdefgh” // total 9 =8 string characters+1 null character

Char mystr4 [ ]; // syntax error //

Char mysrt5 [6] = “abcdef”; //total 6 bytes

String Header file:


string.h
Built in Functions:
strlen() : Calculates the length of the string
strcpy() : Copies one string to another string
strcat() :Appends one string to another string

strcmp() :Compares one string with another


Str1 abcde abcde abCde
Str2 abCde abcde Abcde
Strcmp(str1,str2) 1(>0) 0 -1(<0)
gets() :alternative for scanf()
puts() :alternative for printf()
#include<stdio.h>
#include<string.h>
int main()
{
int mystrlen,cmp_val;
char mystr1[20]="abcde";
char mystr2[20];
char mystr3[20];

strcpy(mystr2,mystr1);

printf("%s\n",mystr1);
printf("%s\n",mystr2);

mystrlen=strlen(mystr2);

printf("%d\n",mystrlen);
strcat(mystr3,mystr1);
printf("%s\n",mystr3);
strcpy(mystr2,"ABCDE");
strcat(mystr3,mystr2);
printf("%s\n",mystr3);
cmp_val=strcmp(mystr3,mystr2);
printf("%d\n",cmp_val);
return 0;
}
Output:
abcde
abcde
5
abcde
abcdeABCDE
-49
Class Room Programs Total
6

SOMETIMES BY LOSING A BATTLE, YOU WILL FIND ANOTHER WAY TO WIN THE
WAR
B.RAMYA

ARRAYS (1D, 2D with Functions)

PROGRAM 1:

#include<stdio.h>
int sum_array_elem(int v1[],int);
void main()
{
int array_elem[]={10,20,30,40,50};
int num_elem,elem;
num_elem=sizeof(array_elem)/sizeof(int);
sum_array_elem(array_elem,num_elem);
printf(“%d\n”,sum_elem);
}
void sum_array_elem(int myarray[],int count)
{
int elem,sum=0;
for(elem=0;elem<count;elem++)
sum=myarray[elem];
return sum;
}

OUTPUT: 150

Program 2:

#include<stdio.h>
Void sum_array_elem(int v1[],int );
Void main()
{
int array_elem[]={10,20,30,40,50};
int num_elem,elem;
num_elem=sizeof(array_elem)/sizeof(int);
sum_elem=sum_array_elem(array_elem,num_elem);
for(elem=0;elem<5;elem++)
printf(“%d”,array_elem[elem]);
}
int sum_array_elem(int myarray[],int count)
{
int elem,mul=1;
for(elem=0;elem<count;elem++){
myarray=mul*10;
mul++;
}
}
2dimensional arrays:

Program1:

//2 D array with initialization


#include<stdio.h>
int main(){
int i,j;
int array[2][3]={{1,2,3},{4,5,6}};
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf(“%d”,array[i][j]);
}printf(“\n”);
}
}
Output:
123
456

Program2:
//2 D array with user input
#include<stdio.h>
int main(){
int r,c,i,j;
printf(“enter rows and columns respectively”);
scanf(“%d%d”,r,c);
int array[r][c];
printf(“enter array elements”);
for(i=0;i<r;i++){
for(j=0;j<c;j++){
scanf(“%d”,&array[i][j]);
}
}
}
for(i=0;i<r;i++){
for(j=0;j<c;j++){
printf(“%d”,&array[i][j]);
}printf(“\n”);
}
}
Output:
enter rows and columns respectively:3
3
Enter array elements123456789
123
456
789

Program3:
//2 D array with assignment
#include<stdio.h>
int main(){
int i,j,v1=1;
int array[2][3];
for(i=0;i<2;i++){
for(j=0;j<3;j++){
array[i][j]=v1;
v1++;
}
}
for(i=0;i<2;i++){
for(j=0;j<3;j++){
printf(“%d”,array[i][j]);
}printf(“\n”);
}
}

Output:
123
456

Class Room Programs Total


5

V Srikanth

Disadvantage of Arrays:
 Suppose if we allocated 200 elements only 150 elements are using and rest 50 are wasted.
 Suppose if we allocated 200 elements we need 250 elements to be stored. Then how?

Insertion:

 Check where to create an empty space.


0 1 2 3 4 5 9

10 20 3 40 50 6  -
0 0

 From right, move by one location to create space.


0 1 2 3 4 5 9

10 20 3 40 50 6  -
0 0

 Now space is available so fill the value.


0 1 2 3 4 5 9

10 20 30 40 50  -

Deletion:

 Check for which location value to be deleted.


0 1 2 3 4 5 9

10 20 3 40 50 6  -
0 0

 From that position move elements left by one location. That element is no more.
0 1 2 3 4 5 9

10 20 3 40 50 6  -
0 0

 Resultant is:
0 1 2 3 4 5 9
10 20 4 50 60  -
0

How to avoid these problems?


These problems can be resolved by using Pointers, Dynamic Memory Allocation(DMA),
Returning multiple values from function and with efficiency.

By using pointers:

Pointers:
Pointer is named because it points to a particular location in memory by storing the address of
that location.

Syntax : data_type *pname;

Advantages: It stores

 Address of any variable.


 Address of function.
 Address of another pointer.
 Address of array

Operators used in pointer operation are ‘&’ and ‘*’.

& - which returns the address of a variable when placed before it.
*- Asterisk preceding this name informs the compiler that the variable is declared as pointer.
Sample Program:

#inlcude<stdio.h>
Int main()
{
int *iptr;
int v1;
v1=10;
iptr=&v1;
printf(“%p,%d\n”,&v1,v1);
printf(“%p,%d\n”,iptr,*iptr);
printf(“%p\n”,&iptr);
printf(“%p\n”,*(&iptr));
return 0;
}

Output:

Address of v1,value of v1
Address of v1,value of v1
Address of pointer
Address of v1 or content of pointer(iptr)

Classroom Programs Total


1
POINTERS
P.SRI LATHA

POINTER: pointer is a variable that stores the address of another variable.

Program 1:
#include<stdio.h>
int main()
{
int val=10,*iptr;
char ch='a',*chptr;
short int val1=100,*sptr;
float val2=14.5,*fptr;
double val3=14.6,*dbptr;
iptr=&val;
chptr=&ch;
sptr=&val1;
fptr=&val2;
dbptr=&val3;
printf("%ld %ld\n",sizeof(iptr),sizeof(*iptr));
printf("%ld %ld\n",sizeof(chptr),sizeof(*chptr));
printf("%ld %ld\n",sizeof(sptr),sizeof(*sptr));
printf("%ld %ld\n",sizeof(fptr),sizeof(*fptr));
printf("%ld %ld\n",sizeof(dbptr),sizeof(*dbptr));
}

O/P:
84
81
82
84
88

Program 2:
#include<stdio.h>
int main()
{
char charry[5]="abcde",*chptr;
int arry1[5]={10,20,30,40},*iptr;
chptr=&charry[0];
iptr=&arry1;
printf("%s %c\n",charry,*chptr);
printf("%p %p\n",&charry,chptr);
printf("%d\n",*iptr);
printf("%p %p\n",&arry1,iptr);
iptr++;
chptr++;
dprintf("%c\n",*chptr);
printf("%p %p\n",&charry,chptr);
printf("%d\n",*iptr);
printf("%p %p\n",&arry1,iptr);
}

O/P:
abcde a
0x7ffc83776c90 0x7ffc83776c90
10
0x7ffc83776c70 0x7ffc83776c70
b
0x7ffc83776c90 0x7ffc83776c91
20
0x7ffc83776c70 0x7ffc83776c74

DOUBLE POINTER: pointer that store addres of another pointer variable.

Program:
#include<stdio.h>
int main()
{
int v1=100,*iptr,**diptr,***tiptr;
iptr=&v1;
diptr=&iptr;
tiptr=&diptr;
printf("%d %d %d %d\n",v1,*iptr,**diptr,***tiptr);
printf("%p %p %p %p\n",&v1,iptr,*diptr,**tiptr);
printf("%p %p %p\n",&iptr,diptr,*tiptr);
printf("%p %p\n",&diptr,tiptr);
printf("%p\n",&tiptr);
}

O/P:
100 100 100 100
0x7ffcea88ac04 0x7ffcea88ac04 0x7ffcea88ac04 0x7ffcea88ac04
0x7ffcea88ac08 0x7ffcea88ac08 0x7ffcea88ac08
0x7ffcea88ac10 0x7ffcea88ac10
0x7ffcea88ac18
Classroom Programs Total
3

K.SHIVANI

Arithmetic operations on pointers:-

Class programs:

program1:

int main()

int myarray[]={10,20,30...}

int *iptr1=myarray;

int *iptr2;

iptr1=iptr+5;

printf(“\n %d %p”,*iptr1,iptr1);

iptr1=iptr1-2;

printf(“\n %p %d”,iptr1,*iptr1);

iptr1=myarray;

iptr2=&myarray[5];

value=iptr2-iptr1;

printf(“\n %d”,value);

Valid condition:

 Increment(++) and decrement(--) operations.


 Add a number to a pointer.
 Subtract a number from pointer.
 Difference of two pointers of same datatype.
Not valid conditions:

 Multiplication by number
 Divide by number
 Adding sum float to pointer.
 Adding two pointers.
Ex:

Int myarray[]={10,20,25,30,35};
Int num_ele,index;
Num_elements=sizeof(myarray)/sizeof(int);
For(index=0;index<numelements;index++)
Printf(“%p %p %p %p”,&myarray[index],&index[myarray],(myarray+index),
(index+myarray));

Void pointer:

Ex:

Int ival=10,*iptr;

Float fval=20.235,*fptr,res;

Void *vptr;

Iptr=&ival;

Printf(“\n %p %d”,iptr,*iptr);

Vptr=fptr;

Iptr=vptr;

Res=*(float *)vptr;

Vptr=iptr;

Int res=*(int *)vptr;

Classroom Programs Total


3
Pointer to an array
A. AKHIL

We can declare a pointer that can point to a whole array instead of only one element of an
array. It can be used in both single and multi-dimensional arrays.

Example1:

#include<stdio.h>

int main( )

int (*ptrArray)[4]; /* it will point to whole array */ //int (*ptr)[]; //valid

intmy_array[4]={10,20,30,40};

ptrArray=&my_array; /*here & is used to point to whole array*/

printf(“%p,%p\n”,ptrArray,my_array);

ptrArray++;

printf(“%p\n”,ptrArray);

printf(“%d\n”,sizeof(*ptrArray));

return 0;

Output:

0x000000000024FE30, 0x000000000024FE30

0x000000000024FE40

16
Example2:

#include<stdio.h>

int main( )

int (*ptrarray)[4]; /*it will point to an array of 4 elements*/

int my2darray[3][4]={{10,20,30,40},{1,2,3,4},{15,25,35,45}};

ptrarray=my2darray;/* points to entire 0th row*/

printf(“%p,%d”,ptrarray,(*ptrarray)[0]);

ptrarray++;

printf(“%p,%d”,ptrarray,(*ptrarray)[0]);

printf(“%p,%d”,*(my2darray+2)+0, *(*(my2darray+2)+0));

/* syntax for referring to an element in 2Darray using array pointer is


*(*(array_name+row)+column)*/

return 0;

Output:

000000000024FE10,10

000000000024FE20,1

000000000024FE30,15

Classroom Programs Total

1
Increment or decrement operation using pointers
CH. HARIKRISHNA

Precedence of * operator and increment /decrement operator’s is same and associatively


from right to left.

#include<stdio.h>
int main()
{
int v1=25,v2=50;
int *ptr=&v1;
ptr++;
ptr=&v2;
ptr--;
v1=*ptr++;
printf(“%d %d\n”,v1,*ptr);
v1=*ptr--;
printf(“%d %d\n”,v1,*ptr);
v1=*++ptr;
printf(“%d %d\n”,v1,*ptr);
v1=*--ptr;
printf(“%d %d\n”,v1,*ptr);
v1=++*ptr;
printf(“%d %d\n”,v1,*ptr);
v1=--*ptr;
printf(“%d %d\n”,v1,*ptr);
v1=(*ptr)++;
printf(“%d %d\n”,v1,*ptr);
v1=(*ptr)--;
printf(“%d %d\n”,v1,*ptr);
return 0;
}
Output:
25 50
50 50
50 50
50 50
51 51
50 50
50 50
50 50

Call by reference
#include<stdio.h>

void swap(int *, int *);

int main()

int v1=10, v2=20;

swap(&v1, &v2);

printf("%d\t%d\n",v1, v2);

return 0;

void swap(int *v1, int *v2)

int temp;
temp = *v1;

*v1 = *v2;

*v2 = temp;

Output:
v1 is 10 v2 is 20
v1 is 20 v2 is 10
Example: Call by value and call by reference

#include<stdio.h>
void myfcn(int val1,int *val2);
int main()
{
int v1,v2;
v1=10;
v2=20;
myfcn(v1,&v2);
printf("%d\t%d",v1,v2);
return 0;
}
void myfcn(int val1,int *val2)
{
val1++;
(*val2)++;
printf("%d\t%d\n",val1,*val2);
return;
}
Output:
val1 is 11 val2 is 21
v1 is 10 v2 is 21
Classroom Programs Total
3

ARAISE, AWAKE AND STOP NOT TILL THE GOAL IS REACHED


-Swami Vivekananda

S. Sheshukumar A. Praveen Kumar


S. Karunakar

Array of pointers
We can declare an array that contains pointers as its elements.

Example:

#include<stdio.h>

int main()

int v1=10,v2=20,v3;

int myarr[5]={1,2,3,4,5};

int *arrptr[3];

arrptr[0]=&v1;

arrptr[1]=myarr;

arrptr[2]=&v2;

printf("%p\t%d\t%p\n",*arrptr[0],arrptr[1],*arrptr[2]);

printf(“Printing arrey elements\n”);

for(v3=0;v3<5;v3++)

Printf(“%d\t”,arrptr[1][v3]);
}

Output:

000000000000000A 2424368 0000000000000014

Printing array elements

1 2 3 4 5

Pointer to function

The code of a function resides in memory and so every function has an address like all
other variables in the program. We can get the address of function by just writing the function’s
name without parentheses.

Example:

#include<stdio.h>

void myfcn();

int main()

void (*fp)();

myfcn();//function calling;

fp=myfcn;

(*fp)();//function calling through function pointer

void myfcn()

printf("my function\n");

}
Output:

my function

my function

Array of function pointers

Function pointer can be used in applications where we don’t know in advance which
function will be called.in that case we can take the addresses of different functions in array and
then call the appropriate function depending on some index number.

Examples 1:

#include<stdio.h>
int add(int,int);
int sub(int,int);
int mul(int,int);
int div(int,int);
int main()
{
int val,i,v1,v2;
int (*fp[4])(int,int)={add,sub,mul,div};
printf("enter v1 and v2\n");
scanf("%d%d",&v1,&v2);
for(i=0;i<4;i++)
{
val=(*fp[i])(v1,v2);
printf("%d\n",val);
}
return 0;
}
int add(int v1,int v2)
{
int res=v1+v2;
return res;
}
int sub(int v1,int v2)
{
int res=v1-v2;
return res;
}
int mul(int v1,int v2)
{
int res=v1*v1;
return res;
}
int div(int v1,int v2)
{
int res=v2/v1;
return res;
}
Output:

Enter v1 and v2

10

25

35

-15

100

2
Passing a function’s address as an argument to other function

We can send the function’s address as an argument to other function in the same way as
we send other argument. To receive the function’s address as an argument, a formal parameter of
the appropriate type should be declared.

Example:

#include<stdio.h>

void myfun1(void);

void myfun2(void);

void exec_fun(void (*fptr)());

main()

void (*myfptr)();

exec_fun(myfun1);

myfptr=myfun2;

exec_fun(myfptr);

void exec_fun(void (*fptr)())

(*fptr)();

return;

void myfun1()

{
printf("In myfun 1\n");

return;

void myfun2()

printf("In my fun 2\n");

return 0;

Output:

In myfun1

In myfun2

Classroom Programs Total


7
*ALL POWER IS WITHIN U, U CAN DO ANYTHING & EVERYTHING*

A RAGHU
Dynamic Memory Allocation (DMA):
The process of allocating memory at the time of execution is called dynamic memory allocation.
The allocation and release of this memory space can be done using library functions that are
declared in stdlib.h. These functions allocate memory from a memory area called heap.
There are 4 types of DMA’s
1. malloc()
Declaration: (int *)malloc(size*sizeof(int) );
2. calloc()
Declaration: (int *)calloc(size, sizeof(int) );
3. realloc()
Declaration: (int *)realloc(void ptr, size*sizeof(int) );
4. free()
Declaration: (void) free(void *ptr)

Program-1:
Example program for malloc()

#include<stdio.h>
#include<stdlib.h>
void main()
{
int num,*ptr,i;
printf("Enter the no.of elements:\n");
scanf("%d", &num);
ptr = (int *)malloc(num*sizeof(int));
if(ptr==0) //if(ptr==NULL)
{
printf("no memory address:\n");
}
for(i=0;i<num;i++)
{
printf("Enter the value to store in index[%d]:\n", i);
scanf("%d", ptr+i);
}
for(i=0; i<num; i++)
{
printf("address[%d] is %p\t",i,(ptr+i));
printf("value of [%d] is %d\n",i, *(ptr+i));
}
}

Output:

Enter the no .of elements:


5
Enter the value to store in index[0]:
2
Enter the value to store in index[1]:
4
Enter the value to store in index[2]:
6
Enter the value to store in index[3]:
3
Enter the value to store in index[4]:
5
address [0] is 0xd4e010 value of [0] is 2
address [1] is 0xd4e014 value of [1] is 4
address [2] is 0xd4e018 value of [2] is 6
address [3] is 0xd4e01c value of [3] is 3
address [4] is 0xd4e020 value of [4] is 5

Program-2:
//Example Program for calloc() and realloc()

#include<stdio.h>
#include<stdlib.h>
void main()
{
int *ptr, i;
ptr= (int *)calloc(5,sizeof(int));
for(i=0; i<=4; i++)
{
*(ptr+i) = i*3;
printf("address of[%d] is :%p\t",i, (ptr+i));
printf("value of[%d] is :%d\n", i, *(ptr+i));
}
ptr= (int *)realloc(ptr, 9*sizeof(int));
printf("\n");
for(i=5;i<=10;i++)
{
*(ptr+i)=i*20;
printf("address of[%d] is :%p\t",i, (ptr+i));
printf("value of[%d] is :%d\n", i,*(ptr+i));
}
}
Output:

Address of [0] is 0x23af010 value of [0] is :0


Address of [1] is 0x23af014 value of [1] is :3
Address of [2] is 0x23af018 value of [2] is :6
Address of [3] is 0x23af01c value of [3] is :9
Address of [4] is 0x23af020 value of [4] is :12

Address of [5] is 0x23af024 value of [5] is :100


Address of [6] is 0x23af028 value of [6] is :120
Address of [7] is 0x23af02c value of [7] is :140
Address of [8] is 0x23af030 value of [8] is :160
Address of [9] is 0x23af034 value of [9] is :180
Address of [10] is 0x23af038 value of [10] is :200

Classroom Programs Total


2
STRUCTURES

To store different data types we can use a structure, which is capable of storing heterogeneous
data. Data of different types can be grouped together under a single name using structures.
Ex-1: Sructure declaration:
struct student //stuct is a keyword
{
char name[20];
int rollno;
float marks;
}stud1,stud2;

Ex-2: Structure Tag:


struct employee
{
char name[20];
int idno;
float salary;
};
struct employee empl;
stuct employee emp2, emp3;

Program-1:

//Example for structure

#include<stdio.h>
#include<string.h>
struct student //struct is a keyword
{
char name[20];
int rollno;
float marks;
}
void main()
{
struct student stud1={"raghu",14,50.5},stud2,stud3,stud4;//Initialization
strcpy(stud2.name, "praveen");
stud2.rollno=28;
stud2.marks=92.3;//Assignment
stud4=stud2; //assignment of structure variables or copying
printf("Enter your details name,rollno and marks:\n");
scanf("%s %d %f", stud3.name,&stud3.rollno,&stud3.marks); //user input
printf("student1 name : %s roll no :%d marks:%.2f\n",stud1.name,stud1.rollno,stud1.marks);
printf("student2 name : %s roll no :%d marks:%.2f\n",stud2.name,stud2.rollno,stud2.marks);
printf("student3 name : %s roll no :%d marks:%.2f\n",stud3.name,stud3.rollno,stud3.marks);
printf("student4 name : %s roll no :%d marks:%.2f\n",stud4.name,stud4.rollno,stud4.marks);
printf("%ld\n", sizeof(struct student));
printf("%ld\n", sizeof(stud1));
printf("%ld\n", sizeof(stud2));
printf("%ld\n", sizeof(stud3));
printf("%ld\n", sizeof(stud4));
}

Output:

Enter your details name,rollno and marks :


raghu
14
80.5
student1 name : raghu roll no :14 marks : 50.50
student2 name : praveen roll no :28 marks : 92.30
student3 name : raghu roll no :14 marks : 80.50
student4 name : praveen roll no :28 marks : 92.30
28
28
28
28
28

Classroom Programs Total


1
Good situations will give you good memories. Bad situations will teach you good lessons

STRUCTURES
P. Srilatha

Constant pointer:
#include<stdio.h>
int main()
{
int v1=10,v2=30;
int *const ptr=&v1;
printf("%p %d\n",ptr,*ptr);
ptr=&v2; //address is constant
*ptr=*ptr+1; //value is variable
printf("%p %d\n",ptr,*ptr);
}

Output: error: assignment of read only variable at ptr=&v2

Pointer to a constant:

#include<stdio.h>
int main()
{

int v1=10,v2;
int const *ptr=&v1;
printf("%p",ptr);
*ptr=v2; // value is fixed
++ptr; //address is variable
printf("%p",ptr);
printf("%d",*ptr);
}

Output: error: ead only error at *ptr=v2

Structure padding:

program:1
#include<stdio.h>
struct student
{
char ch[5];
//char padding[3];
int rollno;
};
int main()
{
struct student stu={"jews",12};
printf("%s %p\t %d %p\n",stu.ch,stu.ch,stu.rollno,&stu.rollno);
}

O/P: jews 0x7ffe78c7d480 12 0x7ffe7488

Arrays within structures:

Program 2:

#include<stdio.h>
struct stud
{
int marks[5];
int count;
};
int main()
{
int i,v1=10;
struct stud s1,s3;
s1.count=10;
for(i=0;i<5;i++)
printf("%d ",s1.marks[i]);
printf("count=%d",s1.count);
for(i=0;i<5;i++)
{
s2.marks[i]=v1;
printf("%d ",s2.marks[i]);
v1++;
}
s1.count=10;
printf("count=%d",s1.count);
printf("enter array elements");
for(i=0;i<5;i++)
scanf("%d ",&s3.marks[i]);
for(i=0;i<5;i++)
printf("%d ",s3.marks[i]);
s3.count=11;
printf("count=%d",s3.count);
}

O/P: 10 11 12 13 14 count=10 enter array elements 1 2 3 4 5


1 2 3 4 5 count=11

ARRAY OF STRUCTURE:

Program 3:

#include<stdio.h>
#include<string.h>
struct employee
{
char name[10];
int id;
float sal;
};
int main()
{
struct employee emp[2] = { {"JYOTHI",10,20000} }; //Initialization
printf("%s %d %f\n",emp[0].name,emp[0].id,emp[0].sal);
strcpy(emp[1].name,"SAHITHYA");
emp[1].id=11;
emp[1].sal=30000; // Assignment
printf("%s %d %f\n",emp[1].name,emp[1].id,emp[1].sal);
printf("enter name,id,values");
scanf("%s%d%f",emp[2].name,&emp[2].id,&emp[2].sal); //User input
printf("%s %d %f\n",emp[2].name,emp[2].id,emp[2].sal);
}

O/P: JYOTHI 10 20000.000000


SAHITHYA 11 30000.000000
enter name,id,values SRI,3,25000
SRI3 25000.000000

Nested structures:

Program 5:

#include<stdio.h>
#include<string.h>
struct date_of_birth
{
int day;
int month;
int year;
};
struct employee
{
char name[10];
int id;
float sal;
struct date_of_birth dob;
};
int main()
{
struct employee e1={"srilatha",20,20000,13,6,1996};
struct employee e2,e3;
printf("%s %d %f %d %d %d\n",e1.name,e1.id,e1.sal,e1.dob.day,e1.dob.month,e1.dob.year);
e2.dob.day=14;
e2.dob.month=7;
e2.dob.year=1997;
printf("%d %d %d\n",e2.dob.day,e2.dob.month,e2.dob.year);
printf("enter day,month,year");
scanf("%d%d%d",&e3.dob.day,&e3.dob.month,&e3.dob.year);
printf("%d %d %d\n",e3.dob.day,e3.dob.month,e3.dob.year);
}

O/P: srilatha 20 20000.000000 13 6 1996


14 7 1997
enter day,month,year 14 7 1995
14 7 1995

Program 6:

#include<stdio.h>
#include<string.h>
struct employee
{
char name[10];
int id;
float sal;
struct date_of_birth
{
int day;
int month;
int year;
}dob;
};
int main()
{
//struct date_of_birth dob;
struct employee e1={"srilatha",20,20000,13,6,1996};
struct employee e2,e3;
printf("%s %d %f %d %d %d\n",e1.name,e1.id,e1.sal,e1.dob.day,e1.dob.month,e1.dob.year);
e2.dob.day=14;
e2.dob.month=7;
e2.dob.year=1997;
printf("%d %d %d\n",e2.dob.day,e2.dob.month,e2.dob.year);
printf("enter day,month,year");
scanf("%d%d%d",&e3.dob.day,&e3.dob.month,&e3.dob.year);
printf("%d %d %d\n",e3.dob.day,e3.dob.month,e3.dob.year);
}

O/P: srilatha 20 20000.000000 13 6 1996


14 7 1997
enter day,month,year 14 7 1995
14 7 1995

POINTERS IN STRUCTURES:

Program 7:/ /pointer in structure

#include<stdio.h>
#include<string.h>
struct employee
{
char *name;
int id;
float sal;
};
int main()
{
struct employee e1;
char name1[7]="ravali";
char name2[5];
e1.name=name1;
e1.id=100;
e1.sal=1000;
printf("%s %p %d %p %f\n",e1.name,e1.name,e1.id,&e1.id,e1.sal);
e1.name=name2;
strcpy(e1.name,"jagruthi");
printf("%s %p %d %f\n",e1.name,e1.name,e1.id,e1.sal);
}

O/P: ravali 0x7ffef9fb0e10 100 0x7ffef9fb0df81000.000000


jagruthi 0x7ffef9fb0e00 100 1000.000000

Program 8: //pointer to structure

#include<stdio.h>
struct student
{
int rollno;
int class;
};
int main()
{
struct student *s1;
struct student s2={12,5};
s1=&s2;
s1->rollno=12;
(*s1).class=10;
printf("%d %d\n",(*s1).rollno,(*s1).class);
}

O/P: 12 10

Functions passing structure and returning structure:

Program 9:

#include<stdio.h>
struct student
{
int rollno;
int class;
};
struct student func_struct(struct student);
int main()
{
struct student stu1,stu2;
stu2=func_struct(stu1);
printf("%d %d\n",stu2.rollno,stu2.class);
}
struct student func_struct(struct student stu1)
{
stu1.rollno=10;
stu1.class=10;
return stu1;
}

O/P:
10 10

Function returning pointer to structure:

Program 10:

#include<stdio.h>
struct student
{
int rollno;
int class;
};
struct student *func(struct student);
int main()
{
struct student s1,*s2;
s2=func(s1);
//printf("%p",&s1);
printf("in main, addres of s2=%p",s2);
}
struct student *func(struct student s1)
{
struct student *ptr;
ptr=&s1;
printf("in func,address is %p",ptr);
return ptr;
}

O/P: in func,address is 0x7ffffd64ae80


in main,address of s2 =0x7ffffd64ae80

Classroom Programs Total


10
BIT FIELDS
V.Srikanth

  We can specify size (in bits) of structure and union members. The idea is to use memory
efficiently when we know that the value of a field or group of fields will never exceed a limit or is within
a small range.

Example: program.1

#include<stdio.h>

Struct sample{

Short int v1:4;

Short int v2:5;

Short int v3:7;

Short int v4:2;

Int main()

Struct sample s1;

Int temp;

//Scanf(“%d”,&s1.v1); which is not a valid statement because the size of variable is specified//

Scanf(“%d”,&temp); //which is a valid statement because temp is a variable of int data type//

S1.v1=temp; //we can assign a value to bit specified variables


Return0;
}
Example: program.2
#include<stdio.h>
Struct sample{
Short int v1:4;
Short int v2:5;
}
Int main()
{
Struct sample s1;
S1.v2=50;
Printf(“value in v2 =%d”,v2);
S1.v2=15;
Printf(“value in v2=%d”v2);
Return 0;
}
Output:
Value in v2= -14
Value in v2=15
UNIONS

A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a value
at any given time.

The main difference between structure and union is, Struct uses all the memory of its member
and union uses the largest member’s memory space. 

Accessing of union variable can be done by using dot (.) and arrow (->) operators.

Syntax:

union tag_name {

data type var_name1;

data type var_name2;

data type var_name3;

--

};

1).Either of the element:

Program.3

#include<stdio.h>

Union performance{

Char grade[3];

Int marks;

Float percent;

};

Int main()

Union performance p1;

Strcpy(p1.grade,”A+”);
Printf(“%s\n”,p1.grade);

P1.marks=259;

Printf(“%d\n”,p1.marks);

P1.percent=92.34;

Printf(“%f\n”,p1.percent);

Return;

Output:

A+

259

92.34

2) Different ways of retrieving same date:

Program 4.

#include<stdio.h>

Union twobytes{

Char ch[2];

Short int v1;

};

Int main()

Union twobyres _2bytes;

_2bytes.ch[0]=0x12;

_2bytes.ch[1]=0x34;

Printf(“%x\n”,ch[0]);

Printf(“%x\n”,ch[1]);

Printf(“%x\n”,v1);

Return;

Output:
12

34

1234

Pointers in UNIONS.
Pointer which stores address of union is called as pointer to union
Program.5
#include<stdio.h>
Union team{
Char name[20];
Int members;
};
Int main()
{
Union team t1,*sptr=&t1;
Strcpy(T1.name,”INDIA”);
Printf(“Team:%s\n”,(*sptr).name);
Printf(“Team:%s\n”,sptr->name);
Return;
}
Output:
Team:INDIA
Team:INDIA
Array of UNIONS
Union is a collection of different data types (variables) which are grouped together.
Whereas, array of unions is nothing but collection of unions. This is also called as union array.

Program.6

#include<stdio.h>
Union team{
Char name[20];
Int id; };
Int main()
{
Union team cand[2];
Strcpy(Cand[0].name,”ragava”);
Printf(“%s\n”,cand[0].name);
Cand[0].id=20301;
Printf(“%d\n”,cand[0].id);
Strcpy(Cand[1].name,”lawrence”);
Printf(“%s\n”,cand[1].name);
Cand[1].id=20302;
Printf(“%d\n”,cand[1].id);
return 0; }
Output:
Ragava
20301
Lawrence
20302

Classroom Programs Total


6

FILES
T.santhosh
 File handling C can be broadly categorized in two types:
 High-level Files(standard files or stream oriented files)
 Low-level Files(system oriented files)
 High-level file handling is managed by library functions.
Eg: Standard: scanf(), printf(), gets(), puts(), getchar(), putchar().
Stream oriented: fscanf(), fprintf(), fgets(), fputs().
 Low-level file handling is managed by system calls.
Eg: open(), close(), read(), write().
 Streams:
 Text stream: Stream of characters.
 Binary stream: Stream of unprocessed bytes.
 Buffer:
 Buffer is an area in memory where the data is temporarily stored being written in to file. When
we open a file, a buffer is automatically associated with its file pointer.
 When the file is closed, all the contents to buffer are automatically written to the file even if the
buffer is not full. This called flushing the buffer.
 Three types of buffers: Fully buffer, Line buffer, Unbuffer.
 Fully buffer: The data transferred only when the buffer is full.
 Line buffer: When the buffer is full or when a newline character is written to the buffer.
 Unbuffer: The data transferred as quickly as possible.
 When a file is opened, a fully buffered is a stream is attached to it. The buffering can be
changed after opening the file and before performing any operation on it using the functions
setbuf() or setvbuf().
 The steps for file operations in C programming are:
 Open a file.
 Read the file or Write data in the file.
 Close the file.

 Opening a file:
 A structure named FILE is defined in the header file stdio.h
 A file pointer (stream pointer) is a pointer to a structure of type FILE.
 Declaration: FILE *fopen(const char *filename, const char *mode);
 “w” (write): File doesn’t exist Create a new file for writing otherwise previous data is erased
and the new data entered is written to the file.
 “r” (read): File doesn’t exist terminated otherwise reading only.
 “a” (append): File doesn’t exist Create a new file otherwise the new data entered is appended at
the end of exiting data.
 “w+” (write+read): File doesn’t exist Create a new file for writing otherwise previous data is
erased and the new data entered is written to the file and read.
 “r+” (read+write): File doesn’t exist terminated otherwise reading and write.
 “a+” (append+read): File doesn’t exist Create a new file otherwise the new data entered is
appended at the end of exiting data.
 Operating files in text mode:
 “wb” Binary file opened in write.
 “ab+” or “a+b” Binary file opened in append mode.
 “rt+”or “a+t”, Text file opened in update mode.
 “w” Text file opened in write mode.
 Errors in opening Files:
 If an error occurs in opening a file, then open() returns NULL.
Eg: #include<stdio.h>
Int main()
{
FILE *fptr;
fptr=fopen(“ERROR_CHECK.txt”,”w”);
if(fptr==NULL)
{
printf(“Error in opening file:\n”);
return;
}
 Closing a File:
 The file that was opened using fopen() function must be closed when no more operations are to
be performed on it.
 Declaration: int fclose(FILE *fptr);
 fclose() returns EOF on error and 0 on success.
 EOF is constant defined in stdio.h and its value is generally -1.
 We can also close multiple files by calling a single function fcloseall(). It closes all the opened
files.
 Declaration: int fcloseall(void)
 End of File:
 The file reading functions need to know the end of file so that they can stop reading. When the
end of file is reached , the OS sends an end-of-file signal to the program.
 Structure of a File Program:
#include<stdio.h>
Int main()
{
FILE *fptr;
fptr=fopen(“filename”,”mode”);
----------------------------------------;
----------------------------------------;
----------------------------------------;
fclose(fptr);
returnd 0;
}
 Standard streams:
File pointer Stream System calls Buffering
stdin standard input 0 Line buffered
stdout standard output 1 Line buffered
stderr standard error 2 Unbuffered
The functions used for file I/O are-
 Character I/O: fgetc(), fputc(), getc(), putc().
 String I/O: fgets(), fputs().
 Formatted I/O: fscanf(), fprintf().
 Record I/O: fread(), fwrite().
---------------ooooo-------------
File Input & Output Operations
GOWTHAMI

TYPES OF I/O:

1. CHARACTER I/O (fgetc(),fputc())

2. STRING I/O ( fgets(),fputs())

3. FORMATTED I/O (fscanf(),fprintf())

4. BLOCK I/O (fread(),fwrite())

1.CHARACTER I/O:

1.fputc():

Declaration: int fputc(int c,FILE *fptr);

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("CHAR_IO.txt","w");
if(fp == NULL){
printf("error");
return;
}
printf("enter char to end cntl+d\n");
ch=getchar();
while(ch!=EOF){
fputc(ch,fp);
ch=getchar();
}
fclose(fp);
return;
}

Output: Enter char to end cntl+d\n


I like tea
I like ice-cream
2.fgetc():

Declaration: int fgetc(FILE *fptr);

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen("CHAR_IO.txt","r");
if(fp == NULL){
printf("error");
return;
}
printf("reading a char from file \n");
ch=fgetc(fp);
while(ch!=EOF){
putchar(ch);
ch=fgetc(fp);
}
fclose(fp);
return;
}
Output:I like tea
I like ice-cream

2. STRING I/O:

1. fputs():
Declaration: int fputs(const char *str,FILE *fptr);
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char str[30];
if((fptr=fopen("test","w"))==NULL)
{
printf("error in opening file\n");
// break;
exit(1);
}
printf("enter the text\n");
printf("to stop entering,press ctrl+d/ctrl+z\n");
while(gets(str)!=NULL)
fputs(str,fptr);
fclose(fptr);
return;
}
O/P:Hello world
Hello hyderabd

2. fgets():

Declaration: char *fgets(char *str, int n, FILE *fptr);


#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fptr;
char str[30];
if((fptr=fopen("test","r"))==NULL)
{
printf("error in opening file\n");
// break;
exit(1);
}
while(fgets(str,80,fptr)!=NULL)
puts(str);
fclose(fptr);
return;
}
Output: Hello world
Hello Hyderabad

3. FORMATTED I/O:

1. fprintf():

Declaration: fprintf (FILE *fptr,const char *format[,argument,…]);


#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
char name[10];
int id;
float marks;
if((fp=fopen("rec","w"))==NULL)
{
printf("error in opening file/n");
exit(1);
}
printf("enter your name,id,marks :");
scanf("%s %d %f",name,&id,&marks);
fprintf(fp,"my name is %s and id is %d and marks are %f",name,id,marks);
fclose(fp);
}
Output:enter your name,id,marks :
Thanushwi
13951a04c6
98
Thanushwi
13951a04c6
98
2. fscanf():

Declaration: fscanf(FILE *fptr,const char *format[,address,..]);

#include<stdio.h>
#include<stdlib.h>
struct student
{
char name[10];
float marks;
int rollno;
}student;
void main()
{
FILE *fp;
if((fp=fopen("student","r"))==NULL)
{
printf("error in opening file :");
exit(1);
}
printf("NAME\t MARKS\t ROLLNO\n");
while(fscanf(fp,"%s %f %d",stu.name,&stu.marks,&stu.rollno)!=EOF)
printf("%s\t %f\t %d\n",stu.name,stu.marks,stu.rollno);
fclose(fp);
}
Output: Thanushwi
13951a04c6
98
3. BLOCK I/O:

1.fread():

Declaration: size_t fread(void *ptr,size_t size_t n,FILE *fptr);

#include<stdio.h>
#include<stdlib.h>
struct record
{
char name[20];
int roll;
int marks;
};
void main()
{
struct record student;
FILE *fp;
fp=fopen("stu","r");
if(fp==NULL)
{
printf("error opening file\n");
return;
}
printf("\n NAME\tROLLNO\tMARKS\n");
while((fread(&student,sizeof(student),1,fp))==1)
{
printf("%s\n",student.name);
printf("%d\n",student.roll);
printf("%d\n",student.marks);
}
fclose(fp);
}
O/P: Thanushwi
13951a04c6
98

2.fwrite():

Declaration: size_t fwrite(const void *ptr,size_tsize,size_t n,FILE *fptr);


#include<stdio.h>
#include<stdlib.h>
struct record
{
char name[20];
int roll;
int marks;
};
void main()
{
struct record student;
int i,n;
FILE *fp;
if((fp=fopen("stu","w"))==NULL)
{
printf("error opening file\n");
exit(1);
}
printf("enter number of records :");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("enter name :");
scanf("%s",student.name);
printf("enter roll no :");
scanf("%d",&student.roll);
printf("enter marks :");
scanf("%d",&student.marks);
fwrite(&student,sizeof(student),1,fp);
}
fclose(fp);
}

O/P: Thanushwi
13951a04c6
98

Classroom Programs Total


10
RANDOM ACCESS TO A FILE
C supports following functions for random access file processing:

-fseek( )

-ftell( )

-rewind( )

-fsetpos( )

-fgetpos( )

Browsing a file in following ways:

1.Beginning

2.Current

3.From end

Constant Value Position

SEEK_SET 0 Beginning of file

SEEK_CURRENT 1 Current position

SEEK_END 2 End of file

/*program to understand fseek*/

#include<stdio.h>

Struct record

Char name[20];

Int roll;

Int marks;
}student;

Void main( )

Int n;

FILE *fp;

Fp=fopen(“stu”,”rb”)_;

If(fp==NULL)

Printf(“error in opening file \n”);

Exit(1);

Printf(“enter the number of records to be read :”);

Scanf(“%d”,&n);

fseek(fp,(n-1)*sizeof(student),0);

fread(&student, sizeof(student),1,fp);

Printf(“%s\t”, student.name);

Printf(“%d\t”, student.roll);

Printf(“%d\t”, student.marks);

fclose(fp);

ftell( ): long ftell(FILE *fptr);

 This function returns the current position of the file.


Rewind( ): void rewind(FILE *fptr);

 This function is used to move the file position.


Ferror( ): int ferror(FILE *fptr);
 This function is for detecting any error.

PREPROCESSOR
 Replacing header file
 Removing comments
 Macro substitution
 Problems with macros
 Generic functionality
 Conditional compilation
 Built in variables for debugging purpose
 Debugging

Replacing header file:

#include<stdio.h> System defined

#include “myfile.h” User defined

Removing comments:

/*

/*

comments Nested comments

*/

*/

Macro substitution:

Class programs:

Program 1:

#include<stdio.h>
#define sum(v1,v2) v1+v2
#define mul(v1,v2) (v1)*(v2)
int main()
{
int res;
res=sum(3*4,5*6);
printf("%d\n",res); output:42
res=mul(3+4,5+6); 77
printf("%d\n",res);

}
Program 2:

#include<stdio.h>
#define MY_SWAP(DTYPE,v1,v2)\
{\
DTYPE temp;\
temp=v1;\
v1=v2;\
v2=temp;\
}
int main()
{
int v1=10,v2=20;
char ch1='a',ch2='b';
float v3=12.34,v4=34.123;
MY_SWAP(int,v1,v2);
printf("%d %d\n",v1,v2);output:20,10
MY_SWAP(char,ch1,ch2);b,a
printf("%c %c\n",ch1,ch2);34.123,12.34
MY_SWAP(float,v3,v4);
printf("%f %f\n",v3,v4);
return 0;
}

Compilation process:

 $gcc filewrite.c -o filewrite


 $ ./filewrite
 $ gcc filewrite.c -o fileread
 $ ./fileread
 $ gcc -E filename.c -o filename.I
 $ gcc -S filename.c
 $ gcc -c filename.s
 $ gcc filename.o

Classroom Programs Total


3
MULTI-LINE MACRO STRINGING OPERATOR TOKEN
PASSING OPERATOR DEBUGGING LEVELS
Macros Vs. Functions :

The overhead of functions in general is difficult i.e. copying all the local variables and
return addresses every time but in macros it will be replaced by a single line.

1.MULTI – LINE MACRO:

PROGRAM:

#include<stdio.h>

#define myswap(DTYPE,v1,v2)\

{DTYPE temp;\

temp=v1;\

v1=v2;\

v2=temp;\

}\

void main()

int v1=10,v2=20;

char ch1='a',ch2='d';

printf("before swap int variables are v1=%d,v2=%d\n",v1,v2);

myswap(int,v1,v2);

printf("after swap int variables are v1=%d,v2=%d\n",v1,v2);

printf("\n\n\n\n");

printf("before swap char variables are ch1=%c,ch2=%c\n",ch1,ch2);

myswap(char,ch1,ch2);
printf("after swap char variables are ch1=%c,ch2=%c\n",ch1,ch2);

OUTPUT:

before swap int variables are v1=10,v2=20

after swap int variables are v1=20,v2=10

before swap char variables are ch1=a,ch2=d

after swap char variables are ch1=d,ch2=a

Generic function :

Macro can be used to generate functions of different datatypes. These types of macros are
called as generic functions.

Example:

Intmax_int(int v1,int v2)

Int temp;

If(v1<v2)

Temp=v1;

Else

Temp=v2;

Return trmp;

STRINGIZING OPERATOR (#) :

#define mystr(value)=printf(“value=%d\n”,value)

Here the formal parameter value outside the string was replaced by the v1,but outside the
string this replacement did not take place.
To solve this type of problem we can use the stringizing operator. We can observe this in
Example program.

Int main()

Int v1=20, v2=24;

Mystr (v1);

Mystr (v2);

Return 0;

OUTPUT:

Value=20

Value=24

But we want to replace “value=%d” to v1=%d,v1 so we go for stringizing operator(#)


(with in the string)

Example:

#define mystr (value) =printf (#value”=%d”, value);

Int main()

Int v1=10,v2=20;

Mystr (v1);

Mystr (v2);

Return 0;

OUTPUT:

v1=10 v2=20
TOKEN PASTING (##):

Token pasting operator ## is used in macros definition to concatenate two tokens into a
single token. As the name implies, this operator pastes two token into one.

#include<stdio.h>

#define PASTE (a, b) a##b

Int main ()

Int v1=10, v2=20;

Printf (“%d %d”, PASTE (v, 1), PASTE (v, 2));

Return 0;

OUTPUT:

10 20

The token passing operator converts the above statement into

Printf (“%d %d”, v1, v2);

CONDITIONAL COMPILATION:

Conditional compilation means compilation of a part of code Based on some condition.


These conditions are checked during the preprocessing phase.

The directives used in conditional compilation are –

#ifdef, #ifndef, #if, #else, #elif, #endif

Example:

#if debug==1

Printf (“conditional compilation”);

#endif

It will debug only for debug 1 not for debug2, 3…etc.

Example 1:
#define debugleval 1

Int main ()

#if debuglevel==1

Printf (“debug level 1”);

#endif

Return 0;

DEBUGGING:

The compiler can detect syntax errors but it is unable to detect run time errors, which
result in incorrect output. To trace these types of errors in the program the debugging has to be
done by the programmer.

#define DEBUG

#ifdef DEBUG

Printf (“debug\n”);

#endif

PREDEFINED MACRO NAMES:

There are certain predefined macros names which can’t be undefined or redefined by
#undef or #define.

_DATE_ - date (dd: mm: yy)

_TIME_ - time (hh:mm:ss)

_FILE_ - file

_LINE_ - line number.


Example:

#include<stdio.h>

Int main()

Printf(“%s\n”,_DATE_);

Printf(“%s\n”,_TIME_);

Printf(“%s\n”,_FILE_);

Printf(“%s\n”,_LINE_);

Return 0;

Classroom Programs Total


7
DATA STRUCTURES
What is data structure?

A data structure is a particular way of organizing and storing data in a computer so


that it can be accessed and modified efficiently.

 Efficient use of memory.


 To overcome the difficulties of rearrangement /processing of elements as in the case of
arrays.

Searching& Sorting:

We need to collect lots of data to store and retrieve, so that we have to sort the data in an
efficient way it can be accessed easily.

There are two types of searching techniques as listed below:

1. Linear search

2. Binary search

1. LINEAR SEARCH:

Comparing the required element with the every element of the array until it found or end
of an array.

PROGRAM FOR LINEAR SEARCH:

#include<stdio.h>

intlinear_search(int[],int,int);

void main()

{intpos,res;

int array[]={1,2,3,4,5,6,7,8,9};

int size=sizeof(array)/sizeof(int);

//printf("array size:%d\n",size);

int search;

printf("enter the search element\n");

scanf("%d",&search);
pos=linear_search(array,size,search);

if(pos==-1)

printf("number number not found\n");

else

printf("number found. position is:%d\n",pos);

intlinear_search(int array[],intsize,int search)

int index=0,res=-1;

while(index<size)

if(array[index]==search)

{res=index;

break;

index++;

return res;

OUTPUT:

enter the search element

number found. position is:4


enter the search element

58

number not found

2. BINARY SEARCH:
Binary search algorithm finds given element in a list of elements. The binary search
algorithm can be used with only sorted list of element. The binary search cannot be used for list
of element which is in random order. This search process starts comparing of the search element
with the middle element in the list. If both are matched, then the result is "element found".
Otherwise, we check whether the search element is smaller or larger than the middle element in
the list. If the search element is smaller, then we repeat the same process for left sublist of the
middle element. If the search element is larger, then we repeat the same process for right sublist
of the middle element. We repeat this process until we find the search element in the list or until
we left with a sublist of only one element. And if that element also doesn't match with the search
element, then the result is "Element not found in the list".

Binary search is implemented using following steps...

 Step 1: Read the search element from the user


 Step 2: Find the middle element in the sorted list
 Step 3: Compare, the search element with the middle element in the sorted list.
 Step 4: If both are matching, then display "Given element found!!!" and terminate the
function
 Step 5: If both are not matching, then check whether the search element is smaller or
larger than middle element.
 Step 6: If the search element is smaller than middle element, then repeat steps 2, 3, 4 and
5 for the left sublist of the middle element.
 Step 7: If the search element is larger than middle element, then repeat steps 2, 3, 4 and 5
for the right sublist of the middle element.
 Step 8: Repeat the same process until we find the search element in the list or until
sublist contains only one element.
 Step 9: If that element also doesn't match with the search element, then display "Element
not found in the list!!!" and terminate the function.

Program:

#include<stdio.h>
#include<stdlib.h>
voidbinary_search(int[],int,int);
void main()
{intpos,res;
int array[]={1,2,3,4,5,6,7,8,9};
int size=sizeof(array)/sizeof(int);
int search;
printf("enter which num you want to search\n");
scanf("%d",&search);
binary_search(array,size,search);

}
voidbinary_search(int array[],intsize,int search)
{
int start=0,end=size-1,middle;
while(end>=start)
{middle=(start+end)/2;
if(search<array[middle])
end=middle-1;
if(search>array[middle])
start=middle+1;
if(array[middle]==search)
{printf("num found. position is:%d\n",middle);
exit(1);}
}
printf("number not found\n");
}

Output:

enter which num you want to search


5
num found. position is:4
enter which num you want to search
99
number not found

3. BUBBLE SORT:
Bubble Sort is an algorithm which is used to sort N elements that are given in a memory for eg:
an Array with N number of elements. Bubble Sort compares the entire element one by one and
sort them based on their values.

It is called Bubble sort, because with each iteration the largest element in the list bubbles up
towards the last place, just like a water bubble rises up to the water surface.

Sorting takes place by stepping through all the data items one-by-one in pairs and comparing
adjacent data items and swapping each pair that is out of order.

Program:

#include<stdio.h>
void bubble(int *,int *);
void main()
{
int array[5];
int v1;
for (int i=0;i<5;i++)
{printf("enter array[%d]=\n",i);
scanf("%d",&array[i]);
}
for (int j=0;j<4;j++)
for (int i=0;i<4;i++)
{//printf("array[%d]=%d\n",i,array[i]);
bubble(&array[i],&array[i+1]);
}
for (int i=0;i<5;i++)
{printf("array[%d]=%d\n",i,array[i]);
//bubble(&array[i],&array[i+1]);
}
}

void bubble(int *v1,int *v2)


{int temp;
if(*v1>*v2)
{temp=*v1;
*v1=*v2;
*v2=temp;
return;}
}
OUTPUT:

enter array[0]=9

enter array[1]=6

enter array[2]=99

enter array[3]=109

enter array[4]=5

array[0]=5

array[1]=6

array[2]=9

array[3]=99

array[4]=109

Classroom Programs Total


3

STACKS AND QUEUES


K.PRAVEENKUMAR

STACK:

A stack is a container of objects it will allow only two operations that are: push the item
into the stack, and pop the item out of the stack. A stack is a limited access data structure -
elements can be added and removed from the stack only at the top. Push adds an item to the top
of the stack, pop removes the item from the top.

3 Item 4 Top
2 Item 3
1 Item 2
0 Item 1

1. PUSH Space is needed otherwise overflow.

2. POPUnderflow (no data and no element in the stack)

3. DISPLAY

The following program showsPUSH, POP and DISPLAY operations:

9
8
7
6
5
4 40
3 30 Top
2 20
1 10
0

Index value Elements

In stack elements are inserted and removed according to the Last-In First-Out (LIFO) principle.
PUSH:

#define max_elements 10//”max_elements 10”represents array size as 10 elements//


int stack[max_elements];
int top=-1;
void push(intval) //Defining PUSH function
{
if(top==max_elements-1){
printf("stack overflow\n");
return;
}
top++;
stack[top]=val;
return;
}
POP:

int pop() //Defining POP function


{
Int val;
if (top==-1){
printf("stack underflow\n");
return -123456;
}
val=stack[top];
top--;
return 0;
}
DISPLAY:

Void display () //Defining DISPLAY function


{
int index;
printf("stack display is:\n");
for(index=top;index>=0;index--){
printf("%d\t",stack[index]);}
printf("\n");
return;
}
QUEUES:

A queue is a container of objects that are inserted and removed according to the first-in
first-out (FIFO) principle. In the queue only two operations are allowed: Insert the item into the
queue, and remove the item out of the queue. A queue is a limited access data structure -
elements can be inserted and removed from the queue only at the front. Insert adds an item to the
top of the queue; removes the items from the top of queue.
The following program shows Insertion and removing operations:

0 1 2 3 4
10 20 30 40 50

Front Rear

INSERT:

#define MAX 6 //”MAX 6”represents array size as 10 elements


int queue[MAX];
int front=-1,rear=-1;
void insert(int element) //Defining INSERTION function

{
if(rear==(MAX-1))
{
printf("overflow condition");
return;
}
if((front==-1)&&(rear==-1))
front=0;
rear++;
queue[rear]=element;
return;
}

REMOVE:

int delete() //Defining DELETION function


{
int element3;
if(front==-1)
{
printf("underflow conditon");
}
element3=queue[front];
if(front==rear)
front=rear=-1;
front++;
return element3;
}

DISPLAY:

void display() //Defining DISPLAY function


{
intcntr;
for(cntr=front;cntr<=rear;cntr++)
{
printf("%d\t",queue[cntr]);
}
printf("\n");
}

Classroom Programs Total


6
S.KARUNAKAR

Circular Queue :

Circular Queue is a linear data structure in which the operations are performed based on
FIFO (First In First Out) principle and the last position is connected back to the first position to
make a circle. It is also called ‘Ring Buffer’.

In a normal Queue, we can insert elements until queue becomes full. But once queue becomes
full, we cannot insert the next element even if there is a space in front of queue.

Operations on Circular Queue:

 Front: Get the front item from queue.


 Rear: Get the last item from queue.
 enQueue(value) This function is used to insert an element into the circular queue. In a
circular queue, the new element is always inserted at Rear position.
Steps:
1. Check whether queue is Full – Check ((rear == size-1 && front == 0) ||
(rear == front-1)).
2. If it is full then display Queue is full. If queue is not full then, check if
(rear == size-1 && front != 0) if it is true then set rear=0 and insert
element.
 De Queue() This function is used to delete an element from the circular queue. In a
circular queue, the element is always deleted from front position.
Steps:
1. Check whether queue is Empty means check (front==-1).
2. If it is empty then display Queue is empty. If queue is not empty then step
3
3. Check if (front==rear) if it is true then set front=rear= -1 else check if
(front==size-1), if it is true then set front=0 and return the element.

The below program will shows the insert, delete and display operations.

Program:

#include<stdio.h>
#define MAX 4
static int front=-1,rear=-1;
int queue[MAX];
void insert();
void delete();
void display();
void main()
{
int num=1;
while(num>0){
printf("enter your choice: insert:1 delete:2 display:3 quit:0\n");
scanf("%d",&num);
switch(num)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
default:
printf("enter correct choice:\n");
break;
}}
return;
}
void insert()
{
if(front==MAX-1&&rear==MAX-1){
printf("queue is full\n");
return;}
front=0;
rear++;
printf("enter a elements:\n");
scanf("%d",&queue[rear]);
if(rear==MAX-1)
rear=rear%(MAX-1);
return;
}
void delete()
{
if(front==-1&&rear==-1){
printf("queue is empty\n");
return;}
printf("poped element %d: %d\n",front,queue[front]);
front++;
return;}
void display()
{
int v1,v2;
if(front==-1&&rear==-1){
printf("queue is empty\n");
return;}
v1=front;v2=rear;
while(v1<=v2){
printf("display %d: %d\n",v1,queue[v1]);
v1++;}
return;}

output:
enter your choice: insert:1 delete:2 display:3 quit:0
1
enter a elements
11
enter your choice: insert:1 delete:2 display:3 quit:0
1
enter a elements
22
enter your choice: insert:1 delete:2 display:3 quit:0
1
enter a elements
33
enter your choice: insert:1 delete:2 display:3 quit:0
1
enter a elements
44
enter your choice: insert:1 delete:2 display:3 quit:0
3
Display 0:11
Display 1:22
Display 2:33
Display 3:44
enter your choice: insert:1 delete:2 display:3 quit:0
2
Poped element 11
enter your choice: insert:1 delete:2 display:3 quit:0
2
Poped element 22
enter your choice: insert:1 delete:2 display:3 quit:0
2
Poped element 33
enter your choice: insert:1 delete:2 display:3 quit:0
2
Poped element 44
enter your choice: insert:1 delete:2 display:3 quit:0
0

LINKED LIST
Linked List : A linked list is a collection of structures in which each structure contained two
field.

They are data field and link.

Link field contains address of the next node .

10 20 30
Types Of Linked List :

1. Single linked list.


2. Double linked list.
3. Circular linked list.

1. Single Linked List: In single linked list each node contains data and single link,which attach
to the next node in the list.

10 20 30

2. Double Linked List : In double linked list each node contains data field and two
pointer.where one pointer points to next node in the list and another pointer points to previous
node in the list.

10 20 30

3. Circular Linked List : In circular linked list the last node is connect to the first node .

data next data next data next


10 20 30

Last element points back to first.


STACK :
Stack is a linear data structure in which insertion and deletions are done at one end called
“top”.

Inserting or placing an element in to the stack is referred to as “push”.

Removing or deleting an element from the stack is referred to as “pop”.

Stack will inserting and removing of data will based on the principle of LIFO (Last In
First Out) .That means the last data what we will put into stack ,that data we will get out first.

In linked list implementation of stack, every new element is inserted as a TOP element.
That means every newly inserted element is pointed by TOP. To remove element from stack
simply remove the nodes which is pointed by TOP by moving TOP to it’s next node in the list.
The next filed of first element must be NULL.

Steps to inserting(push) elements into stack:

 create a new node with given values.


 Check whether stack is empty (TOP==NULL)
 If it is empty then set new node -->=NULL.
 If it is not empty then set newnode -->=TOP.
 Finally set TOP=new node.

Steps to removing(pop) elements into stack:

 Check stack is empty(TOP==NULL).


 If it is empty stack is under flow.
 If it is not empty node pointer temp=TOP.
 Then set TOP=TOPnext
 Finally delete allocated memory free(temp).

Steps to display elements of stack:

 Check whether stock is empty (TOP==NULL).


 If it empty display stack is empty and terminate the function.
 If it is not empty initialize temp with TOP.
 Display temp data and move it to the next node.
 Repeat it untill temp reaches to temp!=NULL.

The following program will shows the push,pop and display operations:

Program:
#include<stdio.h>
#include<stdlib.h>
struct stack
{
int data;
struct stack *next;
};
struct stack *push(struct stack *,int);
struct stack *pop(struct stack*,int *);
void display(struct stack*);
int main()
{
struct stack *top=NULL;
int element1,element2,val;
start:
printf("1:push 2:pop 3:display");
printf("enter your choice");
scanf("%d",&val);
switch(val)
{
case 1:
printf("enter element");
scanf("%d",&element1);
top=push(top,element1);
break;
case 2:
top=pop(top,&element2);
printf("pop element is %d",element2);
break;
case 3:
display(top);
break;
default:
printf("enter valid choice");
break;
}goto start;
}
struct stack *push(struct stack *top,int element1)
{
struct stack *temp;
temp=(struct stack*)malloc(sizeof(struct stack));
if(temp==NULL)
{
printf("NOT ENOUGH MEMORY");
return;
}
temp->data=element1;
//temp->next=NULL;
temp->next=top;
top=temp;
return top;
}
struct stack *pop(struct stack *top,int *element2)
{

if(top==NULL)
{
printf("underflow condition");
return;
}
*element2=top->data;
top=top->next;
return top;
}
void display(struct stack *top)
{

struct stack *temp;


temp=top;
while(temp!=NULL)
{
printf("%d\t",temp->data);
temp=temp->next;
}
printf("\n");
}

Output:
1:push 2:pop 3:display.

Enter your choice


1
Enter element.
40.
Enter your choice1
Enter element
59
Enter your choice
1
Enter element
60
Enter your choice
3
40 59 60
Enter your choice
2
Poped element:40
Enter your choice
2
Poped element: 59
Enter your choice
2
Poped element
60
Enter choice 3
Stack empty.

Classroom Programs Total


2

NO MATTER WHO EVER YOU ARE & HOW EVER YOU LOOK LIKE.IT JUST
MATTERS HOW DID YOU DO THINGS PERFECT & SUCCEED.
NAME: RAJESH

CALL BY REFERENCE:

Program 1:

#include<stdio.h>

Void main ( )

int v1,v2,*v3;

v1=10;

v2=10;

v3=&v1;

printf("%p %d\n ",v3,*v3);

call_by_addr(v1,v3,&v3);

Void call_by_ref_addr (int v1, int *iptr, int **dptr)

Int *myvar;

myvar=(int *)malloc(sizeof(int));

if(myvar==NULL)

printf("error message");

return;

*myvar=12345;

*dptr=myvar

Printf ("%p %p\n", myvar,*myvar);


}

Output: 12345 0x7ffbb59c608

QUEUE USING LINKED LIST:

To enter something in the queue we must do the following:

1. Create a new node:

Front =NULL

Rear=NULL

2. put data in it
10 NULL
temp

front

rear

3.Link into the list i.e the old rear node links to this new rear node.

10 NULL 20 NULL
rear temp

rear

4.Finally change the rear link to new rare.

temp

10 20 NUL 30 NULL
L

rear rear

program for queue using linked list:

#include<stdio.h>
#include<stdlib.h>

struct que

int data;

struct que *next;

};

void insert_into_que(struct que **front,struct que **rear,int element);

int remove_from_que(struct que **front,struct que **rear)

void main()

struct que *front=NULL;

struct que *rear=NULL;

int c=0;v1,v2;

while(c<3)

printf("enter element");

scanf("%d",&v1);

insert_into_que(&front,&rear,v1);

c++;

v2=remove_from_que(&front,&rear);
printf("%d",v2);

void insert_into_que(**front,struct que,**rear,int element 1)

struct que *temp;

temp=(struct que*)malloc(sizeof(struct que));

if(temp==NULL)

printf("memory is not sufficient");

return;

temp->data=element1;

temp->next=NULL;

if((*front==NULL)&&(*rear==NULL))

*front =*rear=temp;

return;

(*rear)->next=temp;

*rear=temp;
return;

int remove_from_que(struct que **front,struct que **rear)

int element2;

struct que *temp;

if((front==NULL)&&(rear==NULL))

printf("underflow condition");

return;

temp=*front;

element2=temp->data;

*front=(*front)->next;

free(temp);

if(front==NULL)

rear=NULL;

return element2;

output: enter elements 24


25

64

Classroom Programs Total

You might also like