Raghusir Notes
Raghusir Notes
-> 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
#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
It is fast
Platform dependent
In this language there is no need of translation
It has little bit of more memory
Faster
Platform dependent
Equally faster
Platform independent
B has 4bytes
C has 2bytes
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]
Compilation Process:
Source file
Preprocessor
Expanded code
Compiler
Assembler code
Assembler
Object file
Executable file(a.exe)
Compilation process
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.
Editor notepad
Compiler Translation of high level to low level language
Execution Loading program from hard disc to RAM
Debugger Analyzing the applications
Execution – (a.exe)
C:\MinGW\include
.o
.o Libraries
.o
Source file(test.c)
Executable file(.exe)
Variable: A value which can change variable during program execution is called variable.
Ex: V1*V2
* Operator
V1&V2 Operands
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;
Ex: {
V1=10;
V2=20;
}
2. Null statement: It has zero statements
C PROGRAMMING
C TOKENS:
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.
2. IDENTIFIER: Each program elements in a C program are given a name called identifiers.
RULES OF IDENTIFIER:
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
Integer Real/Float
Binary (0, 1)
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_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
Tasks:
Types Bytes
1. Char 1 byte
2. Int 2 or 4 bytes
3. Float 4 bytes
4. Double 8 bytes
Class programs
#include<stdio.h>
int main ( )
char chartype;
return 0;
int main( )
char ch;
ch=100;
Printf(“%c\n”, ch);
return 0;
Char ASCII
0 48
1 49
. .
. .
. .
. .
A 65
. .
. .
. .
. .
Z 90
. .
. .
. .
. .
a 97
. .
. .
. .
z 122
Character Range:
0000 0000 0 0
Unsigned: 0 to 2^n – 1
Signed: -2^(n-1) to 2^(n-1) – 1
n is the number of bits
CLASS PROGRAMS
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;
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
#include<stdio.h>
void main ()
{
int v1,v2;
v1=10; //assignment
v2=20; //assignment
Sum=v1+v2; //assignment
void main( )
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 ( )
sum= v1+v2;
mul= v1*v2;
div= v1/v2;
per= v1%v2;
Program:
#include<stdio.h>
void main( )
a= 10;
b= 20;
a= a+b;
sub= (a-=b);
mul= (a*=b);
div= (a%=b);
Types:
Program:
#include<stdio.h>
void main( )
int v1,v2,v3,v4,v5;
v1= 10;
v2= v1++;
v3= (++v1);
v4= v1--;
v5= (--v1);
}
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;
printf(“\n %d”,result);
Printf(“\n %d”,result);
result=(v1<v2)&&(v2=40);
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;
Comma operator: comma operator is used to combine the multiple statements to a single
statement.
Example:
#include<stdio.h>
void main()
int result;
result= (v1=10,v2=30,v1+v2);
float result;
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;
V2=3;
result=v1/v2;
Example2:
#include<stdio.h>
void main()
float v2 result;
V1=10;
result=v1/v2;
}
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;
Float result;
result=10/3.0;
result=10.0/3;
Result=10.0/3.0;
}
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.
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.
#include<stdio.h>
result = (v1&v2);
}
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.
#include<stdio.h>
result = (v1||v2);
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.
#include<stdio.h>
result = (v1^v2);
}
Left-shift operator: The left-shift operator is used to shift values to left until overflows.
Formulae: result= value*2^n
#include<stdio.h>
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.
#include<stdio.h>
K.SHIVANI
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.
#include<stdio.h>
Void main()
Int result;
Printf(“%d\n”,result);
DESCRIPTION: V1=10
//Msb bit=1, so the given number is –ve, so we have to do the 2’s complement//
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;
printf(“%f\n”,result1); //
result2=20/ (float)3;
printf(“%f\n”,result2);
Ex:2
#include<stdio.h>
Void main()
Char ch1=200;
Printf(“%d%d\n”,ch1,ch2);
Output:-56,200;
#include<stdio.h>
Void main ()
Printf(“%d%d\n”,v1,v2);
NAME: P. Srilatha
CONDITIONAL STATEMENTS
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
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;
}
Program4:
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;
}
Program 7:
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
#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;
}
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;
}
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
Loop statements are used to repeat the process again and again.
Loop statements
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: 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”);
#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);
}
}
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
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”);
}
P. Rajesh Date-29/01/2018
Embedded_1
Nested loop
Algorithm:
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.....
1.Break
2.Continue
Example1:
#include<stdio.h>
Int main()
Int v1=16;
If(v1>3)
Printf(“%d\n”,v1);
Break;
return 0;
Output: Error
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()
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
Example3:
#include<stdio.h>
Int main()
Sum=0;
Scanf(“%d”,&num);
While(num!=0)
If (num>0)
Sum+=num;
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()
{
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);
................................................................................................................................
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
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
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
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
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
It is defined by the user. The program we write is the definition of the main() function.
Syntax
printf() and scanf() functions are present in the library. The files related to them are
libc.aarchive and static library
libc.soshared 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
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.
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:
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)
{
-----------
-----------
}
syntax:
int func(void);
int main(void)
{
--------------
---------------
func( );
--------------
return 0;
}
int func(void)
{
-----------
return expression;
}
syntax:
}
void func( int c, int d )
{
-----------
-----------
}
4. functions with arguments and return value:
syntax:
}
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;
}
S.Pravalika
STORAGE CLASSES
There are 3 types
1. Automatic 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);
}
#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
~ #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
#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
#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;
}
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.
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>
Int main ()
{
Enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Bitwise operators Significance
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
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
11 $ head file.txt
13 $ tail file.txt
14 $ ls-file.txt
File is an argument
15 $ ls-file1.txt file2.txt
16 $ ls/bin |more
17 $ ls/bin |page
18 cat<binaryfiles.txt
20 $ echo”sbin files”>binaryfiles.txt
Truncated already existing file. If the file does not exist it create the file.
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)
$ ls / bin /b * 1 > bin-with b.txt // output of ‘ls / bin /b *’ is directed to ‘bin-with b.txt’
$ ls*.py >error_py.txt //error because “no such files are there”&we are
trying to give
it through Std.out(2)
//Here 1&2are the file descriptive id for standard input and standard
output
close(0)
LINKS:
1. Hard Link
2. Soft Link
HARD LINK:
SOFT LINK:
->linked to file
Hard link:
SOFT LINK:
$ ln -s file1.txt file2_link.txt //created hard link. Ensure that ‘file2_link.txt’ file is not there
before .
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.
$touch file1.txt
Touch command creates an empty file, If file is already created then it will open .
Permissions:
Types of files:
1.Normal file----------------------------------------------------------
3.Charactor (c)
4.Block (b)
1. Symbols
2. Numbers
1. Symbols:
(+) Add permissios.
$ls -l file1.txt
$ls -l file1.txt
Again the permission changes from --w- rw- r-- to -rw- rw- r--
$ls file1.txt
$ls -l file1.txt
$chmod u-x,g-w
$ls -l file1.txt
2.Number
r w x
4 2 1
r---read
w---write
x---execute
$ls -l file1.txt
$ls -l -lfile1.txt
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
$ls -l helloworld.c
$gcc helloworld.c
$ls -l a.out
$./a.out
helloworld
$./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
$cd temp1
Permission denied
We are removing read permission to user.(It goes to directory but it not shows any content.)
In Directory:
$umask
000?
0-octal
0-owner
0-group
?-others
$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.
Here age is array of type int, which can store 100 elements of type int.
Note:
If we enter the elements more than the size, The application will be crashed.
Example programs:
int myints[5]; 0 1 2 3 4
Output:
size of (sints)=10
size of (myints)=20
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}
10 20 30 40 50
Sum+=sints[count]; 3000 3002 3004 3006 3008
}
Printf(“%d\n”,sum);
Output:
Sum=150
}
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}
12-2-2018.
0 1 2 3.........................................9
10 20 30 40 50 0 0 0 0 0
4*5=20 bytes //
4*20=80bytes //
4*20=80bytes //
Eg : char mystr[10];
Char value;
Value=’a’;
Value++;
Gets ( )
Puts ( )
(Or)
Char mystr2 [10]= “abcdef”; // 10bytes........if you are not initialising null
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
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:
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
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:
10 20 3 40 50 6 -
0 0
10 20 3 40 50 6 -
0 0
10 20 30 40 50 -
Deletion:
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
By using pointers:
Pointers:
Pointer is named because it points to a particular location in memory by storing the address of
that location.
Advantages: It stores
& - 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)
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
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
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:
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;
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( )
intmy_array[4]={10,20,30,40};
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 my2darray[3][4]={{10,20,30,40},{1,2,3,4},{15,25,35,45}};
printf(“%p,%d”,ptrarray,(*ptrarray)[0]);
ptrarray++;
printf(“%p,%d”,ptrarray,(*ptrarray)[0]);
printf(“%p,%d”,*(my2darray+2)+0, *(*(my2darray+2)+0));
return 0;
Output:
000000000024FE10,10
000000000024FE20,1
000000000024FE30,15
1
Increment or decrement operation using pointers
CH. HARIKRISHNA
#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>
int main()
swap(&v1, &v2);
printf("%d\t%d\n",v1, v2);
return 0;
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
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]);
for(v3=0;v3<5;v3++)
Printf(“%d\t”,arrptr[1][v3]);
}
Output:
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;
void myfcn()
printf("my function\n");
}
Output:
my function
my function
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);
main()
void (*myfptr)();
exec_fun(myfun1);
myfptr=myfun2;
exec_fun(myfptr);
(*fptr)();
return;
void myfun1()
{
printf("In myfun 1\n");
return;
void myfun2()
return 0;
Output:
In myfun1
In myfun2
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:
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:
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;
Program-1:
#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:
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
POINTERS IN STRUCTURES:
#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);
}
#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
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
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;
}
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{
Int main()
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//
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 {
--
};
Program.3
#include<stdio.h>
Union performance{
Char grade[3];
Int marks;
Float percent;
};
Int main()
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
Program 4.
#include<stdio.h>
Union twobytes{
Char ch[2];
};
Int main()
_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
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:
1.fputc():
#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;
}
#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():
3. FORMATTED I/O:
1. fprintf():
#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():
#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():
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
-fseek( )
-ftell( )
-rewind( )
-fsetpos( )
-fgetpos( )
1.Beginning
2.Current
3.From end
#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)
Exit(1);
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);
PREPROCESSOR
Replacing header file
Removing comments
Macro substitution
Problems with macros
Generic functionality
Conditional compilation
Built in variables for debugging purpose
Debugging
Removing 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:
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.
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';
myswap(int,v1,v2);
printf("\n\n\n\n");
myswap(char,ch1,ch2);
printf("after swap char variables are ch1=%c,ch2=%c\n",ch1,ch2);
OUTPUT:
Generic function :
Macro can be used to generate functions of different datatypes. These types of macros are
called as generic functions.
Example:
Int temp;
If(v1<v2)
Temp=v1;
Else
Temp=v2;
Return trmp;
#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()
Mystr (v1);
Mystr (v2);
Return 0;
OUTPUT:
Value=20
Value=24
Example:
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>
Int main ()
Return 0;
OUTPUT:
10 20
CONDITIONAL COMPILATION:
Example:
#if debug==1
#endif
Example 1:
#define debugleval 1
Int main ()
#if debuglevel==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
There are certain predefined macros names which can’t be undefined or redefined by
#undef or #define.
_FILE_ - file
#include<stdio.h>
Int main()
Printf(“%s\n”,_DATE_);
Printf(“%s\n”,_TIME_);
Printf(“%s\n”,_FILE_);
Printf(“%s\n”,_LINE_);
Return 0;
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.
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.
#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;
scanf("%d",&search);
pos=linear_search(array,size,search);
if(pos==-1)
else
int index=0,res=-1;
while(index<size)
if(array[index]==search)
{res=index;
break;
index++;
return res;
OUTPUT:
58
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".
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:
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]);
}
}
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
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
3. DISPLAY
9
8
7
6
5
4 40
3 30 Top
2 20
1 10
0
In stack elements are inserted and removed according to the Last-In First-Out (LIFO) principle.
PUSH:
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:
{
if(rear==(MAX-1))
{
printf("overflow condition");
return;
}
if((front==-1)&&(rear==-1))
front=0;
rear++;
queue[rear]=element;
return;
}
REMOVE:
DISPLAY:
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.
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.
10 20 30
Types Of 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 .
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.
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)
{
Output:
1:push 2:pop 3:display.
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;
call_by_addr(v1,v3,&v3);
Int *myvar;
myvar=(int *)malloc(sizeof(int));
if(myvar==NULL)
printf("error message");
return;
*myvar=12345;
*dptr=myvar
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
temp
10 20 NUL 30 NULL
L
rear rear
#include<stdio.h>
#include<stdlib.h>
struct que
int data;
};
void main()
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);
if(temp==NULL)
return;
temp->data=element1;
temp->next=NULL;
if((*front==NULL)&&(*rear==NULL))
*front =*rear=temp;
return;
(*rear)->next=temp;
*rear=temp;
return;
int element2;
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;
64