c prog ppt

196
EMBEDDED SYSTEMS PROGRAMMING

Upload: xinoe

Post on 22-Jan-2018

698 views

Category:

Software


0 download

TRANSCRIPT

Page 1: C prog ppt

EMBEDDED SYSTEMS PROGRAMMING

Page 2: C prog ppt

Embedded systems

qComputers used as a part of larger system-- that usually doesn’t look like a computer-- that usually controls physical devices

qOften reliability is critical--“Critical” as in “if system fails someone might die”

qOften resources (memory, processor capacity) are limitedqOften real-time response is essential

Page 3: C prog ppt

Application areas

Page 4: C prog ppt

üWhat are the difference between microcontroller and microprocessor ?

üWhat is an N-bit CPU/microcontroller/microprocessor ?

üHow does an embedded program run ?

üWhat is Hard real time and soft real time embedded systems ?

üWhy is design of embedded system is difficult ?

üFlow chart Vs Pseudo code

Page 5: C prog ppt

Possible organization of embedded systems

Page 6: C prog ppt

Development cycle

Page 7: C prog ppt

Why do we use C……?

C has now become a widely used professional language for various reasons.•Easy to learn•Structured language•It produces efficient programs.•It can handle low-level activities.•It can be compiled on a variety of computers.

C suit for developingOSs,System level programming,Embedded Systems(including micro-controllers such as PIC, ARM, and MP),RTOS,Compilers,website programminglibraries to other languages

Page 8: C prog ppt

C programming Features cont...Powerful programming language:

C is very efficient and powerful programming language, which provides various data types, functions, pointers, control and loop control statements, & it is best used for data structures and developing system software.

Efficient use of pointers, pointers has direct access to memory.

Bit manipulation:C program can be manipulated using bits. We can perform different operations at bit

level. We can manage memory at bit level.(for ex: in structures)

High Level Features :It is more User friendly as compare to Previous languages. Previous languages such as

BCPL,Pascal and other programming languages never provide such great features to manage data. Previous languages have there pros and cons but C Programming collected all useful features of previous languages thus C become more effective language.

Page 9: C prog ppt

Advantages (or) features of C programming language

C is the most popular programming language, C has many advantages:Modularity:

Modularity is one of the important characteristics of C. we can split the C program in to number of modules instead of repeating same logic statements(sequentially). It allows reusability of modules.

Middle level language:As a middle level language C combines advantages of both high and low level

language. (array, pointers, etc.)

General purpose programming language: C can be used to implement any kind of applications such as maths oriented, graphics, business oriented applications.

Portability: We can compile or execute C programming in any operating system (windows, dos, unix).

Page 10: C prog ppt

structure of C a program

#include<stdio.h> /* Header File */main () /* starting function */{ /* start of program */ --------Statements;--------Return;}

Page 11: C prog ppt

Example C program

Ex:/* Hello world Program*/#include <stdio.h>int main(){printf (“Hello world\n”);return 0;}

Page 12: C prog ppt

Compilation process

Page 13: C prog ppt

Type the following command to verify that gcc is installed:

$ which gcc

Output:/usr/bin/gcc

Find out version of gcc:$ gcc --version

Output:gcc (GCC) 4.0.3 20060212 (prerelease) (Debian 4.0.2-9) Copyright (C) 2006 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Page 14: C prog ppt

Step by step compilation commands:

-E preprocess only, do not compile, assemble or link.-S compile only, do not assemble or link.-C compile and assemble, but do not link-O Place the output in to file

$gcc –E hello.c –o hello.i$gcc –S hello.i –o hello.s$gcc –C hello.s –o hello.o$./hello.o

Page 15: C prog ppt

Format Specifiers

There are many format specifiers defined in C. Take a look at the following list:

%i or %d int%c char%f float%lf double%s string

Note: %lf stands for long float.

Page 16: C prog ppt

Let’s take a look at an example of printf formatted output:

#include<stdio.h>main(){

int a,b;float c,d;a = 15;b = a / 2;printf("%d\n",b);printf("%3d\n",b);printf("%03d\n",b);c = 15.3;d = c / 3;printf("%3.2f\n",d);

}

Page 17: C prog ppt

/*EXAMPLE*/#include<stdio.h>

main(){

printf("The color: %s\n", "blue");printf("First number: %d\n", 12345);printf("Second number: %04d\n", 25);printf("Third number: %i\n", 1234);printf("Float number: %3.2f\n", 3.14159);printf("Hexadecimal: %x\n", 255);printf("Octal: %o\n", 255);printf("Unsigned value: %u\n", 150);printf("Just print the percentage sign %%\n", 10);

}

Page 18: C prog ppt

Formatting Strings

#include<stdio.h>main(){

printf(":%s:\n", "Hello, world!");printf(":%15s:\n", "Hello, world!");printf(":%.10s:\n", "Hello, world!");printf(":%-10s:\n", "Hello, world!");printf(":%-15s:\n", "Hello, world!");printf(":%.15s:\n", "Hello, world!");printf(":%15.10s:\n", "Hello, world!");printf(":%-15.10s:\n", "Hello, world!");

}

Page 19: C prog ppt

Data types- Primary data types- Derived data types

Page 20: C prog ppt

Type Storage size Value range

char 1 byte -128 to 127 or 0 to 255

unsigned char 1 byte 0 to 255

signed char 1 byte -128 to 127

int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647

unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295

short 2 bytes -32,768 to 32,767

unsigned short 2 bytes 0 to 65,535

long 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long 4 bytes 0 to 4,294,967,295

Integer TypesFollowing table gives you details about standard integer types with its storage sizes and value ranges:

Page 21: C prog ppt

Floating-Point Types

Following table gives you details about standard floating-point types with storage sizes and value ranges and their precision:

Type Storage size Value range Precision

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Page 22: C prog ppt

C program to Find Maximum and minimum range of Float data type

#include <stdio.h>#include <float.h>

int main(){ printf("Storage size for float : %d \n", sizeof(float)); printf("Minimum float positive value: %E\n", FLT_MIN ); printf("Maximum float positive value: %E\n", FLT_MAX ); printf("Precision value: %d\n", FLT_DIG ); return 0;}

Page 23: C prog ppt

Identifiers in C language:

•Each program elements in a C program are given a name called identifiers.•Names given to identify Variables, functions and arrays are examples for identifiers.

Keywords in C language:

•Keywords are pre-defined words in a C compiler.•Each keyword is meant to perform a specific function in a C program.•Since keywords are referred names for compiler, they can’t be used as variable name•C language supports 32 keywords

Page 24: C prog ppt

Variables in C

C variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable.

The value of the C variable may get change in the program.

C variable might be belonging to any of the data type like int, float, char etc.

Page 25: C prog ppt

Rules for Constructing Variable Names

A Variable name consists of any combination of alphabets, digits and underscores.

Some compiler allows variable names whole length could be up to 247 characters. Still it would be safer to stick to the rule of 31 characters.

The first character of the variable name must either be alphabet or underscore, It should not start with the digit.

No commas and blanks are allowed in the variable name

No special symbols other than underscore are allowed in the variable name

Page 26: C prog ppt

C tokens:

•C tokens are the basic buildings blocks in C language which are constructed together to write a C program.•Each and every smallest individual units in a C program are known as C tokens.•C tokens are of six types. They are,1.Keywords (eg: int, while),3.Identifiers (eg: main, total),5.Constants (eg: 10, 20),7.Strings (eg: “total”, “hello”),9.Special symbols (eg: (), {}),11.Operators (eg: +, /,-,*)

Page 27: C prog ppt

C tokens example program:

int main(){int x, y, total;x=10, y=20;total=x+y;printf(“total=%d\n”,total);}

where,main – identifier{,}, (,) – delimiterint – keywordx, y, total – identifiermain, {, }, (, ), int, x, y, total – tokens

Page 28: C prog ppt

Operators•Assignment operator

- (=, +=, -=, /=, %=, *=)

•Arithmetic operator- C supports 5 operators : (+, -, *, /, %,++, --)

•Relational operator-(<, >, <=, >=, ==, !=)

•Logical operator-(&&, ||, !)

•Bitwise operator-(&, |, ^, <<, >>)

Page 29: C prog ppt

Operators cotnd....

Conditional operatorAlso called ternary operator or ?: operatorEx: Use a conditional operator to find whether number you entered is odd or

even

Special operators-Sizeof(), & and * pointer operators

Comma operator-Comma as operator and as separator.

Page 30: C prog ppt

Operator precedence and Associativity

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative * / % Left to right

Additive + - Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Page 31: C prog ppt

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |=

Right to left

Comma , Left to right

Page 32: C prog ppt

/* c program to illustrate mathematical operations.*/# include <stdio.h>int main(){ int i; i = 5; printf("The Value of i is : %d", i); i = i + 5; printf("\nThe Value of i is : %d", i); i = i - 2; printf("\nThe Value of i is : %d", i); i = i * 2; printf("\nThe Value of i is : %d", i); i = i / 4; printf("\nThe Value of i is : %d", i); i++; printf("\nThe Value of i is : %d", i); i++; printf("\nThe Value of i is : %d", i); i --; printf("\nThe Value of i is : %d", i); return(0) ; }

