SlideShare a Scribd company logo
EMBEDDED SYSTEMS
PROGRAMMING
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 limited
qOften real-time response is essential
Application areas
ü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
Possible organization of embedded systems
Development cycle
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 developing
OSs,
System level programming,
Embedded Systems(including micro-controllers such as PIC, ARM, and MP),
RTOS,
Compilers,
website programming
libraries to other languages
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.
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).
structure of C a program
#include<stdio.h> /* Header File */
main () /* starting function */
{ /* start of program */
--------
Statements;
--------
Return;
}
Example C program
Ex:
/* Hello world Program*/
#include <stdio.h>
int main()
{
printf (“Hello worldn”);
return 0;
}
Compilation process
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.
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
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.
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("%dn",b);
printf("%3dn",b);
printf("%03dn",b);
c = 15.3;
d = c / 3;
printf("%3.2fn",d);
}
/*EXAMPLE*/
#include<stdio.h>
main()
{
printf("The color: %sn", "blue");
printf("First number: %dn", 12345);
printf("Second number: %04dn", 25);
printf("Third number: %in", 1234);
printf("Float number: %3.2fn", 3.14159);
printf("Hexadecimal: %xn", 255);
printf("Octal: %on", 255);
printf("Unsigned value: %un", 150);
printf("Just print the percentage sign %%n", 10);
}
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!");
}
Data types
- Primary data types
- Derived data types
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 Types
Following table gives you details about standard integer types with its storage
sizes and value ranges:
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
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: %En", FLT_MIN );
printf("Maximum float positive value: %En", FLT_MAX );
printf("Precision value: %dn", FLT_DIG );
return 0;
}
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
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.
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
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: +, /,-,*)
C tokens example program:
int main()
{
int x, y, total;
x=10, y=20;
total=x+y;
printf(“total=%dn”,total);
}
where,
main – identifier
{,}, (,) – delimiter
int – keyword
x, y, total – identifier
main, {, }, (, ), int, x, y, total – tokens
Operators
•Assignment operator
- (=, +=, -=, /=, %=, *=)
•Arithmetic operator
- C supports 5 operators : (+, -, *, /, %,++, --)
•Relational operator
-(<, >, <=, >=, ==, !=)
•Logical operator
-(&&, ||, !)
•Bitwise operator
-(&, |, ^, <<, >>)
Operators cotnd....
Conditional operator
Also called ternary operator or ?: operator
Ex: 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.
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
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
/* 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) ;
}
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 int
unsigned int
long int
long long int
53, 762, -478 etc
5000u, 1000U etc
483,647
2,147,483,680
2 Real or Floating point constants float
doule
10.456789
600.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”
Defining Constants
There are two simple ways in C to define constants:
-Using #define preprocessor.
-Using const keyword.
/* 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;
}
/* 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;
}
#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 %dn" , no);
printf("Double value is %lf n", dbl);
printf("Octal value is %o n", no);
printf("Hexadecimal value is %x n", no);
return 0;
}
#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);
}
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 | BitwiseOR
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
#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 = %dn",AND_opr );
printf("OR_opr value = %dn",OR_opr );
printf("NOT_opr value = %dn",NOT_opr );
printf("XOR_opr value = %dn",XOR_opr );
printf("left_shift value = %dn", m << 1);
printf("right_shift value = %dn", m >> 1);
}
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.
C provides two types of flow control
●Branching
●Looping
●
Branching
1. If Statement
2. The If else Statement
3. Compound Relational tests
4. Nested if Statement
5. Switch Statement
Loop control statements in C
1. for
2. while
3. do-while
If statement
if(condition)
{
statement;
}
If else statement
If(condition)
Program statement1
else
program statement 2
Compound relational test
a) if (condition1 && condition2 && condition3)
b) if (condition1 || condition2 || condition3)
Nested if statement
if (condition1)
if (condition2)
statement-1;
else
statement-2;
else
statement-3;
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.
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);
Loop control statements
•Break – exit from loop or switch
•Continue – skip one iteration in loop
//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;
}
-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
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.
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 = %dn",
a, b, c);
return 0;
}
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 = %dn",
a, b, c);
return 0;
}
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 = %dn", a, b, g);
return 0;
}
Formal Parameters
Function 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() = %dn", a);
c = sum( a, b);
printf ("value of c in main() = %dn", c);
return 0;
}
int sum(int a, int b) /* function to add two integers */
{
printf ("value of a in sum() = %dn", a);
printf ("value of b in sum() = %dn", b);
return a + b; }
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 Value
int 0
char '0'
float 0
double 0
pointer NULL
Storage class specifiers in C
There are 4 storage class specifiers available in C language. They are,
• auto
• extern
• static
• register
--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++;
}
Memory Layout of C programs
A typical memory representation of C program consists of following sections.
1. Text segment
2. Initialized data segment
3. Uninitialized data segment
4. Stack
5. Heap
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.
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
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
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.
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,
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
Declaring single dimensional array :
Syntax: data_type arr_name [size];
int a[10]; // integer array
char b[10]; // character array i.e. string
int 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]);
}
}
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] : %dn",i,j,arr[i][j]);
}}}
-- prog to Add elements of an array at odd position.
-- Prog to find intersection of 3 arrays.
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, ... ] );
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.
/*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);
}
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() */}
Macros in C
All the lines starting with # are processed by preprocessor
1) 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*b
int main()
{
printf("%d", MULTIPLY(2+3, 3+5));
return 0;
}
6) The tokens passed to macros can be concatenated using operator ## called Token-Pasting operator.
#include <stdio.h>
#define merge(a, b) a##b
int 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;
}
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*x
int main()
{
int x = 36/square(6);
printf("%d", x);
return 0;
}
10) There are some standard macros
#include <stdio.h>
int main()
{
printf("Current File :%sn", __FILE__ );
printf("Current Date :%sn", __DATE__ );
printf("Current Time :%sn", __TIME__ );
printf("Line Number :%dn", __LINE__ );
return 0;
}
11) Other directives in C
a) #if, #elif, #else, #endif
#if constant_expression
#else
#endif
or
#if constant_expression
#elif constant_expression
#endif
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)
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("%dn", a);
return 0;
}
int a=20;
#include<stdio.h>
int main()
{
extern int i;
i = 20;
printf("%dn", sizeof(i));
return 0;
}
#include<stdio.h>
int main()
{
printf("IndiaBIX");
main();
return 0;
}
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 %dn", j, j);
j++;
}
return 0;
}
#include<stdio.h>
int main()
{
int a = 500, b = 100, c;
if(!a >= 400)
b = 300;
c = 200;
printf("b = %d c = %dn", b, c);
return 0;
}
#include<stdio.h>
int main()
{
int i=1;
for(;;)
{
printf("%dn", i++);
if(i>10)
break;
}
return 0;
}
#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;
}
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: %xn", &var );
printf("Address stored in ip variable: %xn", ip );
printf("Value of *ip variable: %dn", *ip );
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:
Incrementing a Pointer
We 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] = %un", i, ptr );
printf("Value of var[%d] = %dn", i, *ptr );
ptr++; /* move to the next location */
}
return 0;
}
Pointer to Pointer in C
A 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 = %dn", var );
printf("Value available at *ptr = %dn", *ptr );
printf("Value available at **pptr = %dn", **pptr);
return 0;
}
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: %ldn", sec );
return 0;
}
void getSeconds(unsigned long *par)
{
/* get the current number of seconds */
*par = time( NULL );
return;
}
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
Ex: #include <stdio.h>
int main ()
{
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
printf("Greeting message: %sn", greeting );
return 0;
}
/*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);}
String handling functions
Following 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
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);
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);
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);
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);
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);
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);
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);
-- 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.
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: %dn",str[j], c);
}
c=0;
}
main()
{
int balance;
int *address;
int value;
balance = 5000;
address = &balance;
value = *address;
printf("Balance is : %dn" , value);
}
main()
{
int *p , num;
p = &num;
*p = 100;
printf("%dn" , num);
(*p)++;
printf("%dn" , num);
(*p)--;
printf("%dn" , num);
}
Sorting algorithms in C
Bubble sort algorithm
Selection sort algorithm
Insertion sort
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;
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;
Linear search
int main()
{
int array[100], search, c, n;
printf("Enter the number of elements in arrayn");
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 searchn");
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;
Binary search
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elementsn");
scanf("%d",&n);
printf("Enter %d integersn", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d",&array[c]); // program assumes input numbers are in ascending order.
printf("Enter value to findn");
scanf("%d",&search);
first = 0;
last = n - 1;
middle = (first+last)/2;
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;
}
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.
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.
#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);
/* 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 %dn",girl.initial, girl.age, girl.grade);
printf("%c is %d years old and got a grade of %dn",boy.initial, boy.age, boy.grade);
}
Bit Fields
Suppose your C program contains a number of TRUE/FALSE variables grouped in a structur
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status;
Without using bit fields it consumes 8 bytes of memory.
Bit Fields
Suppose your C program contains a number of TRUE/FALSE variables grouped in a structur
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
Using using bit fields it consumes 2 bits of memory.
Bit Fields
struct
{
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 : %dn", sizeof(status1));
printf( "Memory size occupied by status2 : %dn", sizeof(status2));
return 0;
}.
Array of structures
main ()
{
struct item
{
char initial;
int id_no;
};
int j;
struct item a[2];
clrscr();
printf ("n Enter Code_no, Pricen ");
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);
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];
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;
/*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}};
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
/*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;}
/*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
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("%st%dt%.2fn",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b);
return 0;
}
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.
#include <stdio.h>
#include <string.h>
struct student
{
int id1;
int id2;
char a;
char b;
float percentage;
};
int main()
{
int i;
struct student record1 = {1, 2, 'A', 'B', 90.5};
printf("size of structure in bytes : %dn", 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;
}
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.
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
#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 examplen");
printf(" Name : %s n", record1.name);
printf(" Subject : %s n", record1.subject);
printf(" Percentage : %f nn", record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values examplen");
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;
}
union intptr {
int i;
int * p;
};
union intptr x;
x.i = 1000;
*(x.p)=90; /* puts 90 at location 1000 */
Example: use of union
union
{
int i;
float f;
} u;
// Convert floating-point bits to integer:
u.f = 3.14159f;
printf("As integer: %08xn", u.i);
Example: use of union
int f(int j)
{
static int i = 50;
int k;
if (i == j)
{
printf("something");
k = f(i);
return 0;
}
else return 0;
}
#include <stdio.h>
main()
{
int i;
int *pi = &i;
scanf("%d", pi);
printf("%dn", i+5);
}
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()
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);
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.
#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 memoryn");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : %sn", mem_allocation );
free(mem_allocation);
2. calloc() function in C:
calloc () function is also like malloc () function. But calloc () initializes the
allocated memory to zero. But, malloc() doesn’t.
#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 memoryn");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : %sn", mem_allocation );
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.
#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 memoryn");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : %sn", mem_allocation );
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.
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;
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 */
#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);
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;
}
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.
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
/*Example illustrating stack operation in c*/
#include <stdio.h>
#include <conio.h>
#define MAXSIZE 5
struct 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);
void main ()
{
int choice;
int option = 1;
clrscr ();
s.top=-1;
printf ("STACK OPERATIONn");
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 choicen");
scanf ("%d", &choice);
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);
}
}
/*Function to add an element to the stack*/
void push ()
{ int num;
if (s.top == (MAXSIZE - 1))
{
printf ("Stack is Fulln");
return;
}
else
{
printf ("Enter the element to be pushedn");
scanf ("%d", &num);
s.top = s.top + 1;
s.stk[s.top] = num;
}
return;
}
/*Function to delete an element from the stack*/
int pop ()
{
int num;
if (s.top == - 1)
{
printf ("Stack is Emptyn");
return (s.top);
}
else
{
num = s.stk[s.top];
printf ("poped element is = %dn", s.stk[s.top]);
s.top = s.top - 1;
}
return(num);
}
/*Function to display the status of the stack*/
void display ()
{
int i;
if (s.top == -1)
{
printf ("Stack is emptyn");
return;
}
else
{
printf ("nThe status of the stack isn");
for (i = s.top; i >= 0; i--)
printf ("%dn", s.stk[i]);
}
printf ("n");
}
•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
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.
#include<stdio.h>
#define MAX 3
int queue[MAX],front=-1,rear=-1;
void push_element();
void pop_element();
void display_queue();
int num;
int main()
{
int op;
do
{
printf("nn 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);
switch(op)
{
case 1: push_element();
break;
case 2: pop_element();
break;
case 3: display_queue();
break;
case 4: return 0;
break;
default: printf("nninvalid numbern");
}
}while(op!=4);
}
void push_element()
{
if(rear==MAX-1)
printf("nnQueue is full");
else
{
printf("nnenter number to be inserted");
scanf("%d",&num);
if(rear==-1 && front==-1)
{
rear=0;
front=0;}
else
rear++;
queue[rear]=num;
printf("nn num inserted is: queue[%d]=
%d",rear,num);
}}
void pop_element()
{
if(front==rear+1)
{
printf("nnqueue is emptyn");
rear=-1;
}
else
{
num=queue[front];
printf("nnnum popped is:queue[%d]=%dn",front,num);
front++;
}
}
void display_queue()
{
int i;
if(front==rear+1)
{
printf("nnqueue has no elements to displayn");
}
else
for(i=front;i<=rear;i++)
{
printf("nnqueue[%d]=%d",i,queue[i]);
}
}
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
#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);
int main()
{
int op;
int item;
do
{
printf("nn 1 -- INSERT at rear end");
printf("nn 2 -- INSERT at front end");
printf("nn 3 -- DELETE at rear end");
printf("nn 4 -- DELETE at front end");
printf("nn 5 -- display");
printf("nn 6 -- EXIT");
scanf("%d", &op);
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 numbern");
}}
while(op!=6);
}
void insert_rear(void)
{
int num;
printf("enter number to be insertedn");
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]=%dn", front,q[front]);
printf("rear is %d, front is %dn",rear, front);
}}
void delete_rear(void)
{
int num;
if(rear==-1)
{
printf("n Cannot delete value at rear endn");
return;
}
else
{
num=q[rear];
q[rear]=0;
if(front>rear)
{ Front=-1; rear=-1; }
else
rear--;
}
printf("n Deleted element is %dn",num);}
void delete_front(void)
{
int num;
if(front==-1 && rear==-1)
{ printf("n Cannot delete value at front endn");
return;
}
else
{
num=q[front];
q[front]=0;
if(front>rear)
{ Front=-1; rear=-1; }
else
front++;
}
printf("n Deleted element is %dn",num);
}
void display(void)
{
int i;
if(front<=0 && rear==-1)
{
printf("n Queue is Underflown");
return;
}
else
{
printf("n Output");
for(i=0;i<=MAX-1;i++)
{
printf("n %d",q[i]);
}
}
}
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.
#include<stdio.h>
#define MAX 3
int queue[MAX],front=-1,rear=-1;
void push_element();
void pop_element();
void display_queue();
int num;
int main()
{
int op;
do {
printf("nn 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);
switch(op)
{
case 1: push_element();
break;
case 2: pop_element();
break;
case 3: display_queue();
break;
case 4: return 0;
break;
default: printf("nninvalid numbern");
}
}
while(op!=4);
}
void push_element()
{
if((front==0 && rear==MAX-1))
{
printf("nnQueue is full");
}
else
{
if((rear==-1)||(rear==MAX-1))
{
printf("nnenter number to be
inserted");
scanf("%d",&num);
rear=0;
front=0;
queue[rear]=num;
}
else
{
rear++;
if((queue[rear] != 0)&&(rear!=0))
{
printf("nnQueue is full");
goto x;
}
printf("nnenter number to be inserted");
scanf("%d",&num);
queue[rear]=num;
printf("nn num inserted is: queue[%d]=%d",rear,num);
}
x:
printf("nn rear is %d and front is %d",rear,front);
}
}
void pop_element()
{
if((front==-1)||(front==rear+1))
printf("nnqueue is emptyn");
else
{
num=queue[front];
queue[front]=0;
if(front==rear)
{ front=-1; rear=-1; }
else if(front==MAX-1)
front=0;
else
front++;
printf("nnnum popped is:queue[%d]=%dn",front,num);
}
printf("nn rear is %d and front is %d",rear,front);
}
void display_queue()
{
int i;
printf("nn rear is %d and front is %d",rear,front);
if((front==-1))//||(front==rear+1))
{
printf("nnqueue has no lements to displayn");
}
else
{
for(i=0;i<=2;i++)
printf("nnqueue[%d]=%d",i,queue[i]);
}
}
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.
/* 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();
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 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);
}
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 arrays
1) Dynamic size
2) 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.
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) data
2) 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;
};
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;
}
/* 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); //found
temp=temp->next;
}
if(flag==0)
return (0);// not found
/*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;
}
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.
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.
#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 * 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);
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 %dn",temp->data);
temp = FindMax(root);
printf("Maximum element is %dn",temp->data);
temp = Find(root,8);
if(temp==NULL)
{
printf("Element 8 not foundn");
}
else
printf("Element 8 Foundn");
}
The Manual (terminal mode)
man This command brings up the online Unix
manual. 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 directory
into the muondata sub-directory
cd .. Moves up one directory (yes, include the
two little dots)
You can also move directly into directories
cd /home/particle/muondata
Moves from ANY directory into the muondata
sub-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.
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.

More Related Content

What's hot

Introduction to C Programming - I
Introduction to C Programming - I Introduction to C Programming - I
Introduction to C Programming - I
vampugani
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
JAYA
 
C language introduction
C language introduction C language introduction
C language introduction
musrath mohammad
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C Language
Abhishek Dwivedi
 
C language
C languageC language
C language
spatidar0
 
C programming language
C programming languageC programming language
C programming language
Maha lakshmi
 
Tokens_C
Tokens_CTokens_C
Tokens_C
Prabhu Govind
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
The Smartpath Information Systems,Bhilai,Durg,Chhattisgarh.
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming languageKumar Gaurav
 
Unit ii
Unit   iiUnit   ii
Unit ii
sathisaran
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for Engineering
Vincenzo De Florio
 
Programming in C- Introduction
Programming in C- IntroductionProgramming in C- Introduction
Programming in C- Introduction
savitamhaske
 
C program
C programC program
C program
AJAL A J
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
MOHAMAD NOH AHMAD
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
Muthuselvam RS
 
Features of c
Features of cFeatures of c
Features of c
Hitesh Kumar
 
Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming language
sanjay joshi
 

What's hot (20)

C tutorial
C tutorialC tutorial
C tutorial
 
Introduction to C Programming - I
Introduction to C Programming - I Introduction to C Programming - I
Introduction to C Programming - I
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
C language introduction
C language introduction C language introduction
C language introduction
 
Learning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C LanguageLearning c - An extensive guide to learn the C Language
Learning c - An extensive guide to learn the C Language
 
C language
C languageC language
C language
 
C programming language
C programming languageC programming language
C programming language
 
Tokens_C
Tokens_CTokens_C
Tokens_C
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
The smartpath information systems c pro
The smartpath information systems c proThe smartpath information systems c pro
The smartpath information systems c pro
 
Brief introduction to the c programming language
Brief introduction to the c programming languageBrief introduction to the c programming language
Brief introduction to the c programming language
 
Unit ii
Unit   iiUnit   ii
Unit ii
 
C PROGRAMMING
C PROGRAMMINGC PROGRAMMING
C PROGRAMMING
 
Advanced C Language for Engineering
Advanced C Language for EngineeringAdvanced C Language for Engineering
Advanced C Language for Engineering
 
Programming in C- Introduction
Programming in C- IntroductionProgramming in C- Introduction
Programming in C- Introduction
 
C program
C programC program
C program
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
CProgrammingTutorial
CProgrammingTutorialCProgrammingTutorial
CProgrammingTutorial
 
Features of c
Features of cFeatures of c
Features of c
 
Introduction to c programming language
Introduction to c programming languageIntroduction to c programming language
Introduction to c programming language
 

Viewers also liked

Embedded system - embedded system programming
Embedded system - embedded system programmingEmbedded system - embedded system programming
Embedded system - embedded system programming
Vibrant Technologies & Computers
 
C++ for Embedded Programming
C++ for Embedded ProgrammingC++ for Embedded Programming
C++ for Embedded Programming
Colin Walls
 
States & Capitals 111
States & Capitals 111States & Capitals 111
States & Capitals 111Bermanburgh
 
Embedded c programming
Embedded c programmingEmbedded c programming
Embedded c programming
PriyaDYP
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
sachindane
 
Embedded C workshop
Embedded C workshopEmbedded C workshop
Embedded C workshop
Mostafa El-koumy
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
Saket Pathak
 
Recursion
RecursionRecursion
Recursion
Nalin Adhikari
 
Embedded C - Lecture 3
Embedded C - Lecture 3Embedded C - Lecture 3
Embedded C - Lecture 3
Mohamed Abdallah
 
C Programming For Embedded Systems
C Programming For Embedded SystemsC Programming For Embedded Systems
C Programming For Embedded SystemsGanesh Samarthyam
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 
Embedded c program and programming structure for beginners
Embedded c program and programming structure for beginnersEmbedded c program and programming structure for beginners
Embedded c program and programming structure for beginners
Kamesh Mtec
 
Embedded C - Lecture 4
Embedded C - Lecture 4Embedded C - Lecture 4
Embedded C - Lecture 4
Mohamed Abdallah
 
Recursion
RecursionRecursion
Recursion
Asif Ali Raza
 
Embedded c programming22 for fdp
Embedded c programming22 for fdpEmbedded c programming22 for fdp
Embedded c programming22 for fdpPradeep Kumar TS
 
1 measurement and error
1 measurement and error 1 measurement and error
1 measurement and error
LOHYINNEE
 
Embedded C - Lecture 1
Embedded C - Lecture 1Embedded C - Lecture 1
Embedded C - Lecture 1
Mohamed Abdallah
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals master
Hossam Hassan
 

Viewers also liked (20)

Embedded system - embedded system programming
Embedded system - embedded system programmingEmbedded system - embedded system programming
Embedded system - embedded system programming
 
C++ for Embedded Programming
C++ for Embedded ProgrammingC++ for Embedded Programming
C++ for Embedded Programming
 
States & Capitals 111
States & Capitals 111States & Capitals 111
States & Capitals 111
 
Embedded c programming
Embedded c programmingEmbedded c programming
Embedded c programming
 
C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
Embedded C
Embedded CEmbedded C
Embedded C
 
Embedded C workshop
Embedded C workshopEmbedded C workshop
Embedded C workshop
 
Recursion in c
Recursion in cRecursion in c
Recursion in c
 
Recursion
RecursionRecursion
Recursion
 
Embedded C - Lecture 3
Embedded C - Lecture 3Embedded C - Lecture 3
Embedded C - Lecture 3
 
C Programming For Embedded Systems
C Programming For Embedded SystemsC Programming For Embedded Systems
C Programming For Embedded Systems
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
 
Embedded c program and programming structure for beginners
Embedded c program and programming structure for beginnersEmbedded c program and programming structure for beginners
Embedded c program and programming structure for beginners
 
Embedded C - Lecture 4
Embedded C - Lecture 4Embedded C - Lecture 4
Embedded C - Lecture 4
 
Recursion
RecursionRecursion
Recursion
 
Recursion
RecursionRecursion
Recursion
 
Embedded c programming22 for fdp
Embedded c programming22 for fdpEmbedded c programming22 for fdp
Embedded c programming22 for fdp
 
1 measurement and error
1 measurement and error 1 measurement and error
1 measurement and error
 
Embedded C - Lecture 1
Embedded C - Lecture 1Embedded C - Lecture 1
Embedded C - Lecture 1
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals master
 

Similar to C prog ppt

C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
Thooyavan Venkatachalam
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Vikram Nandini
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAlpana Gupta
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
Shankar Gangaju
 
c_pro_introduction.pptx
c_pro_introduction.pptxc_pro_introduction.pptx
c_pro_introduction.pptx
RohitRaj744272
 
C programming
C programmingC programming
C programming
Rounak Samdadia
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures
Pradipta Mishra
 
C programming
C programmingC programming
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structures
Pradipta Mishra
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
20EUEE018DEEPAKM
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
Mohamed Fawzy
 
C language
C language C language
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. AnsariBasic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
G. H. Raisoni Academy of Engineering & Technology, Nagpur
 
c programming session 1.pptx
c programming session 1.pptxc programming session 1.pptx
c programming session 1.pptx
RSathyaPriyaCSEKIOT
 
Basic c
Basic cBasic c
Basic c
Veera Karthi
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
Likhil181
 
Programming in c
Programming in cProgramming in c
Programming in c
Ashutosh Srivasatava
 
c-introduction.pptx
c-introduction.pptxc-introduction.pptx
c-introduction.pptx
Mangala R
 
Cpu
CpuCpu
C programming.pdf
C programming.pdfC programming.pdf
C programming.pdf
JitendraYadav351971
 

Similar to C prog ppt (20)

C introduction by thooyavan
C introduction by  thooyavanC introduction by  thooyavan
C introduction by thooyavan
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
1. introduction to computer
1. introduction to computer1. introduction to computer
1. introduction to computer
 
c_pro_introduction.pptx
c_pro_introduction.pptxc_pro_introduction.pptx
c_pro_introduction.pptx
 
C programming
C programmingC programming
C programming
 
Introduction to programming c and data-structures
Introduction to programming c and data-structures Introduction to programming c and data-structures
Introduction to programming c and data-structures
 
C programming
C programmingC programming
C programming
 
Introduction to programming c and data structures
Introduction to programming c and data structuresIntroduction to programming c and data structures
Introduction to programming c and data structures
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
C programming day#1
C programming day#1C programming day#1
C programming day#1
 
C language
C language C language
C language
 
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. AnsariBasic of C Programming | 2022 Updated | By Shamsul H. Ansari
Basic of C Programming | 2022 Updated | By Shamsul H. Ansari
 
c programming session 1.pptx
c programming session 1.pptxc programming session 1.pptx
c programming session 1.pptx
 
Basic c
Basic cBasic c
Basic c
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
Programming in c
Programming in cProgramming in c
Programming in c
 
c-introduction.pptx
c-introduction.pptxc-introduction.pptx
c-introduction.pptx
 
Cpu
CpuCpu
Cpu
 
C programming.pdf
C programming.pdfC programming.pdf
C programming.pdf
 

Recently uploaded

Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 

Recently uploaded (20)

Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 

C prog ppt

  • 2. 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 limited qOften real-time response is essential
  • 4. ü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
  • 5. Possible organization of embedded systems
  • 7. 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 developing OSs, System level programming, Embedded Systems(including micro-controllers such as PIC, ARM, and MP), RTOS, Compilers, website programming libraries to other languages
  • 8. 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.
  • 9. 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).
  • 10. structure of C a program #include<stdio.h> /* Header File */ main () /* starting function */ { /* start of program */ -------- Statements; -------- Return; }
  • 11. Example C program Ex: /* Hello world Program*/ #include <stdio.h> int main() { printf (“Hello worldn”); return 0; }
  • 13. 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.
  • 14. 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
  • 15. 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.
  • 16. 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("%dn",b); printf("%3dn",b); printf("%03dn",b); c = 15.3; d = c / 3; printf("%3.2fn",d); }
  • 17. /*EXAMPLE*/ #include<stdio.h> main() { printf("The color: %sn", "blue"); printf("First number: %dn", 12345); printf("Second number: %04dn", 25); printf("Third number: %in", 1234); printf("Float number: %3.2fn", 3.14159); printf("Hexadecimal: %xn", 255); printf("Octal: %on", 255); printf("Unsigned value: %un", 150); printf("Just print the percentage sign %%n", 10); }
  • 18. 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!"); }
  • 19. Data types - Primary data types - Derived data types
  • 20. 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 Types Following table gives you details about standard integer types with its storage sizes and value ranges:
  • 21. 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
  • 22. 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: %En", FLT_MIN ); printf("Maximum float positive value: %En", FLT_MAX ); printf("Precision value: %dn", FLT_DIG ); return 0; }
  • 23. 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
  • 24. 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.
  • 25. 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
  • 26. 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: +, /,-,*)
  • 27. C tokens example program: int main() { int x, y, total; x=10, y=20; total=x+y; printf(“total=%dn”,total); } where, main – identifier {,}, (,) – delimiter int – keyword x, y, total – identifier main, {, }, (, ), int, x, y, total – tokens
  • 28. Operators •Assignment operator - (=, +=, -=, /=, %=, *=) •Arithmetic operator - C supports 5 operators : (+, -, *, /, %,++, --) •Relational operator -(<, >, <=, >=, ==, !=) •Logical operator -(&&, ||, !) •Bitwise operator -(&, |, ^, <<, >>)
  • 29. Operators cotnd.... Conditional operator Also called ternary operator or ?: operator Ex: 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.
  • 30. 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
  • 31. 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
  • 32. /* 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) ; }
  • 33. 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 int unsigned int long int long long int 53, 762, -478 etc 5000u, 1000U etc 483,647 2,147,483,680 2 Real or Floating point constants float doule 10.456789 600.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”
  • 34. Defining Constants There are two simple ways in C to define constants: -Using #define preprocessor. -Using const keyword.
  • 35. /* 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; }
  • 36. /* 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; }
  • 37. #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 %dn" , no); printf("Double value is %lf n", dbl); printf("Octal value is %o n", no); printf("Hexadecimal value is %x n", no); return 0; }
  • 38. #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); }
  • 39. 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 | BitwiseOR 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
  • 40. #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 = %dn",AND_opr ); printf("OR_opr value = %dn",OR_opr ); printf("NOT_opr value = %dn",NOT_opr ); printf("XOR_opr value = %dn",XOR_opr ); printf("left_shift value = %dn", m << 1); printf("right_shift value = %dn", m >> 1); }
  • 41. 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.
  • 42. C provides two types of flow control ●Branching ●Looping ● Branching 1. If Statement 2. The If else Statement 3. Compound Relational tests 4. Nested if Statement 5. Switch Statement Loop control statements in C 1. for 2. while 3. do-while
  • 43. If statement if(condition) { statement; } If else statement If(condition) Program statement1 else program statement 2 Compound relational test a) if (condition1 && condition2 && condition3) b) if (condition1 || condition2 || condition3)
  • 44. Nested if statement if (condition1) if (condition2) statement-1; else statement-2; else statement-3;
  • 45. 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.
  • 46. 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);
  • 47. Loop control statements •Break – exit from loop or switch •Continue – skip one iteration in loop
  • 48. //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; }
  • 49. -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
  • 50. 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.
  • 51. 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 = %dn", a, b, c); return 0; }
  • 52. 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 = %dn", a, b, c); return 0; }
  • 53. 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 = %dn", a, b, g); return 0; }
  • 54. Formal Parameters Function 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() = %dn", a); c = sum( a, b); printf ("value of c in main() = %dn", c); return 0; } int sum(int a, int b) /* function to add two integers */ { printf ("value of a in sum() = %dn", a); printf ("value of b in sum() = %dn", b); return a + b; }
  • 55. 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 Value int 0 char '0' float 0 double 0 pointer NULL
  • 56. Storage class specifiers in C There are 4 storage class specifiers available in C language. They are, • auto • extern • static • register
  • 57. --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++; }
  • 58. Memory Layout of C programs A typical memory representation of C program consists of following sections. 1. Text segment 2. Initialized data segment 3. Uninitialized data segment 4. Stack 5. Heap
  • 59. 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.
  • 60. 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
  • 61. 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
  • 62. 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.
  • 63. 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,
  • 64. 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
  • 65. Declaring single dimensional array : Syntax: data_type arr_name [size]; int a[10]; // integer array char b[10]; // character array i.e. string int 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]); } }
  • 66. 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] : %dn",i,j,arr[i][j]); }}}
  • 67. -- prog to Add elements of an array at odd position. -- Prog to find intersection of 3 arrays.
  • 68. 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, ... ] );
  • 69. 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.
  • 70. /*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); }
  • 71. 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() */}
  • 72. Macros in C All the lines starting with # are processed by preprocessor 1) 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*b int main() { printf("%d", MULTIPLY(2+3, 3+5)); return 0; }
  • 73. 6) The tokens passed to macros can be concatenated using operator ## called Token-Pasting operator. #include <stdio.h> #define merge(a, b) a##b int 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; }
  • 74. 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*x int main() { int x = 36/square(6); printf("%d", x); return 0; }
  • 75. 10) There are some standard macros #include <stdio.h> int main() { printf("Current File :%sn", __FILE__ ); printf("Current Date :%sn", __DATE__ ); printf("Current Time :%sn", __TIME__ ); printf("Line Number :%dn", __LINE__ ); return 0; } 11) Other directives in C a) #if, #elif, #else, #endif #if constant_expression #else #endif or #if constant_expression #elif constant_expression #endif
  • 76. 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)
  • 77. 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("%dn", a); return 0; } int a=20;
  • 78. #include<stdio.h> int main() { extern int i; i = 20; printf("%dn", sizeof(i)); return 0; } #include<stdio.h> int main() { printf("IndiaBIX"); main(); return 0; }
  • 79. 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 %dn", j, j); j++; } return 0; }
  • 80. #include<stdio.h> int main() { int a = 500, b = 100, c; if(!a >= 400) b = 300; c = 200; printf("b = %d c = %dn", b, c); return 0; } #include<stdio.h> int main() { int i=1; for(;;) { printf("%dn", i++); if(i>10) break; } return 0; }
  • 81. #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; }
  • 82. 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: %xn", &var ); printf("Address stored in ip variable: %xn", ip ); printf("Value of *ip variable: %dn", *ip ); 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:
  • 83. Incrementing a Pointer We 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] = %un", i, ptr ); printf("Value of var[%d] = %dn", i, *ptr ); ptr++; /* move to the next location */ } return 0; }
  • 84. Pointer to Pointer in C A 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 = %dn", var ); printf("Value available at *ptr = %dn", *ptr ); printf("Value available at **pptr = %dn", **pptr); return 0; }
  • 85. 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: %ldn", sec ); return 0; } void getSeconds(unsigned long *par) { /* get the current number of seconds */ *par = time( NULL ); return; }
  • 86. 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
  • 87. Ex: #include <stdio.h> int main () { char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'}; printf("Greeting message: %sn", greeting ); return 0; }
  • 88. /*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);}
  • 89.
  • 90. String handling functions Following 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
  • 91. 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);
  • 92. 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);
  • 93. 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);
  • 94. 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);
  • 95. 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);
  • 96. 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);
  • 97. 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);
  • 98. -- 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.
  • 99. 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: %dn",str[j], c); } c=0; }
  • 100. main() { int balance; int *address; int value; balance = 5000; address = &balance; value = *address; printf("Balance is : %dn" , value); }
  • 101. main() { int *p , num; p = &num; *p = 100; printf("%dn" , num); (*p)++; printf("%dn" , num); (*p)--; printf("%dn" , num); }
  • 102. Sorting algorithms in C Bubble sort algorithm Selection sort algorithm
  • 104. 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;
  • 105. 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;
  • 106. Linear search int main() { int array[100], search, c, n; printf("Enter the number of elements in arrayn"); 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 searchn"); 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;
  • 107. Binary search #include <stdio.h> int main() { int c, first, last, middle, n, search, array[100]; printf("Enter number of elementsn"); scanf("%d",&n); printf("Enter %d integersn", n); for ( c = 0 ; c < n ; c++ ) scanf("%d",&array[c]); // program assumes input numbers are in ascending order. printf("Enter value to findn"); scanf("%d",&search); first = 0; last = n - 1; middle = (first+last)/2;
  • 108. 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; }
  • 109. 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.
  • 110. 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.
  • 111. #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);
  • 112. /* 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 %dn",girl.initial, girl.age, girl.grade); printf("%c is %d years old and got a grade of %dn",boy.initial, boy.age, boy.grade); }
  • 113. Bit Fields Suppose your C program contains a number of TRUE/FALSE variables grouped in a structur struct { unsigned int widthValidated; unsigned int heightValidated; } status; Without using bit fields it consumes 8 bytes of memory.
  • 114. Bit Fields Suppose your C program contains a number of TRUE/FALSE variables grouped in a structur struct { unsigned int widthValidated : 1; unsigned int heightValidated : 1; } status; Using using bit fields it consumes 2 bits of memory.
  • 115. Bit Fields struct { 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 : %dn", sizeof(status1)); printf( "Memory size occupied by status2 : %dn", sizeof(status2)); return 0; }.
  • 116. Array of structures main () { struct item { char initial; int id_no; }; int j; struct item a[2]; clrscr(); printf ("n Enter Code_no, Pricen "); 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);
  • 117. 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];
  • 118. 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;
  • 119. /*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}};
  • 120. 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
  • 121. /*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;}
  • 122. /*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
  • 123. 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("%st%dt%.2fn",(ptr+i)->c,(ptr+i)->a,(ptr+i)->b); return 0; }
  • 124. 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.
  • 125. #include <stdio.h> #include <string.h> struct student { int id1; int id2; char a; char b; float percentage; };
  • 126. int main() { int i; struct student record1 = {1, 2, 'A', 'B', 90.5}; printf("size of structure in bytes : %dn", 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; }
  • 127. 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.
  • 128. 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
  • 129. #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 examplen");
  • 130. printf(" Name : %s n", record1.name); printf(" Subject : %s n", record1.subject); printf(" Percentage : %f nn", record1.percentage); // assigning values to record2 union variable printf("Union record2 values examplen"); 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; }
  • 131. union intptr { int i; int * p; }; union intptr x; x.i = 1000; *(x.p)=90; /* puts 90 at location 1000 */ Example: use of union
  • 132. union { int i; float f; } u; // Convert floating-point bits to integer: u.f = 3.14159f; printf("As integer: %08xn", u.i); Example: use of union
  • 133. int f(int j) { static int i = 50; int k; if (i == j) { printf("something"); k = f(i); return 0; } else return 0; }
  • 134. #include <stdio.h> main() { int i; int *pi = &i; scanf("%d", pi); printf("%dn", i+5); }
  • 135. 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()
  • 136. 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);
  • 137. 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.
  • 138. #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 memoryn"); } else { strcpy( mem_allocation,"fresh2refresh.com"); } printf("Dynamically allocated memory content : %sn", mem_allocation ); free(mem_allocation);
  • 139. 2. calloc() function in C: calloc () function is also like malloc () function. But calloc () initializes the allocated memory to zero. But, malloc() doesn’t.
  • 140. #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 memoryn"); } else { strcpy( mem_allocation,"fresh2refresh.com"); } printf("Dynamically allocated memory content : %sn", mem_allocation );
  • 141. 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.
  • 142. #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 memoryn"); } else { strcpy( mem_allocation,"fresh2refresh.com"); } printf("Dynamically allocated memory content : %sn", mem_allocation );
  • 143. 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.
  • 144. 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;
  • 145. 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 */
  • 146. #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);
  • 147. 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; }
  • 148. 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.
  • 149.
  • 150. 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
  • 151. /*Example illustrating stack operation in c*/ #include <stdio.h> #include <conio.h> #define MAXSIZE 5 struct 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);
  • 152. void main () { int choice; int option = 1; clrscr (); s.top=-1; printf ("STACK OPERATIONn"); 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 choicen"); scanf ("%d", &choice);
  • 153. 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); } }
  • 154. /*Function to add an element to the stack*/ void push () { int num; if (s.top == (MAXSIZE - 1)) { printf ("Stack is Fulln"); return; } else { printf ("Enter the element to be pushedn"); scanf ("%d", &num); s.top = s.top + 1; s.stk[s.top] = num; } return; }
  • 155. /*Function to delete an element from the stack*/ int pop () { int num; if (s.top == - 1) { printf ("Stack is Emptyn"); return (s.top); } else { num = s.stk[s.top]; printf ("poped element is = %dn", s.stk[s.top]); s.top = s.top - 1; } return(num); }
  • 156. /*Function to display the status of the stack*/ void display () { int i; if (s.top == -1) { printf ("Stack is emptyn"); return; } else { printf ("nThe status of the stack isn"); for (i = s.top; i >= 0; i--) printf ("%dn", s.stk[i]); } printf ("n"); }
  • 157. •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
  • 158. 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.
  • 159. #include<stdio.h> #define MAX 3 int queue[MAX],front=-1,rear=-1; void push_element(); void pop_element(); void display_queue(); int num; int main() { int op; do { printf("nn 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);
  • 160. switch(op) { case 1: push_element(); break; case 2: pop_element(); break; case 3: display_queue(); break; case 4: return 0; break; default: printf("nninvalid numbern"); } }while(op!=4); }
  • 161. void push_element() { if(rear==MAX-1) printf("nnQueue is full"); else { printf("nnenter number to be inserted"); scanf("%d",&num); if(rear==-1 && front==-1) { rear=0; front=0;} else rear++; queue[rear]=num; printf("nn num inserted is: queue[%d]= %d",rear,num); }}
  • 162. void pop_element() { if(front==rear+1) { printf("nnqueue is emptyn"); rear=-1; } else { num=queue[front]; printf("nnnum popped is:queue[%d]=%dn",front,num); front++; } }
  • 163. void display_queue() { int i; if(front==rear+1) { printf("nnqueue has no elements to displayn"); } else for(i=front;i<=rear;i++) { printf("nnqueue[%d]=%d",i,queue[i]); } }
  • 164. 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
  • 165. #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);
  • 166. int main() { int op; int item; do { printf("nn 1 -- INSERT at rear end"); printf("nn 2 -- INSERT at front end"); printf("nn 3 -- DELETE at rear end"); printf("nn 4 -- DELETE at front end"); printf("nn 5 -- display"); printf("nn 6 -- EXIT"); scanf("%d", &op);
  • 167. 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 numbern"); }} while(op!=6); }
  • 168. void insert_rear(void) { int num; printf("enter number to be insertedn"); 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; }}
  • 169. 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]=%dn", front,q[front]); printf("rear is %d, front is %dn",rear, front); }}
  • 170. void delete_rear(void) { int num; if(rear==-1) { printf("n Cannot delete value at rear endn"); return; } else { num=q[rear]; q[rear]=0; if(front>rear) { Front=-1; rear=-1; } else rear--; } printf("n Deleted element is %dn",num);}
  • 171. void delete_front(void) { int num; if(front==-1 && rear==-1) { printf("n Cannot delete value at front endn"); return; } else { num=q[front]; q[front]=0; if(front>rear) { Front=-1; rear=-1; } else front++; } printf("n Deleted element is %dn",num); }
  • 172. void display(void) { int i; if(front<=0 && rear==-1) { printf("n Queue is Underflown"); return; } else { printf("n Output"); for(i=0;i<=MAX-1;i++) { printf("n %d",q[i]); } } }
  • 173. 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.
  • 174. #include<stdio.h> #define MAX 3 int queue[MAX],front=-1,rear=-1; void push_element(); void pop_element(); void display_queue(); int num; int main() { int op; do { printf("nn 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);
  • 175. switch(op) { case 1: push_element(); break; case 2: pop_element(); break; case 3: display_queue(); break; case 4: return 0; break; default: printf("nninvalid numbern"); } } while(op!=4); }
  • 176. void push_element() { if((front==0 && rear==MAX-1)) { printf("nnQueue is full"); } else { if((rear==-1)||(rear==MAX-1)) { printf("nnenter number to be inserted"); scanf("%d",&num); rear=0; front=0; queue[rear]=num; }
  • 177. else { rear++; if((queue[rear] != 0)&&(rear!=0)) { printf("nnQueue is full"); goto x; } printf("nnenter number to be inserted"); scanf("%d",&num); queue[rear]=num; printf("nn num inserted is: queue[%d]=%d",rear,num); } x: printf("nn rear is %d and front is %d",rear,front); } }
  • 178. void pop_element() { if((front==-1)||(front==rear+1)) printf("nnqueue is emptyn"); else { num=queue[front]; queue[front]=0; if(front==rear) { front=-1; rear=-1; } else if(front==MAX-1) front=0; else front++; printf("nnnum popped is:queue[%d]=%dn",front,num); } printf("nn rear is %d and front is %d",rear,front); }
  • 179. void display_queue() { int i; printf("nn rear is %d and front is %d",rear,front); if((front==-1))//||(front==rear+1)) { printf("nnqueue has no lements to displayn"); } else { for(i=0;i<=2;i++) printf("nnqueue[%d]=%d",i,queue[i]); } }
  • 180. 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.
  • 181. /* 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();
  • 182. 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++; }
  • 183. /* 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); }
  • 184. 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 arrays 1) Dynamic size 2) 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.
  • 185. 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) data 2) 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; };
  • 186. 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; }
  • 187. /* 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); //found temp=temp->next; } if(flag==0) return (0);// not found
  • 188. /*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; }
  • 189. 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.
  • 190. 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.
  • 191. #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; }
  • 192. 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);
  • 193. 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 %dn",temp->data); temp = FindMax(root); printf("Maximum element is %dn",temp->data); temp = Find(root,8); if(temp==NULL) { printf("Element 8 not foundn"); } else printf("Element 8 Foundn"); }
  • 194. The Manual (terminal mode) man This command brings up the online Unix manual. 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 directory into the muondata sub-directory
  • 195. cd .. Moves up one directory (yes, include the two little dots) You can also move directly into directories cd /home/particle/muondata Moves from ANY directory into the muondata sub-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.
  • 196. 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.

Editor's Notes

  1. &amp;lt;number&amp;gt;
  2. &amp;lt;number&amp;gt;
  3. &amp;lt;number&amp;gt;
  4. &amp;lt;number&amp;gt;
  5. &amp;lt;number&amp;gt;
  6. &amp;lt;number&amp;gt;
  7. &amp;lt;number&amp;gt;
  8. &amp;lt;number&amp;gt;
  9. &amp;lt;number&amp;gt;
  10. &amp;lt;number&amp;gt;
  11. &amp;lt;number&amp;gt;
  12. &amp;lt;number&amp;gt;
  13. &amp;lt;number&amp;gt;
  14. &amp;lt;number&amp;gt;
  15. &amp;lt;number&amp;gt;
  16. &amp;lt;number&amp;gt;
  17. &amp;lt;number&amp;gt;
  18. &amp;lt;number&amp;gt;
  19. &amp;lt;number&amp;gt;
  20. &amp;lt;number&amp;gt;
  21. &amp;lt;number&amp;gt;
  22. &amp;lt;number&amp;gt;
  23. &amp;lt;number&amp;gt;
  24. &amp;lt;number&amp;gt;
  25. &amp;lt;number&amp;gt;
  26. &amp;lt;number&amp;gt;
  27. &amp;lt;number&amp;gt;
  28. &amp;lt;number&amp;gt;
  29. &amp;lt;number&amp;gt;
  30. &amp;lt;number&amp;gt;
  31. &amp;lt;number&amp;gt;
  32. &amp;lt;number&amp;gt;
  33. &amp;lt;number&amp;gt;
  34. &amp;lt;number&amp;gt;
  35. &amp;lt;number&amp;gt;
  36. &amp;lt;number&amp;gt;
  37. &amp;lt;number&amp;gt;
  38. &amp;lt;number&amp;gt;
  39. &amp;lt;number&amp;gt;
  40. &amp;lt;number&amp;gt;
  41. &amp;lt;number&amp;gt;
  42. &amp;lt;number&amp;gt;
  43. &amp;lt;number&amp;gt;
  44. &amp;lt;number&amp;gt;
  45. &amp;lt;number&amp;gt;
  46. &amp;lt;number&amp;gt;
  47. &amp;lt;number&amp;gt;
  48. &amp;lt;number&amp;gt;
  49. &amp;lt;number&amp;gt;
  50. &amp;lt;number&amp;gt;
  51. &amp;lt;number&amp;gt;
  52. &amp;lt;number&amp;gt;
  53. &amp;lt;number&amp;gt;
  54. &amp;lt;number&amp;gt;
  55. &amp;lt;number&amp;gt;
  56. &amp;lt;number&amp;gt;
  57. &amp;lt;number&amp;gt;
  58. &amp;lt;number&amp;gt;
  59. &amp;lt;number&amp;gt;
  60. &amp;lt;number&amp;gt;
  61. &amp;lt;number&amp;gt;
  62. &amp;lt;number&amp;gt;
  63. &amp;lt;number&amp;gt; which may use the brk and sbrk system calls to adjust its size (note that the use of brk/sbrk and a single “heap area” is not required to fulfill the contract of malloc/realloc/free; they may also be implemented using mmap to reserve potentially non-contiguous regions of virtual memory into the process’ virtual address space). The Heap area is shared by all shared libraries and dynamically loaded modules in a process.
  64. &amp;lt;number&amp;gt;
  65. &amp;lt;number&amp;gt;
  66. &amp;lt;number&amp;gt;
  67. &amp;lt;number&amp;gt;
  68. &amp;lt;number&amp;gt;
  69. &amp;lt;number&amp;gt;
  70. &amp;lt;number&amp;gt;
  71. &amp;lt;number&amp;gt;
  72. &amp;lt;number&amp;gt;
  73. &amp;lt;number&amp;gt;
  74. &amp;lt;number&amp;gt;
  75. &amp;lt;number&amp;gt;
  76. &amp;lt;number&amp;gt;
  77. &amp;lt;number&amp;gt;
  78. &amp;lt;number&amp;gt;
  79. &amp;lt;number&amp;gt;
  80. &amp;lt;number&amp;gt;
  81. &amp;lt;number&amp;gt;
  82. &amp;lt;number&amp;gt;
  83. &amp;lt;number&amp;gt;
  84. &amp;lt;number&amp;gt;
  85. &amp;lt;number&amp;gt;
  86. &amp;lt;number&amp;gt;
  87. &amp;lt;number&amp;gt;
  88. &amp;lt;number&amp;gt;
  89. &amp;lt;number&amp;gt;
  90. &amp;lt;number&amp;gt;
  91. &amp;lt;number&amp;gt;
  92. &amp;lt;number&amp;gt;
  93. &amp;lt;number&amp;gt;
  94. &amp;lt;number&amp;gt;
  95. &amp;lt;number&amp;gt;
  96. &amp;lt;number&amp;gt;
  97. &amp;lt;number&amp;gt;
  98. &amp;lt;number&amp;gt;
  99. &amp;lt;number&amp;gt;
  100. &amp;lt;number&amp;gt;
  101. &amp;lt;number&amp;gt;
  102. &amp;lt;number&amp;gt;
  103. &amp;lt;number&amp;gt;
  104. &amp;lt;number&amp;gt;
  105. &amp;lt;number&amp;gt;
  106. &amp;lt;number&amp;gt;
  107. &amp;lt;number&amp;gt;
  108. &amp;lt;number&amp;gt;
  109. &amp;lt;number&amp;gt;
  110. &amp;lt;number&amp;gt;
  111. &amp;lt;number&amp;gt;
  112. &amp;lt;number&amp;gt;
  113. &amp;lt;number&amp;gt;
  114. &amp;lt;number&amp;gt;
  115. &amp;lt;number&amp;gt;
  116. &amp;lt;number&amp;gt;
  117. &amp;lt;number&amp;gt;
  118. &amp;lt;number&amp;gt;
  119. &amp;lt;number&amp;gt;
  120. &amp;lt;number&amp;gt;
  121. &amp;lt;number&amp;gt;
  122. &amp;lt;number&amp;gt;
  123. &amp;lt;number&amp;gt;
  124. &amp;lt;number&amp;gt;
  125. &amp;lt;number&amp;gt;
  126. &amp;lt;number&amp;gt;
  127. &amp;lt;number&amp;gt;
  128. &amp;lt;number&amp;gt;
  129. &amp;lt;number&amp;gt;
  130. &amp;lt;number&amp;gt;
  131. &amp;lt;number&amp;gt;
  132. &amp;lt;number&amp;gt;
  133. &amp;lt;number&amp;gt;
  134. &amp;lt;number&amp;gt;
  135. &amp;lt;number&amp;gt;
  136. &amp;lt;number&amp;gt;
  137. &amp;lt;number&amp;gt;
  138. &amp;lt;number&amp;gt;
  139. &amp;lt;number&amp;gt;
  140. &amp;lt;number&amp;gt;
  141. &amp;lt;number&amp;gt;
  142. &amp;lt;number&amp;gt;
  143. &amp;lt;number&amp;gt;
  144. &amp;lt;number&amp;gt;
  145. &amp;lt;number&amp;gt;
  146. &amp;lt;number&amp;gt;
  147. &amp;lt;number&amp;gt;
  148. &amp;lt;number&amp;gt;
  149. &amp;lt;number&amp;gt;
  150. &amp;lt;number&amp;gt;
  151. &amp;lt;number&amp;gt;
  152. &amp;lt;number&amp;gt;
  153. &amp;lt;number&amp;gt;
  154. &amp;lt;number&amp;gt;
  155. &amp;lt;number&amp;gt;
  156. &amp;lt;number&amp;gt;
  157. &amp;lt;number&amp;gt;
  158. &amp;lt;number&amp;gt;
  159. &amp;lt;number&amp;gt;
  160. &amp;lt;number&amp;gt;
  161. &amp;lt;number&amp;gt;
  162. &amp;lt;number&amp;gt;
  163. &amp;lt;number&amp;gt;
  164. &amp;lt;number&amp;gt;
  165. &amp;lt;number&amp;gt;
  166. &amp;lt;number&amp;gt;
  167. &amp;lt;number&amp;gt;
  168. &amp;lt;number&amp;gt;
  169. &amp;lt;number&amp;gt;
  170. &amp;lt;number&amp;gt;
  171. &amp;lt;number&amp;gt;
  172. &amp;lt;number&amp;gt;
  173. &amp;lt;number&amp;gt;
  174. &amp;lt;number&amp;gt;
  175. &amp;lt;number&amp;gt;
  176. &amp;lt;number&amp;gt;
  177. &amp;lt;number&amp;gt;
  178. &amp;lt;number&amp;gt;
  179. &amp;lt;number&amp;gt;
  180. &amp;lt;number&amp;gt;
  181. &amp;lt;number&amp;gt;
  182. &amp;lt;number&amp;gt;
  183. &amp;lt;number&amp;gt;
  184. &amp;lt;number&amp;gt;
  185. &amp;lt;number&amp;gt;
  186. &amp;lt;number&amp;gt;
  187. &amp;lt;number&amp;gt;
  188. &amp;lt;number&amp;gt;
  189. &amp;lt;number&amp;gt;
  190. &amp;lt;number&amp;gt;
  191. &amp;lt;number&amp;gt;
  192. &amp;lt;number&amp;gt;
  193. &amp;lt;number&amp;gt;
  194. &amp;lt;number&amp;gt;
  195. &amp;lt;number&amp;gt;
  196. &amp;lt;number&amp;gt;
  197. &amp;lt;number&amp;gt;