Page 33: C prog ppt

Constants in C:

•C Constants are also like normal variables. But, only difference is, their values can not be modified by the program once they are defined.•Constants refer to fixed values.•Constants may be belonging to any of the data type.

S.no Constant type data type Example

1 Integer constants intunsigned int

long intlong long int

53, 762, -478 etc 5000u, 1000U etc

483,6472,147,483,680

2 Real or Floating point constants floatdoule

10.456789600.123456789

3 Octal constant int 013 /* starts with 0 */

4 Hexadecimal constant int 0×90 /* starts with 0x */

5 character constants char ‘A’ , ‘B’, ‘C’

6 string constants char “ABCD” , “Hai”

Page 34: C prog ppt

Defining Constants

There are two simple ways in C to define constants:

-Using #define preprocessor.-Using const keyword.

Page 35: C prog ppt

/* Example program using #define preprocessor */#include <stdio.h>#define LENGTH 10#define WIDTH 5#define NEWLINE '\n'int main(){

int area;area = LENGTH * WIDTH;printf("value of area : %d", area);printf("%c", NEWLINE);return 0;

}

Page 36: C prog ppt

/* defining constants using const */#include <stdio.h>int main(){

const int LENGTH = 10;const int WIDTH = 5;const char NEWLINE = '\n';int area;area = LENGTH * WIDTH;printf("value of area : %d", area);printf("%c", NEWLINE);return 0;

}

Page 37: C prog ppt

#include <stdio.h>int main(){ char ch = 'A'; char str[20] = "fresh2refresh.com"; float flt = 10.234; int no = 150; double dbl = 20.123456; printf("Character is %c \n", ch); printf("String is %s \n" , str); printf("Float value is %f \n", flt); printf("Integer value is %d\n" , no); printf("Double value is %lf \n", dbl); printf("Octal value is %o \n", no); printf("Hexadecimal value is %x \n", no); return 0;}", str);}

Page 38: C prog ppt

#include <stdio.h> int main(){ char ch; char str[100]; printf("Enter any character \n"); scanf("%c", &ch); printf("Entered character is %c \n", ch); printf("Enter any string ( upto 100 character ) \n"); scanf("%s", &str); printf("Entered string is %s \n", str);}

Page 39: C prog ppt

Bit wise operators in C:

These operators are used to perform bit operations. Decimal values are converted into binary values which are the sequence of bits and bit wise operators work on these bits.Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left shift) and >> (right shift).

 x y  x|y x & y x ^ y Operator_symbol Operator_name

& Bitwise_AND

0 0 0 0 0 | Bitwise OR

0 1 1 0 1~ Bitwise_NOT

1 0 1 0 1

^ XOR1 1 1 1 0

  << Left Shift

>> Right Shift

Truth table for bitwise operator bitwise operator

Page 40: C prog ppt

#include <stdio.h>int main(){ int m=40,n=80,AND_opr,OR_opr,XOR_opr,NOT_opr ; AND_opr = (m&n); OR_opr = (m|n); NOT_opr = (~m); XOR_opr = (m^n); printf("AND_opr value = %d\n",AND_opr ); printf("OR_opr value = %d\n",OR_opr ); printf("NOT_opr value = %d\n",NOT_opr ); printf("XOR_opr value = %d\n",XOR_opr ); printf("left_shift value = %d\n", m << 1); printf("right_shift value = %d\n", m >> 1);}

Page 41: C prog ppt

Conditional or ternary operators in C:

Conditional operators return one value if condition is true and returns another value is condition is false.

This operator is also called as ternary operator.Syntax : (Condition? true_value: false_value);Example : (A > 100 ? 0 : 1);

In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional statements.

Page 42: C prog ppt

C provides two types of flow control

●Branching●Looping●

Branching1. If Statement2. The If else Statement3. Compound Relational tests4. Nested if Statement5. Switch Statement

Loop control statements in C1. for2. while3. do-while

Page 43: C prog ppt

If statementif(condition){statement;

}

If else statementIf(condition)Program statement1elseprogram statement 2

Compound relational test

a) if (condition1 && condition2 && condition3)b) if (condition1 || condition2 || condition3)

Page 44: C prog ppt

Nested if statement

if (condition1) if (condition2)

statement-1;elsestatement-2;elsestatement-3;

Page 45: C prog ppt

Switch statement

switch( expression ) {

case constant-expression1: statements1;break;case constant-expression2: statements2;break;case constant-expression3: statements3;break; default : statements4;

}

// Note: Expression used in switch must be integral type (char, int, enum). Default can be placed anywhere in the program.

Statements written above case are never executed. Two case labels cannot have same value.

Page 46: C prog ppt

while ( expression ){

Single statement or Block of statements;} for( expression1; expression2; expression3){ Single statement or Block of statements;}

do{ Single statement or Block of statements;} while(expression);

Page 47: C prog ppt

Loop control statements

•Break – exit from loop or switch•Continue – skip one iteration in loop

Page 48: C prog ppt

//program to demonstrate the working of continue statement in C programming# include <stdio.h>int main(){int i,num,product;for(i=1,product=1;i<=4;++i){ printf("Enter num%d:",i); scanf("%d",&num); if(num==0) continue; / *In this program, when num equals to zero, it skips the statement product*=num and continue the loop. */ product*=num;} printf ("product=%d“,product);return 0;}

Page 49: C prog ppt

-Prog to print numbers from 1 to 10 skipping 5 using continue.

-Prog to check, if number entered is equal to 10, less than 10 or greater than 10.

-Write a program to find greatest of 2 numbers.

-Write a program to find greatest of 3 numbers.

-Write a program to generate counts from 1 to 20 using while and for loop.

-Prog to reverse a integer

-Prog to calculate power of a number

-Prog to implement a simple calculator

-Prog to print prime numbers from 1 to 100.

-Prog to find number entered is palindrome or not

-Prog to find factorial of a number

-Prog to find if a given bit is set to one or not

-For a given binary number find equivalent decimal value

-Prog to count number of bits set to ‘0’ in a binary value

-Prog to check if all bits of a given integer is one

-Prog to check if a given integer is power of two

-Prog to swap two numbers using bitwise operator

-Prog to find sum of odd and even numbers from 1 to N

-Prog to read 4 integers and find average of last two numbers

-Prog to read number of month and display month

Page 50: C prog ppt

Scope Rules

A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable can not be accessed. There are three places where variables can be declared in C programming language:

•Inside a function or a block which is called local variables,

•Outside of all functions which is called global variables.

•In the definition of function parameters which is called formal parameters.

Page 51: C prog ppt

Local Variables

Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own.

#include <stdio.h>int main (){ int a, b; /* local variable declaration */ int c; A = 10; /* actual initialization */ b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0;}

Page 52: C prog ppt

Local Variables

Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own.

#include <stdio.h>int main (){ int a, b; /* local variable declaration */ int c; A = 10; /* actual initialization */ b = 20; c = a + b; printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0;}

Page 53: C prog ppt

Global Variables

Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.

#include <stdio.h>int g; /* global variable declaration */int main (){int a, b; /* local variable declaration */a = 10; /* actual initialization */ b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0;}

Page 54: C prog ppt

Formal ParametersFunction parameters, formal parameters, are treated as local variables with-in that

function and they will take preference over the global variables.#include <stdio.h>int a = 20; /* global variable declaration */int main (){int a = 10; /* local variable declaration in main function */ int b = 20; int c = 0; printf ("value of a in main() = %d\n", a); c = sum( a, b); printf ("value of c in main() = %d\n", c); return 0;}int sum(int a, int b) /* function to add two integers */{ printf ("value of a in sum() = %d\n", a); printf ("value of b in sum() = %d\n", b); return a + b; }

Page 55: C prog ppt

Initializing Local and Global Variables

When a local variable is defined, it is not initialized by the system, you must initialize it yourself. Global variables are initialized automatically by the system when you define them as follows:

Data Type Initial Default Valueint 0char '\0'float 0double 0pointer NULL

Page 56: C prog ppt

Storage class specifiers in C

There are 4 storage class specifiers available in C language. They are,• auto• extern• static• register

Page 57: C prog ppt

--Find output of following program#include<stdio.h>void increment(void);int main(){ increment(); increment(); increment(); increment(); return 0;}void increment(void){ static int i = 0 ; printf ( "%d ", i ) ; i++;}

#include<stdio.h>int x = 10 ;int main( ){ extern int y ; printf ( "The value of x is %d \n", x ) ; printf ( "The value of y is %d",y ) ; return 0;}int y = 50 ;

Page 58: C prog ppt

Memory Layout of C programs

A typical memory representation of C program consists of following sections.

1. Text segment2. Initialized data segment3. Uninitialized data segment4. Stack5. Heap

Page 59: C prog ppt

1. Text Segment:

A text segment , also known as a code segment or simply as text, is one of the sections of a program in an object file or in memory, which contains executable instructions.

2. Initialized Data Segment:

Initialized data segment, usually called simply the Data Segment. A data segment is a portion of virtual address space of a program, which contains the global variables and static variables that are initialized by the programmer.Note that, data segment is not read-only, since the values of the variables can be altered at run time.

Page 60: C prog ppt

2. Initialized Data Segment:

This segment can be further classified into initialized read-only area and initialized read-write area.

For instance the global string defined by char s[] = “hello world” in C and a C statement like int debug=1 outside the main (i.e. global) would be stored in initialized read-write area. And a global C statement like const char* string = “hello world” makes the string literal “hello world” to be stored in initialized read-only area and the character pointer variable string in initialized read-write area.

Ex: static int i = 10 will be stored in data segment and global int i = 10 will also be stored in data segment

Page 61: C prog ppt

3. Uninitialized Data Segment:

Uninitialized data segment, often called the “bss” segment, named after an ancient assembler operator that stood for “block started by symbol.” Data in this segment is initialized by the kernel to arithmetic 0 before the program starts executing

uninitialized data starts at the end of the data segment and contains all global variables and static variables that are initialized to zero or do not have explicit initialization in source code.

For instance a variable declared static int i; would be contained in the BSS segment.For instance a global variable declared int j; would be contained in the BSS segment

Page 62: C prog ppt

4. Stack:

The stack area traditionally adjoined the heap area and grew the opposite direction; when the stack pointer met the heap pointer, free memory was exhausted. (With modern large address spaces and virtual memory techniques they may be placed almost anywhere, but they still typically grow opposite directions.Stack, where automatic variables are stored, along with information that is saved each time a function is called. Each time a function is called, the address of where to return to and certain information about the caller’s environment, such as some of the machine registers, are saved on the stack. The newly called function then allocates room on the stack for its automatic and temporary variables. This is how recursive functions in C can work. Each time a recursive function calls itself, a new stack frame is used, so one set of variables doesn’t interfere with the variables from another instance of the function.

Page 63: C prog ppt

5. Heap:

Heap is the segment where dynamic memory allocation usually takes place.

The heap area begins at the end of the BSS segment and grows to larger addresses from there.The Heap area is managed by malloc, realloc, and free,

Page 64: C prog ppt

Arrays

C Array is a collection of variables belongings to the same data type. You can store group of data of same data type in an array.

•Array might be belonging to any of the data types•Array size must be a constant value.•Always, Contiguous (adjacent) memory locations are used to store array elements in memory.•It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any values to array.•Array can be single dimensional or multidimensional

Page 65: C prog ppt

Declaring single dimensional array :Syntax: data_type arr_name [size];

int a[10]; // integer arraychar b[10]; // character array i.e. stringint arr[ ]={3,6,8,9,3,};

#include<stdio.h>int main(){ int i; int arr[5] = {10,20,30,40,50}; for (i=0;i<5;i++) { printf("value of arr[%d] is %d \n", i, arr[i]); }}

Page 66: C prog ppt

Multidimensional array declaration

Syntax: data_type arr_name [no_of_rows][no_of_columns];int arr [2][2]={1, 2, 3, 4};

#include<stdio.h>int main(){int i,j;int arr[2][2] = {10,20,30,40};for (i=0;i<2;i++) { for (j=0;j<2;j++) {

printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]); }}}

Page 67: C prog ppt

-- prog to Add elements of an array at odd position.-- Prog to find intersection of 3 arrays.

Page 68: C prog ppt

Functions:

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

Syntax: return_type function_name ( [parameter list] ){// body of the function}

Function Declarations:

A function declaration tells the compiler about a function name and how to call the function. A function declaration has the following parts:

return_type function_name( parameter list );

Ex: int max(int num1, int num2);

Ex: int max(int, int); // is also valid declaration

Calling a function in C

function_name( [arg1, ... ] );

Page 69: C prog ppt

Calling a function:

•Call by value•Call by reference

Different types of function calling in c programming

•Function with no arguments and no return value•Function with no arguments and return value•Function with arguments but no return value•Function with arguments and return value.

Page 70: C prog ppt

/*Program using function call by value*/void swap(int x, int y){ int z; z = x; x = y; y = z; printf("Swapped values are a = %d and b = %d", x, y);}void main(){ int a = 7, b = 4; printf("Original values are a = %d and b = %d", a, b); swap(a, b); printf("The values after swap are a = %d and b = %d", a, b);}

Page 71: C prog ppt

Recursion in C:A function that calls itself is known as recursive function and this technique is known as recursion in C programming.

/*program to find sum of first n natural numbers using recursion. Note: Positive integers are known as natural number i.e. 1, 2, 3....n*/

#include <stdio.h>int sum(int n);int main(){ int num,add; printf("Enter a positive integer:\n"); scanf("%d",&num); add=sum(num); printf("sum=%d",add);}int sum(int n){ if(n==0) return n; else return n+sum(n-1); /*self call to function sum() */}

Page 72: C prog ppt

Macros in C

All the lines starting with # are processed by preprocessor1) There is a difference in following two

#include <example.h>#include “example.h”

2) When we use define for a constant, the preprocessor produces a C program where the defined constant is searched and matching tokens are replaced with the given expression

3) The macros can take function like arguments, the arguments are not checked for data type.

4) The macro arguments are not evaluated before macro expansion. For example consider the following program

#include <stdio.h>#define MULTIPLY(a, b) a*bint main(){printf("%d", MULTIPLY(2+3, 3+5)); return 0;}

Page 73: C prog ppt

6) The tokens passed to macros can be concatenated using operator ## called Token-Pasting operator.

#include <stdio.h>#define merge(a, b) a##bint main(){ printf ("%d ", merge(12, 34));}

7) A token passed to macro can be converted to a sting literal by using # before it.

#include <stdio.h>#define message_for(a, b) \ printf(#a " and " #b ": We love you!\n")

int main(void){ message_for(Carole, Debra); return 0;}

Page 74: C prog ppt

8) The macros can be written in multiple lines using ‘\’. The last line doesn’t need to have ‘\’.

#include <stdio.h>#define PRINT(i, limit) while (i < limit) \ { \ printf ("GeeksQuiz "); \ i++; \ }int main(){ int i = 0; PRINT(i, 3); return 0;}

9) Find the output of following program#define square(x) x*xint main(){int x = 36/square(6);printf("%d", x); return 0;}

Page 75: C prog ppt

10) There are some standard macros

#include <stdio.h>int main(){ printf("Current File :%s\n", __FILE__ ); printf("Current Date :%s\n", __DATE__ ); printf("Current Time :%s\n", __TIME__ ); printf("Line Number :%d\n", __LINE__ ); return 0;}

11) Other directives in C a) #if, #elif, #else, #endif

#if constant_expression#else#endifor#if constant_expression#elif constant_expression#endif

Ex:int main(void) { #if 1 printf("Yabba Dabba Do!\n"); #else printf("Zip-Bang!\n"); #endif return 0;}

b) #define, #undef, #ifdef, #ifndef#define identifier replacement-code

#undef identifier

#ifdef identifier#else or #elif#endif

#ifndef identifier#else or #elif#endif

Page 76: C prog ppt

c) #error The #error directive will cause the compiler to halt compiling and return with the specified error message.

Syntax:

#error message

Examples:

#ifndef VERSION #error Version number not specified. #endif

d) #pragma #pragma startup function1 #pragma exit function 1

#pragma warning(disable:4700) #pragma warning(once:4700) #pragma warning(error:4700)

Page 77: C prog ppt

What is the output if following program?#include<stdio.h>int main(){ void v = 0; printf("%d", v); return 0;}

#include<stdio.h>int main(){ extern int a; printf("%d\n", a); return 0;}int a=20;

Page 78: C prog ppt

#include<stdio.h>int main(){ extern int i; i = 20; printf("%d\n", sizeof(i)); return 0;}

#include<stdio.h>

int main(){ printf("IndiaBIX"); main(); return 0;}

Page 79: C prog ppt

Point out errors in following code#include<stdio.h>int main(){ display(); return 0;}void display(){ printf("IndiaBIX.com");}

#include<stdio.h>int main(){ int j=1; while(j <= 255) { printf("%c %d\n", j, j); j++; } return 0;}

#include<stdio.h>int main(){ int x; for(x=-1; x<=10; x++) { if(x < 5) continue; else break; printf("IndiaBIX"); } return 0;}

#include<stdio.h>int main(){ int i=0; for(; i<=5; i++); printf("%d", i); return 0;}

Page 80: C prog ppt

#include<stdio.h>int main(){ int a = 500, b = 100, c; if(!a >= 400) b = 300; c = 200; printf("b = %d c = %d\n", b, c); return 0;}

#include<stdio.h>int main(){ int i=1; for(;;) { printf("%d\n", i++); if(i>10) break; } return 0;}

#include<stdio.h>int main(){ int a = 10; switch(a) { } printf("This is c program."); return 0;}#include<stdio.h>int main(){ int i = 1; switch(i) { printf("This is c program."); case 1: printf("Case1"); break; case 2: printf("Case2"); break;}return 0;}

Page 81: C prog ppt

#include<stdio.h>int main(){ int a = 5; switch(a) { case 1: printf("First");

case 2: printf("Second");

case 3 + 2: printf("Third");

case 5: printf("Final"); break;

} return 0;}

Page 82: C prog ppt

Syntax: Data type *var_name

#include <stdio.h>int main (){ int var = 20; /* actual variable declaration */ int *ip; /* pointer variable declaration */ ip = &var; /* store address of var in pointer variable*/ printf("Address of var variable: %x\n", &var ); printf("Address stored in ip variable: %x\n", ip ); printf("Value of *ip variable: %d\n", *ip ); return 0;}

/* null pointer in c*/#include <stdio.h>int main (){ int *ptr = NULL; printf("The value of ptr is : %x\n", ptr ); return 0;}

Pointer

A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address. The general form of a pointer variable declaration is:

Page 83: C prog ppt

Incrementing a PointerWe prefer using a pointer in our program instead of an array because the variable pointer can be

incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array:

#include <stdio.h>const int MAX = 3;int main (){ int var[] = {10, 100, 200}; int i, *ptr;ptr = var; for ( i = 0; i < MAX; i++) { printf("Address of var[%d] = %u\n", i, ptr ); printf("Value of var[%d] = %d\n", i, *ptr );

ptr++; /* move to the next location */ } return 0;}

Page 84: C prog ppt

Pointer to Pointer in CA pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer

contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.Syntax: int **var_name;

#include <stdio.h>int main (){ int var; int *ptr; int **pptr; var = 3000; ptr = &var; pptr = &ptr; printf("Value of var = %d\n", var ); printf("Value available at *ptr = %d\n", *ptr ); printf("Value available at **pptr = %d\n", **pptr); return 0;}

Page 85: C prog ppt

Passing pointer to function

#include <stdio.h>#include <time.h>void getSeconds(unsigned long *par);int main (){ unsigned long sec; getSeconds( &sec ); /* print the actual value */ printf("Number of seconds: %ld\n", sec ); return 0;}void getSeconds(unsigned long *par){ /* get the current number of seconds */ *par = time( NULL ); return;}

#include <stdio.h>double getAverage(int *arr, int size);int main (){int balance[5] = {1000, 2, 3, 17, 50};double avg;avg = getAverage( balance, 5 ) ;printf("Average value is: %f\n", avg );return 0;}double getAverage(int *arr, int size){ int i, sum = 0; double avg; for (i = 0; i < size; ++i) sum += arr[i]; avg = (double)sum / size; return avg;}}

Page 86: C prog ppt

Strings

• C Strings are nothing but array of characters ended with null character (‘\0’).• This null character indicates the end of the string.• Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.

Example for C string:

char string[20] = { ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘2’ , ‘r’ , ‘e’ , ‘f’ , ’r’ , ‘e’ , ‘s’ , ‘h’ , ‘\0’}; (or) char string[20] = “fresh2refresh”; (or) char string [] = “fresh2refresh”;

char greeting[] = "Hello";

Following is the memory presentation of above defined string in C:String Presentation in C

Page 87: C prog ppt

Ex: #include <stdio.h>int main (){ char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; printf("Greeting message: %s\n", greeting ); return 0;}

Page 88: C prog ppt

/*program to reverse a string*/#include<stdio.h>#include<string.h>void main(){ char str[100],temp; int i,j=0; printf("nEnter the string :"); gets(str); i=0; j=strlen(str)-1; while(i<j) { temp=str[i]; str[i]=str[j]; str[j]=temp; i++; j--; } printf("nReverse string is :%s",str); return(0);}

Page 89: C prog ppt
Page 90: C prog ppt

String handling functionsFollowing are some of the useful string handling functions supported by C.

1) strlen()2) strcpy()3) strncpy()4) strcat()5) strncat()6) strcmp()7) strncmp()8) strcmpi()9) strncmpi()

strlen()

strlen() function returns the length of the string. strlen() function returns integer value.

char *str = "Learn C Online";int strLength;strLength = strlen(str); //strLength contains the length of the string i.e. 14

Page 91: C prog ppt

strcpy()

function is used to copy one string to another. The Destination_String should be a variable and Source_String can either be a string constant or a variable.

Syntax:strcpy(Destination_String,Source_String);

char *Destination_String;char *Source_String = "Learn C Online";strcpy(Destination_String,Source_String);printf("%s", Destination_String);

Page 92: C prog ppt

strncpy()

strncpy() is used to copy only the left most n characters from source to destination. The Destination_String should be a variable and Source_String can either be a string constant or a variable.Syntax:strncpy(Destination_String, Source_String,no_of_characters);

strcat()

strcat() is used to concatenate two strings.The Destination_String should be a variable and Source_String can either be a string constant or a variable.Syntax:strcat(Destination_String, Source_String);

char *Destination_String ="Learn ";char *Source_String = "C Online";strcat(Destination_String, Source_String);puts( Destination_String);

Page 93: C prog ppt

char *Destination_String="Visit ";char *Source_String = "Learn C Online is a great site";strncat(Destination_String, Source_String,14);puts( Destination_String);

strncat()

strncat() is used to concatenate only the leftmost n characters from source with the destination string.The Destination_String should be a variable and Source_String can either be a string constant or a variable.Syntax:strncat(Destination_String, Source_String,no_of_characters);

Page 94: C prog ppt

strcmp()

strcmp() function is use two compare two strings. strcmp() function does a case sensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable.

Syntax:int strcmp(string1, string2);This function returns integer value after comparison.

char *string1 = "Learn C Online";char *string2 = "Learn C Online";int ret;ret=strcmp(string1, string2);printf("%d",ret);

Page 95: C prog ppt

strncmp()

strncmp() is used to compare only left most ‘n’ characters from the strings.

Syntax:int strncmp(string1, string2,no_of_chars);This function returns integer value after comparison.Value returned is 0 if left most ‘n’ characters of two strings are equal.

char *string1 = "Learn C Online is a great site";char *string2 = "Learn C Online";int ret;ret=strncmp(string1, string2,7);printf("%d",ret);

Page 96: C prog ppt

strcmpi()

strcmpi() function is use two compare two strings. strcmp() function does a case insensitive comparison between two strings. The Destination_String and Source_String can either be a string constant or a variable.

Syntax:int strcmpi(string1, string2);This function returns integer value after comparison.

char *string1 = “Learn C Online”;char *string2 = “LEARN C ONLINE”;int ret;ret=strcmpi(string1, string2);printf("%d",ret);

Page 97: C prog ppt

strncmpi()

strncmpi() is used to compare only left most ‘n’ characters from the strings. strncmpi() function does a case insensitive comparison.

Syntax:int strncmpi(string1, string2,no_of_chars);This function returns integer value after comparison.

char *string1 = "Learn C Online is a great site";char *string2 = "LEARN C ONLINE";int ret;ret=strncmpi(string1, string2,7);printf("%d",ret);

Page 98: C prog ppt

-- Find the difference between int *const ptr and int const *ptr

-- Prog to calc size of float pointer, integer pointer, char pointer.

-- Find the difference between *ptr++ and ++*ptr

-- Swap two numbers using pointer function

-- Prog to reverse a string using pointers

-- Prog to implement all the above string handling functions.

-- Prog to find number of times each letter repeated in a sentence

-- Prog to concatenate two strings without using string.h

-- Prog to find if a given string is palindrome or not

-- Prog to convert string of upper case to lower and lower case to upper

-- Prog to find sum of diagonals of matrix

-- Prog to add two matrices.

-- Prog to find transpose of matrix.

Page 99: C prog ppt

Prog to find number of times letter is repeating in string

for(j=0;j<m;j++){for(i=0;i<len;i++){if(string[j]==string[i])c++;}if(c>=2){printf("\nnumber of times %c repeating is: %d\n",str[j], c);}c=0;}

Page 100: C prog ppt

main()

{

int balance;

int *address;

int value;

balance = 5000;

address = &balance;

value = *address;

printf("Balance is : %d\n" , value);

}

Page 101: C prog ppt

main(){

int *p , num;

p = &num;

*p = 100;

printf("%d\n" , num);

(*p)++;

printf("%d\n" , num);

(*p)--;

printf("%d\n" , num);

}

Page 102: C prog ppt

Sorting algorithms in C

Bubble sort algorithm

Selection sort algorithm

Page 103: C prog ppt

Insertion sort

Page 104: C prog ppt

Bubble sort algorithm#include<stdio.h>int main(){ int s,temp,i,j,a[20]; printf("Enter total numbers of elements: "); scanf("%d",&s); printf("Enter %d elements: ",s); for(i=0;i<s;i++) scanf("%d",&a[i]); for(i=s-2;i>=0;i--){ for(j=0;j<=i;j++){ if(a[j]>a[j+1]){ temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("After sorting: "); for(i=0;i<s;i++) printf(" %d",a[i]); return 0;}

Page 105: C prog ppt

Bubble sort algorithm#include<stdio.h>int main(){ int s,temp,i,j,a[20]; printf("Enter total numbers of elements: "); scanf("%d",&s); printf("Enter %d elements: ",s); for(i=0;i<s;i++) scanf("%d",&a[i]); for(i=s-2;i>=0;i--){ for(j=0;j<=i;j++){ if(a[j]>a[j+1]){ temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } printf("After sorting: "); for(i=0;i<s;i++) printf(" %d",a[i]); return 0;}

Page 106: C prog ppt

Linear searchint main(){ int array[100], search, c, n; printf("Enter the number of elements in array\n"); scanf("%d",&n); printf("Enter %d integer(s)\n", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); printf("Enter the number to search\n"); scanf("%d", &search); for (c = 0; c < n; c++) { if (array[c] == search) /* if required element found */ { printf("%d is present at location %d.\n", search, c+1); break; }} if (c == n) printf("%d is not present in array.\n", search); return 0;}

Page 107: C prog ppt

Binary search

#include <stdio.h>int main(){ int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n"); scanf("%d",&n);

printf("Enter %d integers\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d",&array[c]); // program assumes input numbers are in ascending order.

printf("Enter value to find\n"); scanf("%d",&search);

first = 0; last = n - 1; middle = (first+last)/2;

Page 108: C prog ppt

while( first <= last ) { if ( array[middle] < search ) first = middle + 1; else if ( array[middle] == search ) { printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1; middle = (first + last)/2; } if ( first > last ) printf("Not found! %d is not present in the list.\n", search); return 0; }

Page 109: C prog ppt

Structures in C

A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling.

Structures help organize complicated data, particularly in large programs, because they permit a group of related variables to be treated as a unit instead of as separate entities.

Page 110: C prog ppt

Uses of C structures:

•C Structures can be used to store huge data. Structures act as a database.•C Structures can be used to send data to the printer.•C Structures can interact with keyboard and mouse to store the data.•C Structures can be used in drawing and floppy formatting.•C Structures can be used to clear output screen contents.•C Structures can be used to check computer’s memory size etc.

Page 111: C prog ppt

#include <stdio.h>#include <string.h>struct student{ int id; char name[20]; float percentage;};int main(){ struct student record = {0}; //Initializing to null record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); return 0;}

Page 112: C prog ppt

/* prog to demonstrate structures in c*/

#include "stdio.h“void main( ){struct{char initial; /* last name initial */int age; /* childs age */int grade; /* childs grade in school */} boy, girl;boy.initial = 'R';boy.age = 15;boy.grade = 75;girl.age = boy.age - 1; /* she is one year younger */girl.grade = 82;girl.initial = 'H';printf("%c is %d years old and got a grade of %d\n",girl.initial, girl.age, girl.grade);printf("%c is %d years old and got a grade of %d\n",boy.initial, boy.age, boy.grade);}

Page 113: C prog ppt

Bit Fields

Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status, as follows:

struct{ unsigned int widthValidated; unsigned int heightValidated;} status;

Without using bit fields it consumes 8 bytes of memory.

Page 114: C prog ppt

Bit Fields

Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure called status, as follows:

struct{ unsigned int widthValidated : 1; unsigned int heightValidated : 1;} status;

Using using bit fields it consumes 2 bits of memory.

Page 115: C prog ppt

Bit Fieldsstruct{ unsigned int widthValidated; unsigned int heightValidated;} status1;struct{ unsigned int widthValidated : 1; unsigned int heightValidated : 1;} status2;int main( ){ printf( "Memory size occupied by status1 : %d\n", sizeof(status1)); printf( "Memory size occupied by status2 : %d\n", sizeof(status2)); return 0;}.

Page 116: C prog ppt

Array of structuresmain (){ struct item { char initial; int id_no; }; int j; struct item a[2]; clrscr(); printf ("\n Enter Code_no, Price\n "); for (j=0;j<2;j++) scanf ("%c %d",&a[j].initial,&a[j].id_no); printf ("\n information you entered are:"); for (j=0;j<2;j++) printf ("\n %c %d",a[j].initial,a[j].id_no);}

Page 117: C prog ppt

Nesting structures (structure within structure)

#include "stdio.h"void main( ){struct person {char name[25];int age;char status; /* M = married, S = single */} ;struct alldata {int grade;struct person descrip;char lunch[25];} student[53];struct alldata teacher,sub;

Page 118: C prog ppt

teacher.grade = 94;teacher.descrip.age = 34;teacher.descrip.status = 'M';strcpy(teacher.descrip.name,"Mary Smith");strcpy(teacher.lunch,“Veg sandwich");sub.descrip.age = 87;sub.descrip.status = 'M';strcpy(sub.descrip.name,"Old Lady Brown");sub.grade = 73;strcpy(sub.lunch,"Yogurt and toast");student[1].descrip.age = 15;student[1].descrip.status = 'S';strcpy(student[1].descrip.name,"Billy Boston");strcpy(student[1].lunch,"Peanut Butter");student[1].grade = 77;student[7].descrip.age = 14;student[12].grade = 87;}

Page 119: C prog ppt

/*another way of nesting structures*/struct Employee{ char ename[20]; int ssn; float salary; struct date { int date; int month; int year; }doj;}emp = {"Pritesh",1000,1000.50,{22,6,1990}};

Page 120: C prog ppt

Pointer to structure

Structure's member through pointer can be used in two ways:•Referencing pointer to another address to access memory•Using dynamic memory allocation

Page 121: C prog ppt

/*Example program to demonstrate referencing pointer to another address to access memory*/#include <stdio.h>struct name{ int a; float b;};int main(){ struct name *ptr,p; ptr=&p; /* Referencing pointer to memory address of p */ printf("Enter integer: "); scanf("%d",&(*ptr).a); printf("Enter number: "); scanf("%f",&(*ptr).b); printf("Displaying: "); printf("%d%f",(*ptr).a,(*ptr).b); return 0;}

Page 122: C prog ppt

/*Prog to demonstrate pointers to structures using dynamic memory allocation*/#include <stdio.h>#include<stdlib.h>struct name{ int a; float b; char c[30];};int main(){ struct name *ptr; int i,n; printf("Enter n: "); scanf("%d",&n); ptr=(struct name*)malloc(n*sizeof(struct name));/* Above statement allocates the memory for n structures with pointer ptr pointing to base address */

Page 123: C prog ppt

for(i=0;i<n;++i){ printf("Enter string, integer and floating number respectively:\n"); scanf("%s%d%f",&(ptr+i)->c,&(ptr+i)->a,&(ptr+i)->b); } printf("Displaying Infromation:\n"); for(i=0;i<n;++i) printf("%s\t%d\t%.2f\n",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b); return 0;}

Page 124: C prog ppt

Structure padding

In order to align the data in memory, one or more empty bytes (addresses) are inserted (or left empty) between memory addresses which are allocated for other structure members while memory allocation. This concept is called structure padding.

Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.

To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address.

Because of this structure padding concept in C, size of the structure is always not same as what we think.

Page 125: C prog ppt

#include <stdio.h>#include <string.h>struct student{ int id1; int id2; char a; char b; float percentage;};

Page 126: C prog ppt

int main(){ int i; struct student record1 = {1, 2, 'A', 'B', 90.5}; printf("size of structure in bytes : %d\n", sizeof(record1)); printf("\nAddress of id1 = %u", &record1.id1 ); printf("\nAddress of id2 = %u", &record1.id2 ); printf("\nAddress of a = %u", &record1.a ); printf("\nAddress of b = %u", &record1.b ); printf("\nAddress of percentage = %u",&record1.percentage); return 0;}

Page 127: C prog ppt

How to avoid structure padding in C?

•#pragma pack ( 1 ) directive can be used for arranging memory for structure members very next to the end of other structure members.

•VC++ supports this feature. But, some compilers such as Turbo C/C++ does not support this feature.

•Please check the below program where there will be no addresses (bytes) left empty because of structure padding.

Page 128: C prog ppt

Union

•C Union is also like structure, i.e. collection of different data types which are grouped together. Each element in a union is called member.

•Union and structure in C are same in concepts, except allocating memory for their members.

•Structure allocates storage space for all its members separately.

•Whereas, Union allocates one common storage space for all its members

Page 129: C prog ppt

#include <stdio.h>#include <string.h>union student{ char name[20]; char subject[20]; float percentage;};int main(){ union student record1; union student record2; // assigning values to record1 union variable strcpy(record1.name, "Raju"); strcpy(record1.subject, "Maths"); record1.percentage = 86.50; printf("Union record1 values example\n");

Page 130: C prog ppt

printf(" Name : %s \n", record1.name); printf(" Subject : %s \n", record1.subject); printf(" Percentage : %f \n\n", record1.percentage);

// assigning values to record2 union variable printf("Union record2 values example\n"); strcpy(record2.name, "Mani"); printf(" Name : %s \n", record2.name); strcpy(record2.subject, "Physics"); printf(" Subject : %s \n", record2.subject); record2.percentage = 99.50; printf(" Percentage : %f \n", record2.percentage); return 0;}

Page 131: C prog ppt

union intptr { int i; int * p; }; union intptr x; x.i = 1000; *(x.p)=90; /* puts 90 at location 1000 */

Example: use of union

Page 132: C prog ppt

union{ int i; float f;} u;

// Convert floating-point bits to integer:u.f = 3.14159f;printf("As integer: %08x\n", u.i);

Example: use of union

Page 133: C prog ppt

int f(int j){ static int i = 50; int k; if (i == j) { printf("something"); k = f(i); return 0; } else return 0;}

int func(int num){ int count = 0; while (num) { count++; num >>= 1; } return (count);}

Page 134: C prog ppt

#include <stdio.h>main(){ int i; int *pi = &i; scanf("%d", pi); printf("%d\n", i+5);}

Page 135: C prog ppt

Dynamic memory allocation in C:

The process of allocating memory during program execution is called dynamic memory allocation.

Dynamic memory allocation functions in C:

C language offers 4 dynamic memory allocation functions. They are,

1) malloc()2) calloc()3) realloc()4) free()

Page 136: C prog ppt

S.no Function Syntax

1 malloc () malloc (number *sizeof(int));

2 calloc () calloc (number, sizeof(int));

3 realloc () realloc (pointer_name, number * sizeof(int));

4 free () free (pointer_name);

Page 137: C prog ppt

1. malloc() function in C:

•malloc () function is used to allocate space in memory during the execution of the program.•malloc () does not initialize the memory allocated during execution. It carries garbage value.•malloc () function returns null pointer if it couldn’t able to allocate requested amount of memory.

Page 138: C prog ppt

#include <stdio.h>#include <string.h>#include <stdlib.h>int main(){ char *mem_allocation; mem_allocation = malloc( 20 * sizeof(char) ); /* memory is allocated dynamically */ if( mem_allocation== NULL ) { printf("Couldn't able to allocate requested memory\n"); } else { strcpy( mem_allocation,"fresh2refresh.com"); } printf("Dynamically allocated memory content : %s\n", mem_allocation ); free(mem_allocation);}

Page 139: C prog ppt

2. calloc() function in C:

calloc () function is also like malloc () function. But calloc () initializes the allocated memory to zero. But, malloc() doesn’t.

Page 140: C prog ppt

#include <stdio.h>#include <string.h>#include <stdlib.h>int main(){ char *mem_allocation; mem_allocation = calloc( 20, sizeof(char) ); /* memory is allocated dynamically */ if( mem_allocation== NULL ) { printf("Couldn't able to allocate requested memory\n"); } else { strcpy( mem_allocation,"fresh2refresh.com"); } printf("Dynamically allocated memory content : %s\n", mem_allocation ); free(mem_allocation);}

Page 141: C prog ppt

3. realloc() function in C:

•realloc () function modifies the allocated memory size by malloc () and calloc () functions to new size.•If enough space doesn’t exist in memory of current block to extend, new block is allocated for the full size of reallocation, then copies the existing data to new block and then frees the old block.

4. free() function in C:

free () function frees the allocated memory by malloc (), calloc (), realloc () functions and returns the memory to the system.

Page 142: C prog ppt

#include <stdio.h>#include <string.h>#include <stdlib.h>int main(){ char *mem_allocation; /* memory is allocated dynamically */ mem_allocation = malloc( 20 * sizeof(char) ); if( mem_allocation == NULL ) { printf("Couldn't able to allocate requested memory\n"); } else { strcpy( mem_allocation,"fresh2refresh.com"); } printf("Dynamically allocated memory content : %s\n", mem_allocation );

Page 143: C prog ppt

typedef

Typedef is a keyword that is used to give a new symbolic name for the existing name in a C program. This is same like defining alias for the commands.

Page 144: C prog ppt

Consider the below structure.

struct student{ int mark [2]; char name [10]; float average;}

Variable for the above structure can be declared in two ways.

1st way :struct student record; /* for normal variable */struct student *record; /* for pointer variable */

2nd way :typedef struct student status;

Page 145: C prog ppt

An alternative way for structure declaration using typedef in C:

typedef struct student{ int mark [2]; char name [10]; float average;} status;

To declare structure variable, we can use the below statements.status record1; /* record 1 is structure variable */status record2; /* record 2 is structure variable */

Page 146: C prog ppt

#include <stdio.h>#include <string.h>typedef struct student // Structure using typedef:{ int id; char name[20]; float percentage;} status;int main(){ status record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; printf(" Id is: %d \n", record.id); printf(" Name is: %s \n", record.name); printf(" Percentage is: %f \n", record.percentage); return 0;}

Page 147: C prog ppt

Another example program for C typedef:

#include <stdio.h>#include <limits.h>

int main(){ typedef long long int LLI;

printf("Storage size for long long int data type : %ld \n", sizeof(LLI));

return 0;}

Page 148: C prog ppt

Stack in C

•Stack is a specialized data storage structure (Abstract data type). Unlike, arrays access of elements in a stack is restricted.•

•It has two main functions push and pop. Insertion in a stack is done using push function and removal from a stack is done using pop function.•

•Stack allows access to only the last element inserted hence, an item can be inserted or removed from the stack from one end called the top of the stack. It is therefore, also called Last-In-First-Out (LIFO) list.

Page 149: C prog ppt
Page 150: C prog ppt

Applications of stack:

•Balancing of symbols•

•Infix to Postfix/Prefix conversion•

•Redo-undo features at many places like editors, photoshop.•

•Forward and backward feature in web browsers

Page 151: C prog ppt

/*Example illustrating stack operation in c*/#include <stdio.h>#include <conio.h>#define MAXSIZE 5struct stack /* Structure definition for stack */{

int stk[MAXSIZE];int top;

};typedef struct stack STACK;STACK s;

/* Function declaration/Prototype*/void push (void);int pop(void);void display (void);

Page 152: C prog ppt

void main (){

int choice;int option = 1;clrscr ();s.top=-1;

printf ("STACK OPERATION\n");while (option){printf ("------------------------------------------\n");

printf (" 1 --> PUSH \n");printf (" 2 --> POP \n");printf (" 3 --> DISPLAY \n");printf (" 4 --> EXIT \n");

printf ("------------------------------------------\n");printf ("Enter your choice\n");scanf ("%d", &choice);

Page 153: C prog ppt

switch (choice){

case 1: push();break;

case 2: pop();break;

case 3: display();break;

case 4: return;}fflush (stdin);

printf ("Do you want to continue(Type 0 or 1)?\n");scanf ("%d", &option);

}}

Page 154: C prog ppt

/*Function to add an element to the stack*/void push (){ int num;

if (s.top == (MAXSIZE - 1)){

printf ("Stack is Full\n");return;

}else{

printf ("Enter the element to be pushed\n");scanf ("%d", &num);s.top = s.top + 1;s.stk[s.top] = num;

}return;

}

Page 155: C prog ppt

/*Function to delete an element from the stack*/int pop (){

int num;if (s.top == - 1){

printf ("Stack is Empty\n");return (s.top);

}else

{num = s.stk[s.top];printf ("poped element is = %d\n", s.stk[s.top]);s.top = s.top - 1;

}return(num);

}

Page 156: C prog ppt

/*Function to display the status of the stack*/void display (){

int i;if (s.top == -1){

printf ("Stack is empty\n");return;

}else{

printf ("\nThe status of the stack is\n");for (i = s.top; i >= 0; i--)

printf ("%d\n", s.stk[i]);}printf ("\n");

}

Page 157: C prog ppt

•Queue is a data structure which works as FIFO principle. FIFO means “First in First out”, i.e the element which we have inserted first will be deleted first and the element that we have inserted last will be deleted last.•

•You can have c program to implement queue using array, using stack and using linked list. Two variables are used to implement queue, i.e “rear” and “front”. Insertion will be done at rear side and deletion will be performed at front side. Figure below will show you and will make some concept of queue.•

•Queue can be implemented as simple queue, circular queue, dequeue, priority queue.

Queue in C

Page 158: C prog ppt

Applications of Queue:

Queue is used when things don’t have to be processed immediately, but have to be processed in First In First Out order like Breadth First Search. This property of Queue makes it also useful in following kind of scenarios.

1) When a resource is shared among multiple consumers. Examples include CPU scheduling, Disk Scheduling.

2) When data is transferred asynchronously (data not necessarily received at same rate as sent) between two processes. Examples include IO Buffers, pipes, file IO, etc.

-- Following code describes simple queue implementation.

Page 159: C prog ppt

#include<stdio.h>#define MAX 3int queue[MAX],front=-1,rear=-1;void push_element();void pop_element();void display_queue();int num;int main(){ int op; do { printf("\n\n 1.Insert an element"); printf("\n 2.Delete an element"); printf("\n 3.Display queue"); printf("\n 4.Exit"); printf("\n Enter your choice: "); scanf("%d",&op);

Page 160: C prog ppt

switch(op) { case 1: push_element(); break; case 2: pop_element(); break; case 3: display_queue(); break; case 4: return 0; break; default: printf("\n\ninvalid number\n"); } }while(op!=4);}

Page 161: C prog ppt

void push_element(){if(rear==MAX-1)printf("\n\nQueue is full");else{printf("\n\nenter number to be inserted");scanf("%d",&num);if(rear==-1 && front==-1){rear=0;front=0;}elserear++;queue[rear]=num;printf("\n\n num inserted is: queue[%d]=%d",rear,num);}}

Page 162: C prog ppt

void pop_element(){if(front==rear+1){printf("\n\nqueue is empty\n");rear=-1;}else{num=queue[front];printf("\n\nnum popped is:queue[%d]=%d\n",front,num);front++;}}

Page 163: C prog ppt

void display_queue(){int i;if(front==rear+1){printf("\n\nqueue has no elements to display\n");}else

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

Page 164: C prog ppt

Dequeues (double ended queues)

•A deque is a double-ended queue•Insertions and deletions can occur at either end•Implementation is similar to that for queues•Deques are not heavily used

Page 165: C prog ppt

#include<stdio.h>

#define MAX 5

int front=-1,rear=-1;int x;int q[MAX];

void insert_rear(void);void display(void);void delete_rear(void);void insert_front(void);void delete_front(void);

Page 166: C prog ppt

int main(){int op;int item;do{printf("\n\n 1 -- INSERT at rear end");printf("\n\n 2 -- INSERT at front end");printf("\n\n 3 -- DELETE at rear end");printf("\n\n 4 -- DELETE at front end");printf("\n\n 5 -- display");printf("\n\n 6 -- EXIT");scanf("%d", &op);

Page 167: C prog ppt

switch(op){case 1: insert_rear();break;case 2: insert_front();break;case 3: delete_rear();break;case 4: delete_front();break;case 5: display();break;case 6: return 0;break;default: printf("invalid number\n");}}while(op!=6);}

Page 168: C prog ppt

void insert_rear(void){int num;printf("enter number to be inserted\n");scanf("%d",&num);if(rear==MAX-1) printf("\n Queue is full...");else if(rear==-1){rear=0;front=0;q[rear]=num;} else{rear++; q[rear]=num;}}

void insert_front(void){ int no; printf("\n Enter value to insert:-"); scanf("%d",&no); if(front<=0) { printf("\n Cannot add value at front end"); return; } else { front--; q[front]=no;

printf("q[%d]=%d\n", front,q[front]);printf("rear is %d, front is %d\n",rear, front); }

}

void delete_rear(void){ int num; if(rear==-1) { printf("\n Cannot delete value at rear end\n"); return; } else { num=q[rear]; q[rear]=0; if(front>rear) { front=-1; rear=-1; } else { rear--; } } printf("\n Deleted element is %d\n",num); }

void delete_front(void){ int num; if(front==-1 && rear==-1) { printf("\n Cannot delete value at front end\n"); return; } else { num=q[front]; q[front]=0; if(front>rear) { front=-1; rear=-1; } else { front++; } } printf("\n Deleted element is %d\n",num); }

void display(void){ int i; if(front<=0 && rear==-1) { printf("\n Queue is Underflow\n"); return; } else { printf("\n Output"); for(i=0;i<=MAX-1;i++) { printf("\n %d",q[i]); } }}

Page 169: C prog ppt

void insert_front(void){int no;printf("\n Enter value to insert:-");scanf("%d",&no);if(front<=0){printf("\n Cannot add value at front end");return;}else{front--; q[front]=no;printf("q[%d]=%d\n", front,q[front]);printf("rear is %d, front is %d\n",rear, front);}}

Page 170: C prog ppt

void delete_rear(void){ int num; if(rear==-1) { printf("\n Cannot delete value at rear end\n"); return; } else { num=q[rear]; q[rear]=0; if(front>rear) { Front=-1; rear=-1; } else rear--; } printf("\n Deleted element is %d\n",num);}

Page 171: C prog ppt

void delete_front(void){ int num; if(front==-1 && rear==-1) { printf("\n Cannot delete value at front end\n"); return; } else { num=q[front]; q[front]=0; if(front>rear) { Front=-1; rear=-1; } else front++; } printf("\n Deleted element is %d\n",num); }

Page 172: C prog ppt

void display(void){ int i; if(front<=0 && rear==-1) { printf("\n Queue is Underflow\n"); return; } else { printf("\n Output"); for(i=0;i<=MAX-1;i++) { printf("\n %d",q[i]); } }}

Page 173: C prog ppt

Circular queues in C

Circular queue c is also implemented as same as simple queue, the main difference is that in circular queue last element will again points to first element as shown in figure.

Page 174: C prog ppt

#include<stdio.h>#define MAX 3int queue[MAX],front=-1,rear=-1;void push_element();void pop_element();void display_queue(); int num;int main(){int op;do { printf("\n\n 1.Insert an element"); printf("\n 2.Delete an element"); printf("\n 3.Display queue"); printf("\n 4.Exit"); printf("\n Enter your choice: "); scanf("%d",&op);

Page 175: C prog ppt

switch(op) { case 1: push_element(); break; case 2: pop_element(); break; case 3: display_queue(); break; case 4: return 0; break; default: printf("\n\ninvalid number\n"); }

}while(op!=4);

}

void push_element(){if((front==0 && rear==MAX-1)){printf("\n\nQueue is full");}else{if((rear==-1)||(rear==MAX-1)){printf("\n\nenter number to be inserted");scanf("%d",&num);rear=0;front=0;queue[rear]=num;}else{rear++; if((queue[rear] != 0)&&(rear!=0)){printf("\n\nQueue is full");return 0;}printf("\n\nenter number to be inserted");scanf("%d",&num);queue[rear]=num;printf("\n\n num inserted is: queue[%d]=%d",rear,num);}}}

Page 176: C prog ppt

void push_element(){if((front==0 && rear==MAX-1)){printf("\n\nQueue is full");}else{if((rear==-1)||(rear==MAX-1)){printf("\n\nenter number to be inserted");scanf("%d",&num);rear=0;front=0;queue[rear]=num;}

Page 177: C prog ppt

else{rear++; if((queue[rear] != 0)&&(rear!=0)){printf("\n\nQueue is full");goto x;}printf("\n\nenter number to be inserted");scanf("%d",&num);queue[rear]=num;printf("\n\n num inserted is: queue[%d]=%d",rear,num);}x:printf("\n\n rear is %d and front is %d",rear,front);}}

Page 178: C prog ppt

void pop_element(){if((front==-1)||(front==rear+1))printf("\n\nqueue is empty\n");else{num=queue[front];queue[front]=0;if(front==rear){ front=-1; rear=-1; }else if(front==MAX-1)front=0;elsefront++;printf("\n\nnum popped is:queue[%d]=%d\n",front,num);}printf("\n\n rear is %d and front is %d",rear,front);}

Page 179: C prog ppt

void display_queue(){int i;printf("\n\n rear is %d and front is %d",rear,front);if((front==-1))//||(front==rear+1)){printf("\n\nqueue has no lements to display\n");}else{for(i=0;i<=2;i++)printf("\n\nqueue[%d]=%d",i,queue[i]);}}

Page 180: C prog ppt

Priority queue

A priority queue is an abstract data type which is like a regular queue or stack data structure, but where additionally each element has a "priority" associated with it. In a priority queue, an element with high priority is served before an element with low priority. If two elements have the same priority, they are served according to their order in the queue.

Page 181: C prog ppt

/* C Prog to Implement Priority Queue to Add and Delete Elements (sorts in decreasing order) */

#include <stdio.h>#include <stdlib.h> #define MAX 5 void insert_by_priority(int);void delete_by_priority(int);void create();void check(int);void display_pqueue(); int pri_que[MAX];int front, rear; void main(){ int n, ch; printf("\n1 - Insert an element into queue"); printf("\n2 - Delete an element from queue"); printf("\n3 - Display queue elements"); printf("\n4 - Exit"); create();

while (1) { printf("\nEnter your choice : "); scanf("%d", &ch); switch (ch) { case 1: printf("\nEnter value to be inserted : "); scanf("%d",&n); insert_by_priority(n); break; case 2: printf("\nEnter value to delete : "); scanf("%d",&n); delete_by_priority(n); break; case 3: display_pqueue(); break; case 4: exit(0); default: printf("\nChoice is incorrect, Enter a correct choice"); } }}

Page 182: C prog ppt

void create(){ front = rear = -1;}

/* Function to insert value into priority queue */void insert_by_priority(int data){ if (rear >= MAX - 1) { printf("\nQueue overflow no more elements can be inserted"); return; } if ((front == -1) && (rear == -1)) { front++; rear++; pri_que[rear] = data; return; } else check(data); rear++;}

/* Function to check priority and place element */void check(int data){ int i,j; for (i = 0; i <= rear; i++) { if (data >= pri_que[i]) { for (j = rear + 1; j > i; j--) { pri_que[j] = pri_que[j - 1]; } pri_que[i] = data; return; } } pri_que[i] = data;}

Page 183: C prog ppt

/* Function to delete an element from queue */void delete_by_priority(int data){ int i; if ((front==-1) && (rear==-1)) { printf("\nQueue is empty no elements to delete"); return; } for (i = 0; i <= rear; i++) { if (data == pri_que[i]) { for (; i < rear; i++) { pri_que[i] = pri_que[i + 1]; } pri_que[i] = -99; rear--; if (rear == -1) front = -1; return; } } printf("\n%d not found in queue to delete", data);}

/* Function to display queue elements */void display_pqueue(){ if ((front == -1) && (rear == -1)) { printf("\nQueue is empty"); return; } for (; front <= rear; front++) { printf(" %d ", pri_que[front]); } front = 0;}

Page 184: C prog ppt

Linked List

Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at contiguous location; the elements are linked using pointers.

Why Linked List?Arrays can be used to store linear data of similar types, but arrays have following limitations.1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage.2) Inserting a new element in an array of elements is expensive, because room has to be created for the new elements and to create room existing elements have to shifted.

For example, in a system if we maintain a sorted list of IDs in an array id[].

id[] = [1000, 1010, 1050, 2000, 2040].

And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000).Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved.

Advantages over arrays1) Dynamic size2) Ease of insertion/deletion

Drawbacks:1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists.2) Extra memory space for a pointer is required with each element of the list.

Page 185: C prog ppt

Representation in C:

A linked list is represented by a pointer to the first node of the linked list. The first node is called head. If the linked list is empty, then value of head is NULL.

Each node in a list consists of at least two parts:1) data2) pointer to the next node

In C, we can represent a node using structures. Below is an example of a linked list node with an integer data.

struct node{ int data; struct node *next;};

Page 186: C prog ppt

Program to create liked list and print the data in linked list

#include<stdio.>#include<conio.h>#include<stdlib.h> or #include<alloc.h>

struct node{int data;struct node *next;} *start=NULL;

void create(){char ch;do{struct node *new_node, *current;new_node=(struct node *)malloc(sizeof(struct node));printf(“enter the data :”);scanf(“%d”,&new_node->data);new_node->next=NULL;if(start==NULL){start=new_node;current=new_node;}

else{current->next=new_node;current=new_node;}printf(“do u want to create another :”);ch=getche();}while(ch!=‘n’);}void display(){struct node *new_node;printf(“the linked list : n”);new_node=start;while(new_node!=NULL){printf(“%d-”,new_node->data);new_node=new_node->next;}printf(“NULL”);}void main(){create();display();}

Page 187: C prog ppt

/* function to count length of linked list */

void count(){struct node *temp;int length=0;temp=start;while(temp!=NULL){length++;temp=temp->next;}printf(“length of linked list : %d”, length);}

/*function to traverse and search for data in linked list*/int search (int num){int flag=0;struct node *temp;temp=start;while(temp!=NULL){if (temp->data==num)return (1); //foundtemp=temp->next;}if(flag==0)return (0);// not found}

/*function to insert node at the end*/

Void insert_at_end(){Struct node *new_node, *current;New_node= (struct node*) malloc (sizeof(struct node));If(“new_node==null)Printf(“\n failed to allocate memory\n”);Printf(“\n enter the data :”);Scanf(“%d”, &new_node->data);New_node->next=null;If(start==null){Start=new_node;Current=new_node;}Else{Temp=start;While(temp->next!=null){Temp=temp->next;}Temp->next=new_node;}}

Page 188: C prog ppt

/*prog to delete first node from the linked list*/

void del_beg(){struct node *temp;

temp = start;start = start->next;

free(temp);printf("nThe Element deleted Successfully ");}

-- write a prog to delete last node from a linked list

/*function to insert node at the middle of the linked list*/

void insert_mid(){ int pos,i; struct node *new_node,*current,*temp,*temp1;

new_node=(struct node *)malloc(sizeof(struct node));

printf("nEnter the data : "); scanf("%d",&new_node->data); new_node->next=NULL;

st : printf("nEnter the position : "); scanf("%d",&pos);

if(pos>=(length()+1)) { printf("nError : pos > length "); goto st; } if(start==NULL) { start=new_node; current=new_node; }

else { temp = start; for(i=1;i< pos-1;i++) { temp = temp->next; } temp1=temp->next; temp->next = new_node; new_node->next=temp1; }}

Page 189: C prog ppt

Circular linked list

Circular linked list is divided in too 2 catagories:

•Singly circular linked list•Doubly circular linked list

Circular singly linked list

•Singly Linked List has a major drawback. From a specified node, it is not possible to reach any of the preceding nodes in the list. To overcome the drawback, a small change is made to the SLL so that the next field of the last node is pointing to the first node rather than NULL. Such a linked list is called a circular linked list.

•Because it is a circular linked list, it is possible to reach any node in the list from a particular node.

•There is no natural first node or last node because by virtue of the list is circular.

Page 190: C prog ppt

Tree in C

The binary tree is a fundamental data structure used in computer science. The binary tree is a useful data structure for rapidly storing sorted data and rapidly retrieving stored data.

A binary tree is made of nodes, where each node contains a "left" pointer, a "right" pointer, and a data element. The "root" pointer points to the topmost node in the tree. The left and right pointers recursively point to smaller "subtrees" on either side. A null pointer represents a binary tree with no elements -- the empty tree. The formal recursive definition is: a binary tree is either empty (represented by a null pointer), or is made of a single node, where the left and right pointers (recursive definition ahead) each point to a binary tree.

Page 191: C prog ppt

#include<stdio.h>#include<stdlib.h>typedef struct treeNode{ int data; struct treeNode *left; struct treeNode *right;}treeNode;treeNode* FindMin(treeNode *node){ if(node==NULL) {

return NULL; } if(node->left) /* Go to the left sub tree to find the min element */ return FindMin(node->left); else return node;}treeNode* FindMax(treeNode *node){ if(node==NULL) {

return NULL; } if(node->right) /* Go to the left sub tree to find the min element */ FindMax(node->right); else return node;}

treeNode * Insert(treeNode *node,int data){ if(node==NULL) { treeNode *temp; temp = (treeNode *)malloc(sizeof(treeNode)); temp -> data = data; temp -> left = temp -> right = NULL; return temp; }

if(data >(node->data)) { node->right = Insert(node->right,data); } else if(data < (node->data)) { node->left = Insert(node->left,data); } /* Else there is nothing to do as the data is already in the tree. */ return node;

}

Page 192: C prog ppt

treeNode * Find(treeNode *node, int data){ if(node==NULL) { /* Element is not found */ return NULL; } if(data > node->data) { /* Search in the right sub tree. */ return Find(node->right,data); } else if(data < node->data) { /* Search in the left sub tree. */ return Find(node->left,data); } else { /* Element Found */ return node; }} void del_tree(treeNode * node){ if (node) { del_tree(node->left); del_tree(node->right); free(node); }}

Page 193: C prog ppt

int main(){ treeNode *root = NULL; root = Insert(root, 5); root = Insert(root, -1); root = Insert(root, 3); root = Insert(root, -14); root = Insert(root, 8); root = Insert(root, 10); root = Insert(root, 9); root = Insert(root, 6); treeNode * temp; temp = FindMin(root); printf("Minimum element is %d\n",temp->data); temp = FindMax(root); printf("Maximum element is %d\n",temp->data); temp = Find(root,8); if(temp==NULL) { printf("Element 8 not found\n"); } else printf("Element 8 Found\n"); }

temp = Find(root,2); if(temp==NULL) { printf("Element 2 not found\n"); } else { printf("Element 6 Found\n"); }Del_tree(root);}

Page 194: C prog ppt

The Manual (terminal mode) man This command brings up the online Unixmanual. Use it on each of the commands below. For Example: man pwd You will see the manual for the pwd command. Accessing files in Folders (Directories) in terminal mode pwd Shows what directory (folder) you are in.In Linux, your home directory is /home/particle · Let's suppose you have several data files (data1, data2 ... etc.) in a directory called muondata.· Then suppose the directory muondata is an entry in your main home directory, /home/particle .· If you are in your home directory (where terminals start) and type pwd, you will see /home/particle.· If you were in the muondata directory, pwd would give you /home/particle/muondata instead · The last slash after a directory name is optional. As you can see, each slash (/) indicates another sub-directory.cd Changes directories. Examples of relative movement among directories:cd muondata Moves down from your current directoryinto the muondata sub-directory

Page 195: C prog ppt

cd .. Moves up one directory (yes, include thetwo little dots) You can also move directly into directoriescd /home/particle/muondata Moves from ANY directory into the muondatasub-directory of your home directory. cd ~ Takes you back to your home directory(/home/particle) Making or Removing a Directory (terminal mode) mkdir dirName Creates a directory with name dirName. For Example:mkdir temp Creates the directory temp. rmdir dirName Removes a directory dirName. For Example:rmdir temp Removes the directory temp. Looking at or Finding your Files (terminal mode) ls Lists files. If you add -al after ls it will give more details for each file. Such as, size, permissions, owners, dates etc.

Page 196: C prog ppt

ls al You'll see a huge list of files that you can't see with the 'ls' command alone and lots of details. If you see such a long list of files that they scroll off the terminal screen, one way to solve the problem is to use: ls -al |more Shows one screen of file names at a time. less data1 Dumps the contents of the data1 file to your screen with a pause at each line so you don't miss any contents as they scroll. You may move through the file using page up, page down, home and end keys. When done with less you use the q key to get back to the main terminal. whereis data1 Shows you the location of the data1 file. Altering your Files rm data1 Deletes the file data1 in the current directory. rm -i muon* Removes all of your muon data files(careful!! rm * will remove ALL your files) The "-i" makes the computer prompt before removing each file. If you really want to work without a net, omit the "-i". cp data1 newdata/ will copy the file data1 to the directory newdata (assuming it has already been created) mv data1 newdata/ moves the file data1 to the folder newdata and deletes the old one.