You are on page 1of 151

Welcome

Introduction

C programming language was developed 1972 by Dennis

Ritchie in Bell Laboratories.

Its an offspring of Basic combined programming called B which was developed by Ken Thomson

B language was interpreter-based but it was very slow So Dennis Ritchie modified the B language and named it as C

History
1960
1967 ALGOL BCPL

International Group
Martin Richards

1970

B Traditional C

Ken Thompson Dennis Ritchie Kernighan & Ritchie

1972

1978

K&R

1989

ANSI C

ANSI Committee

1990

ANSI/ISO C

ISO Committee

Benefits

C programs are efficient, fast & Highly portable It can be written in one computer and can be run in another computer without any Modification.

Its easy for debugging, testing & maintenance because of structured programming

Functions can be used many Number of building blocks

COMPILER

A compiler is a computer program (or set of programs) that transforms source code written in a computer language (the source language) into another computer language (the target language, often having a binary form known as object code). The most common reason for wanting to transform source code is to create an executable program. The name "compiler" is primarily used for programs that translate source code from a high-level programming language to a lower level language (e.g., assembly language or machine code). A program that translates from a low level language to a higher level one is a decompiler. A program that translates between high-level languages is usually called a language translator,

DIFFERENCE BETWEEN COMPILER AND


INTERPRETER
1.Compiler checks syntax of programme where as Interpreter checks the keywords of a prog. 2. compiler checks at a time all the prog, But interpreter checks simultaneously in the eidtor. 3.Interpretor provides colour coding to the prog and helps in self debugging while writing a prog.

Why

C used Widely

Pointers it allow reference to memory location

by a name

Memory allocation Allow static as well as dynamic memory location

Recursion Is a process in which a function can call itself

Bit Manipulation Allows manipulation of data in its lowest form of storage

DIFFERENCE BETWEEN STATIC AND DYNAMIC


Static memory allocation: The compiler allocates the required memory space for a declared variable. By using the address of operator, the reserved address is obtained and this address may be assigned to a pointer variable. Since most of the declared variable have static memory is assigned during compilation time. Dynamic memory allocation: It uses functions such as malloc( ) or calloc( ) to get memory dynamically. If these functions are used to get memory dynamically and the values returned by these functions are assingned to pointer variables, such assignments are known as dynamic memory allocation. memory is assined during run time.

Structure of the programming


Documentation Section Link Section Definition Section Global Declaration Section Main() Function Section { Declaration Part Executable Part }

Subprogram Section (User-defined FUnctions)

ABOUT PRINTF:
Printf The printf statement allows you to send output to standard out. Here is program that will help you learn more about printf: #include <stdio.h> int main() { int a, b, c; a = 5; b = 7; c = a + b; printf("%d + %d = %d\n", a, b, c); return 0; }

ABOUT SCANF:

The scanf function allows you to accept input from standard in, which for us is generally the keyboard.

For Example: #include <stdio.h> int main()

{
int a, b, c;

printf("Enter the first value:");


scanf("%d", &a);

printf("Enter the second value:");


scanf("%d", &b); c = a + b;

printf("%d + %d = %d\n", a, b, c);


return 0;

Simple Programs
# include <stdio.h> # include <conio.h> Void main() { /*Program to Display The Content*/ clrscr(); printf(Good Morning..! Have a Nice Day); getch(); }

Simple Programs
# include <stdio.h>

# include <conio.h>
Void main()

{
/*Program for Addition*/ int a,b,c;

clrscr();
printf(Enter the value of A :);

scanf(%d,&a);
printf(Enter the value of B :);

scanf(%d,&b);
c=a+b; printf(The Value of C is :,c);

Character Set

The Character that can be used to form words, numbers and expression depends upon the computer on which the program runs. Letters Digits Special Character White Space

, .

.Comma .Period

& ^

.Ampersand .Caret

;
: ? ' " ! |

.Semicolon
.Colon .Question Mark .Aphostrophe .Quotation Marks .Exclaimation Mark .Vertical Bar

*
+ < > ( )

.Asterisk
.Minus Sign .Plus Sign .Opening Angle (Less than sign) .Closing Angle (Greater than sign) .Left Parenthesis .Right Parenthesis

/
\ ~ -

.Slash
.Backslash .Tilde .Underscore

[
] { }

.Left Bracket
.Right Bracket .Left Brace .Right Bracket

$
%

.Dollar Sign
.Percentage Sign

#
.

.Number Sign
.

Keywords

Keywords are words that have special meaning to the C compiler. These keywords cannot be used as identifiers in the program

auto

double

int

struct

break

else

long

switch

case

enum

register

typedef

char

extern

return

union

const

float

short

unsigned

continue

for

signed

void

default

go to

size of

volatile

do

if

static

while

Identifiers
Identifiers" are the names you supply for variables, types, functions, and labels in your program. Identifier names must differ in spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved for special use. Rules: First character must be an alphabet (or underscore). Must consist of only letters, digits or underscore. Only first 31 characters are significant. Cannot use a keyword. Must not contain white space .

Constants
Constants

Numeric Constants

Character Constants

Integer

Real

Single Character

String

Data Types

This enables the programmer to select the appropriate data type as per the need of the application ANSI C supports three classes of data types

Data Type

Bytes

Default Range

signed char

-128 to 127

Unsigned char

0 to 255

short signed int

-32768 to 32767

short unsigned int

0 to 65535

Primary data types


Derived data types

long signed int

-2147483648 to 2147483647

long unsigned int

0 to 4294967295

User-defined data types

Float

-3.4e38 to +3.4e38

Double

-1.7e308 to +1.7e308

long double

10

-1.7e4932 to +1.7e493

Operator and Expressions

Operator indicates an operation to be performed on data that yields a value


1.

2.
3.

4.
5.

6.
7. 8.

Arithmetic operators (+,-,*,/,%) Relational operators (>,<,= =,>=,<=,!=) Logical operators (&&,||,!) Increment and decrement operator (++,--) Assignment operator (=) Bitwise operator (&,|,^,>>,<<) Comma operator (,) Conditional operator (?,:)

Operator Precedence
Operator Description Parentheses (function call) (see Note 1) Brackets (array subscript) Member selection via object name Member selection via pointer Postfix increment/decrement (see Note 2) Prefix increment/decrement Unary plus/minus Logical negation/bitwise complement Cast (change type) Dereference Address Determine size in bytes Multiplication/division/modulus Associativity left-to-right () [] . -> ++ --

++ -+ ! ~ (type) * & sizeof * / %

right-to-left

left-to-right left-to-right
left-to-right left-to-right

+ << >>
< <= > >=

Addition/subtraction Bitwise shift left, Bitwise shift right


Relational less than/less than or equal to Relational greater than/greater than or equal to

== != & ^ | &&

Relational is equal to/is not equal to Bitwise AND Bitwise exclusive OR Bitwise inclusive OR Logical AND

left-to-right left-to-right

left-to-right
left-to-right left-to-right

||
?:

Logical OR
Ternary conditional Assignment Addition/subtraction assignment Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment Comma (separate expressions)

left-to-right
right-to-left

right-to-left

= += *= %= ^= <<=

-= /= &= |= >>=

left-to-right

BACKSLASH CODES FOR IN CHARACTER


CONSTANTS AND STRINGS

\a alert, audible alarm, bell


\b Backspace,

\f Form feed, new page,


\n New line, carriage return and line feed

\o Octal constant
\r Carriage return, no line feed,

\t Horizontal tab, tab


\v Vertical tab, \x Hexadecimal constant, \" Quote character \ Apostrophe character \\ Backslash character \? Question mark character

FORMAT COMMANDS FOR PRINTF() SCANF() FPRINTF(), FSCANF() SPRINTF() SSCANF()


%c a single character, char %d a decimal number, int , %hd is for short %ld is for long %e a floating point number, float in scientific notation, %E for 1.0E-3 %le is for double, %Le is for long double

%f a floating point number with decimal point %10.4f 10 wide .dddd %lf is for double, %Lf is for long double %g a floating point number, %f or %e as needed, %G for capital E %lg is
for double, %Lg is for long double

%h an unsigned hexadecimal short integer (scanf only), old usage


%i an integer, int %hi is for short int, %li is for long int %n pointer to integer to receive number of characters so far, int *i %o an unsigned octal number, unsigned int %ho and %lo for short and long %p a pointer, void **x %s a string ( must be null terminated ! ), use %s for scanf %u an unsigned decimal integer (printf only), unsigned int %hu %lu %x a hexadecimal number, %X for capital ABCDEF.

PREPROCESSOR DIRECTIVES:

#include "mine.h"search current working directory first


#include <stdio.h>search command line directory then system #define TRUE 1macro substitution, usually use capitals #define min(a,b) (a<b)?(a):(b)macro substitution with parameters #define abs(a) (a<0)?(-(a)):(a)macro substitution #define note /* comment */ this comment gets inserted every time note appears */ backslash \ at end of a line means continue #undef TRUEundefines a previously defined macroname

#error stop compiling at this point


#if expressionconditional compilation, start if structure

#elif expressionelse if expression != 0 compile following code


#elseelse compile following code

#endifend of conditional compiling


#ifdef macronamelike #if, compiles if macroname defined #ifndeflike #if, compiles if macroname undefined #line number [filename]set origin for __LINE__ and __FILE__ #pragmagives the compiler commands

Decision Statement
To alter the flow of a program. Test the logical conditions. Control the flow of execution as per the selection.

if-statements if-else statement else-if statement Nested if statement switch-statement

If-Construct
Syntax: i) if (expr) statement; ii) if(expr) { statement1; statement2; }

where expr is Boolean Note:


True Boolean values are any integer different from zero. False Boolean value is the integer zero.

If-else Construct
Syntax: if (expr) statement1; else statement2; Example: a=5,b=10 if (a<b) { printf(b is bigger than a); } else { Printf(a is bigger than b); }

Else-if Construct
Syntax: if (expr) Statement 1; else if(expr1) Statement 2; else if(exp2) Statement 3; else Statement n; Example: a=5 b=10 c=15 If (a>b && a>c) { printf (a is the biggest no); } else if (b>c) { printf(b is the biggest no); } else { Printf(c is the biggest no); }

Nested if Construct
i)
If(expr) { if(expr2) statement 1; }
ii) If(expr) { if(expr1) statement1; else statement2; } else { if(expr2) statement3; else if(expr3) statement4; else statement5; }

Example for Nested if


A=5 b=10 c=20

If(a>b) { if(a>c) { printf(a is the biggest no); } else { printf(c is the biggest no); } } Else if(b>c) { printf(b is the biggest no); } Else { printf(c is the biggest no); }

evencount = oddcount = 0; if ( (num % 2) == 0 ) { printf(%d is an even number.\n, num); ++evencount; if( (num % 4) == 0 ) printf(It is divisible by 4\n); if( num == 0 ) { printf(It is zero.\n); printf(That isnt interesting.\n); } } else { printf(%d is an odd number.\n, num); ++oddcount; if( (num % 9) == 0 ) printf(It is divisible by 9\n); else printf(It is not divisible by 9\n); }

Switch Construct
Syntax: switch (expr) /* expr is a boolean expression { case C1: {statement0;break;} case C2: {statement1;break;} default: /* optional */ {DefaultStatement;break;} } Note : C1 & C2 represent values. It is the type of int or char only.

Example for Switch Construct


Int a; Scanf (%d,&a); Switch (a) { case 1: printf (you entered : %d,1); break; case 2: printf(you entered : %d ,2); break; case 3: printf (you entered : %d ,3); break; default: /*optional*/ printf (you entered except 1,2,3); } Char a; Scanf(% c,&a); Switch (a) { case a: printf(you entered : a); break; case b: printf(you entered : b); break; case c : printf(you entered : c); break; default: /* optional*/ printf(you entered except a,b,c); }

Loop Control Statements


Looping is deciding how many times to take certain action. In looping process in general would include the following four
steps 1. Setting and initialization of a counter. 2. Exertion of the statements in the loop. 3. Test for a specified conditions for the execution of the loop. 4. Incrementing the counter.

Types
while-statement do-while statement for-statement

While Constructs
Syntax: while(expr) { statement1; statement2; }

while (expr) Statement;

where expr is Boolean Note:

True Boolean values are any integer different from zero; False Boolean value is the integer zero.

Example for While Construct


i=0; while(i<10) #include<stdio.h> int main()

{
printf(precision\n); i++; }

{
int counter, howmuch; scanf("%d", &howmuch); counter = 0;

while ( counter < howmuch)


{

counter++;
printf("%d\n", counter);

}
return 0; }

Do-while Construct
Syntax: do { statement1; statement2; }while(expr);

do Statement; while (expr);

Note: while statement executes zero or more iterations of the loop; do-while statement executes one or more iterations of the loop.

Example for do-while construct


i=0; do { printf(precision\n); i++; } while(i<10);
#include<stdio.h> int main() { int counter, howmuch; scanf("%d", &howmuch); counter = 0; do { counter++; printf("%d\n", counter); } while ( counter < howmuch); return 0; }

For Construct
Syntax: for(expr1; expr2; expr3) Statement; for(expr1;expr2;expr3) { statement1; statement2; }

Semantic: equivalent to expr1; while (expr2) { Statement; expr3; }

Example for For Construct


#include<stdio.h> int main() { int i; for (i = 0; i < 10; i++) { printf ("Hello\n"); printf ("World\n"); } return 0; } #include<stdio.h> int main() { int i; for (i =20; i >10; i--) { printf ("Hello\n"); printf ("World\n"); i--; } return 0; }

Looping Related Statements


Break Continue

Break statement
Syntax: break;
Semantic: terminates the execution of a loop or a switch

Example for Break Statement


#include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; if ( i == 10) break; } return 0; }

Continue statement
Syntax: continue;

Semantic: terminates the current iteration of a loop

Example for Continue Statement


#include<stdio.h> int main() { int i; i = 0; while ( i < 20 ) { i++; continue; printf("Nothing to see\n"); } return 0; }

Unconditional jump statement


Syntax: goto Label;

where Label:Statement; belongs to the program


Semantic: forces control to go to the Statement;

Example for goto Statement


#include<stdio.h> int main() { Int i=0; START: i++; printf(%d\n,i); if(a<=10) { goto START; } else { goto END; } END: return 0; }

Array

One-Dimensional array Two-Dimensional array Multi-Dimensional array

One-Dimensional Array

collection of elements of same data type that are stored contiguous in memory.
data

10

20

30

25

35

50

45

28

14

1000 1002

1004 1006 1008

1010 1012

1014 1016

1018

Address

One-Dimensional Array

The subscript, or the index of each array element is determined based on the number of offset positions it is from the starting position. The starting offset is taken as 0.
offset
0
10

1
20

2
30

3
25

4
35

5
6

6
50

7
45

8
28

9
14

1000 1002

1004 1006 1008

1010 1012

1014 1016

1018

One-Dimensional Array
Syntax:

datatype variablename [size];

Example:
int a[10]; block of 10 contiguous elements in memory.

Array name (Starting address of the array)

a
offset

a[0]

a[1]

a[2]

a[3] a[4]

a[5] a[6]

a[7] a[8]

a[9]

One-Dimensional Array
Initialization

A character array needs a string terminator, the NULL character (\0) as the last character, whereas integer and float arrays do not need a terminator. Examples:
char array1[ ] = {A, R, R, A, Y, \0}; char array2[ ] = {ARRAY}; char dayofweek[7] = {M, T, W, T, F, S, S};

float values[ ] = {100.56, 200.33, 220.44, 400.22, 0};

Initialization
Example:

One-Dimensional Array

#include<stdio.h> main( ) { char array1[ ] = {A, R, R, A, Y, \0};


char array2[ ] = {ARRAY};

int i = 0;
printf( String 1 is %s\n, array1); printf( String 2 is %s\n, array2); }

One-Dimensional Array
Initialization
int a[5]={7,3,8,2,25}; (or) int a[5]; a[0]=7; a[1]=3; a[2]=8; a[3]=2; a[4]=25;

Input To Array
Normal Variable:

Array Variable:
int a[20],i; for(i=0;i<20;i++) { scanf(%d, &a[ i ]); }

int a; scanf(%d,&a);
Array Variable: int a[20]; scanf(%d,&a[0]); ----scanf(%d,&a[19]);

Array offset always start with 0

4 lines

Which one is best ?


20 lines

Array Manipulation Using Subscripts


/* this function finds the length of a character string */ #include <stdio.h> main( ) { int i = 0; char string[11]; /* char array decalaration */ printf(Enter a string of maximum ten characters\n);

gets(string);

buffer) */

/* get the input from the keyboard (stdin


/* clear the stdin buffer */

fflush( stdin);

for(i =0; string[i] != \0; i = i + 1); printf(The length of the string is %d \n, i);
}

Array Addressing

In the declaration: char string[11]; the name of the array refers to the starting address of the area that gets allocated for storing the elements of the array.
Thus, string contains the address of string[0]. In the aforesaid declaration, string refers to the starting position of the array, and the subscript refers to the offset position from the starting position.

Array Addressing
string

100

100

101

102

103

104

105

106

107

108

109

110

a
0

b
1

c
2

d
3

e
4

f
5

g
6

h
7

i
8

j
9

\0
10

Array Addressing
To arrive at the address of the particular element, the compiler applies the following simple formula:

starting address of the array + ( offset position * size of data type)

Address of element 4 = 100 + ( 3 * 1) = 100 +3 = 103

One-Dimensional Array
Example: #include <stdio.h> int main() { int iMarks[4]; short newMarks[4]; iMarks[0]=78; iMarks[1]=64; iMarks[2]=66; iMarks[3]=74; for(i=0; i<4; i++) newMarks[i]=iMarks[i];

for(j=0; j<4; j++) printf("%d\n", newMarks[j]); return 0;


}

Two-Dimensional Array
Syntax:
datatype variablename [rowsize] [columnsize];

Example: int a[4][3]; block of 15(5*3) contiguous elements in memory.

Address
Of a[0][0]

a[0][0] 1000 1006

Column offset value

0
1 2 3 a[0][2] 1004

Row offset value

Two-Dimensional Array
Initialization

Example:
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };

int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; char arr[3][12]= { "Rose", "India", "technologies" };

Two-Dimensional Array
Initialization
Example: #include <stdio.h> #include <conio.h> void main() { char arr[3][12]= { "Rose", "India", "technologies" }; clrscr(); printf("Array of String is = %s,%s,%s\n", arr[0], arr[1], arr[2]); getch(); }

Input To 2-D Array


1-D Array: 2-D Array:

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

int a[10][5],i,j;
for(i=0;i<10;i++) { for(j=0;j<5;j++) { scanf(%d,&a[i][j]); } }

Increment row index

Increment column index

Note:

In this 2-D array example we will get input row by row. That means get rows value one by one using inner for loop. Increment row using outer loop.

Example: main ( ) { int stud [4] [3]; int i, j; for (i =0; i < =3; i ++) { for(j=0;j<=2;j++) { printf ("\n Enter roll no. and marks"); scanf ("%d%d", &stud [i] [j], &stud [i] [j] ); } }
for (i = 0; i < = 3; i ++) { for(j=0;j<=2;j++) { printf ("\n %d %d", stud [i] [j], stud [i] [j]); } }

Two-Dimensional Array

Functions

A function is a sub-program of one or more statements that performs a special task when called C supports two types of function

Library Function
User Defined Function
main()
{ -------

abc(x,y,z);
-------

Function call (Actual argument)

}
abc(l,k,j) Function Definition (Formal argument)

{ }

-------------

Functions

A function is a sub-program of one or more statements that performs a special task when called
C supports two types of function

Library Function
User Defined Function

A function is declared as

return-value-type function-name( parameter-list ) { declarations and statements }

Function definition format (continued)


return-value-type function-name( parameter-list ) { declarations and statements }

Declarations and statements: function body

Variables can be declared inside blocks Functions can not be defined inside other functions

Returning control

If nothing returned return;

If something returned return expression

Rules and Regulations

A function should follows 1.Function Declaration 2.Function call 3.Function Definition

Example
#include<stdio.h> Void display() /* function declaration*/ Void main() { display();/*function call*/ } Void display()/*function definition*/ { int a,b,c; a=10;b=20; c=a+b; printf(%d,c); }

Key Points

C program is a collection of one or more functions.

A function gets called when the function name is followed by a semicolon. For example, main( ) { argentina( ) ; }
A function is defined when function name is followed by a pair of braces in which one or more statements may be present. argentina( ) { statement 1 ; statement 2 ; statement 3 ; }

For example,

Any function can be called from any other function. Even main( ) can be called from other functions. For example, main() { message( ) ; }

message( ) { printf ( "\nCan't imagine life without C" ) ; main( ) ; }

A function can be called any number of times.

For example, main( ) { message( ) ; message( ) ; } message( ) { printf ( "\n Hai Welcome to C Language !!" ) ; }

Advantages of Functions

Divide and conquer

Manageable program development Use existing functions as building blocks for new programs

Software reusability

Avoid code repetition

Types of functions
There are mainly 4 types of functions 1.Function with no arguments and no return values 2.Functions with arguments and no return values 3.Functions without arguments and no return values 4. Functions with arguments and return values

Function with no arguments and no return values


void main() { Printf(welcome to c); message(); printf(for good learning c); } Void message() { printf(all the best); }

Function with arguments and no return values


#include<stdio.h> Void main() { int a,b,c; a=10;b=20; add(a,b); } Void add( int x,int y) {
printf(%d,(x+y));

Function without arguments and return values


#include<stdio.h> Void main() { Int c; c= add(); Printf(%d,c); } int add() { int a,b,c; a=10;b=20; return(a+b); }

Function with arguments and return values


#include<stdio.h> Void main() { int a,b; a=10;b=20; c= add(a,b); Printf(%d,c); } int add (int x, int y) { return(x+y); }

Invoking functions

Function can be be invoked by using two ways 1.Call by value 2.call by reference

Call by value

If a function is invoked by passing values of actual arguments to is corresponding formal arguments. Whenever using call by value, the values of actual arguments is copied into its corresponding formal arguments

Whenever we make changes in formal arguments which will not reflect to its corresponding actual arguments.

Example
#include<stdio.h> Void exchange(int a,int b) { int t; t=a; a=b; b=t; printf(the values of a and b are:%d%d,a,b); } Main() { int a,b; a=10;b=20; exchange(a,b);/* call by value procedure*/ }

2. Call by reference

If a function is invoked by passing the address of actual arguments to its corresponding formal arguments. If we make changes in the formal arguments ,all the values will reflected into its corresponding actual arguments.

Example
#include<stdio.h> Void exchange(int *a,int *b) { int t; t=*a; *a=*b; *b=t; printf(the values of a and b are:%d%d,*a,*b); } Main() { int a,b; a=10;b=20; exchange(&a,&b);/* call by reference procedure*/ }

Function Prototype

Function name Parameters what the function takes in Return type data type function returns (default int)

Used to validate functions Prototype only needed if function definition comes after use in program The function with the prototype

int maximum( int, int, int ); Takes in 3 ints Returns an int

Recursion Function

A function call by itself

Example: int main() { int result, number; ... result = factorial( number ); } int factorial( int num ) /* Function definition */ { ... if ( ( num > 0 ) || ( num <= 10 ) ) return( num * factorial( num - 1 ) ); /*call itself */ }

Structures

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 to 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. An example of a structure is the payroll record: an employee is described by a set of attributes such as name, address, social security number, salary, etc.

Declaring a Structure

The C language provides the struct keyword for declaring a structure. The following is a structure declaration for employee attributes.
struct empdata
{ int empno; char name[10]; char job[10]; float salary; };

Declaring a Structure Variable


struct empdata { int empno; char name[10]; char job[10]; float salary; } emprec; /* emprec is a variable of structure type empdata */

Or a structure can be declared separately as: struct empdata emprec;/* emprec is a variable of structure type empdata */

Accessing Elements of a Structure

Once a structure variable has been declared, the individual members of the structure can be accessed by prefixing the structure variable to the element of the structure.
struct empdata { int empno; char name[10]; char job[10]; float salary; } struct empdata emprec; emprec.empno=101; /* referring to the element of the structure variable emprec */

Structure Example
#include< stdio.h > void main() { struct { int id_no; char name[20]; char address[20]; int age; }newstudent; printf(Enter the student information); printf(Now Enter the student id_no); scanf(%d,&newstudent.id_no); printf(Enter the name of the student); scanf(%s,&new student.name); printf(Enter the address of the student); scanf(%s,&new student.address);

printf(Enter the age of the student); scanf(%d,&new student.age);


printf(Student information\n); printf(student id_number=%d\n,newstudent.id_no); printf(student name=%s\n,newstudent.name); printf(student Address=%s\n,newstudent.address); printf(Age of student=%d\n,newstudent.age); }

Initializing of a structure
struct empdata

{
int empno; char name[10];

char job[10];
float salary;

}emprec={101,Arun,Developer,20000};

Array of Structures

Just as it is possible to declare arrays of primitive data types, it should also be possible to declare arrays of structures as well. Consider the structure declaration for the employee details used earlier.

struct empdata
{

int empno;
char name[10]; char job[10]; float salary; };

struct empdata employee_array[4];

Structure Example
#include< stdio.h > { struct info { int id_no; char name[20]; char address[20]; char combination[3]; int age; } struct info std[100]; int I,n; printf(Enter the number of students); scanf(%d,&n); printf( Enter Id_no,name address combination age\m); for(I=0;I < n;I++) scanf(%d%s%s%s%d,&std[I].id_no,std[I].name,std[I].address,std[I].combin ation,&std[I].age); printf(\n Student information); for (I=0;I< n;I++) printf(%d%s%s%s%d\n, ,std[I].id_no,std[I].name,std[I].address,std[I].combination,std[I].age); }

Structure within Structure

A structure may be defined as a member of another structure. In such structures the declaration of the embedded structure must appear before the declarations of other structures.

struct date { int day; int month; int year; }; struct student { int id_no; char name[20]; char address[20]; char combination[3]; int age; structure date def; structure date doa; }oldstudent, newstudent;

Structures & Files

Consider a situation where your application needs to read records from a file for processing. The general approach would be to read the various fields of a record into corresponding memory variables.

Computations can then be performed on these memory variables, the contents of which can then be updated to the file.
But, this approach would involve manipulating the current file offset for the relevant fields that need to be updated.

Writing Records On To a File

The fwrite( ) function allows a structure variable to be written on to a file.

The following statement writes the structure variable salesvar on to a file SALES.DAT, which is pointed to by the FILE type pointer fp:
fwrite( &salesvar, sizeof(struct salesdata), 1, fp);

Reading Records from a File

Records can be read from a file using fread( ). The corresponding read statement using fread( ) for the earlier fwrite( ) statement would be: fread(&salesvar, sizeof(struct salesdata), 1, fp); Here, the first parameter &salesvar is the address of the structure variable salesvar into which 1 record is to be read from the file pointed to by the FILE type pointer fp. The second parameter specifies the size of the data to be read into the structure variable.

Structures with pointers

We can store the address structure variable in a pointer variable

The pointer variable also should be the variable for the structure data type;
#include<stdio.h> struct student { int rollno; int marks; }s={101,99},*p;

Accessing structure by pointer


#include<stdio.h> struct student { int rollno; int marks; }s={101,99},*p; main() { p=&s; printf("%d",(*p).rollno); printf("%d",(*p).marks); }

Accessing structure by pointer

With pointers, though, in accessing structure members an arrow notation is used, rather than the dot notation:
struct student { int rollno; int marks; }s={101,99},*p; main() { p=&s; printf("%d",p->rollno); printf("%d",p->rollno); getch(); }

Passing structure in a function


struct student{ int rollno; int marks; }s={101,99},*p; main() { p=&s; printf("%d",p->rollno); printf("%d", p->marks); f1(&s); printf("%d", p-> rollno); printf("%d", p-> marks); } f1(struct student *s1) { s1->rollno=103; }

Pointers

Pointers is a memory variable that stores a memory address It always denoted by (*) asterisk symbol

Features

Pointers save the memory space. Direct access to memory location Useful for representing two-dimensional & Multi- dimensional array

Declaration
int *x; float *f;

Example for Pointer


# include <stdio.h> # include <conio.h> void main() { int v=10, *p; clrscr(); p=&v; printf( \n Address of V = %u ,p); printf( \n Value of V = %d ,*p); printf( \n Address of P = %u ,&p); } Output Address of V = 4060 Value of V = 10 Address of P = 4062

Pointers

Pointers are variables that contain memory addresses as their values. A variable name directly references a value. A pointer indirectly references a value. Referencing a value through a pointer is called indirection. A pointer variable must be declared before it can be used.

It always denoted by (*) asterisk symbol

Concept of Address and Pointers


Memory can be conceptualized as a linear set of data locations. Variables reference the contents of a locations Pointers have a value of the address of a given location

ADDR1 ADDR2 ADDR3 ADDR4 ADDR5 ADDR6

Contents1

* * *
ADDR11 Contents11

* *
ADDR16 Contents16

Syntax: datatype * variablename; identifier

Example:

Indirection operator int *a;

Pointer variable

Note: A normal variable(identifier) declared with * symbol is called pointer variable.

Examples of pointer declarations: int *a; float *b; char *c;


The asterisk, when used as above in the declaration, tells the compiler that the variable is to be a pointer, and the type of data that the pointer points to, but NOT the name of the variable pointed to.

Consider the statements:

#include <stdio.h> int main ( ) { int *aptr ; */ float *bptr ; float */ int a =10; float b =2.5f;

/* Declare a pointer to an int /* Declare a pointer to a


/* Declare an int variable */ /* Declare a float variable */

aptr = &a ; bptr = &b ;

printf(%u,&a); printf(%u,aptr); printf(%d,a); printf(%d\n,*aptr);


printf(%u,&b); printf(%u,bptr); printf(%f,b); printf(%f,*bptr); return 0 ; }

aptr
1000 10

a
1000

bptr
1500

b
2.5

1500

Output: 1000 1000 10 10 1500 1500 2.500000 2.500000

Use of & and *

When is & used? When is * used?

& -- "address operator" which gives or produces the memory address of a data variable * -- "dereferencing operator" which provides the contents in the memory location specified by a pointer

Arithmetic and Logical Operations on Pointers


A pointer may be incremented or decremented An integer may be added to or subtracted from a pointer. Pointer variables may be subtracted from one another.

Pointer variables can be used in comparisons, but usually only in a comparison to NULL.

Arithmetic Operations on Pointers

When an integer is added to or subtracted from a pointer, the new pointer value is changed by the integer times the number of bytes in the data variable the pointer is pointing to.

For example, if the pointer valptr contains the address of a double precision variable and that address is 234567870, then the statement: valptr = valptr + 2; would change valptr to 234567886

Arithmetic Operations on Pointers


Example: int *a; int b=10; a=&b;

Before this Statement


1000

2.5

a++;

1000 After this Statement a++ a=a+1 Integer 1=2bytes

1000++ a=1000+1 a value is 1002

Arithmetic Operations on Pointers


Example: #include< stdio.h > main() { int *ptr1,*ptr2; int a,b,x,y,z; a=30;b=6; ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 6; y=6*- *ptr1/ *ptr2 +30; printf(\nAddress of a +%u,ptr1); printf(\nAddress of b %u,ptr2); printf(\na=%d, b=%d,a,b); printf(\nx=%d,y=%d,x,y); ptr1=ptr1 + 70; ptr2= ptr2; printf(\na=%d, b=%d,a,b); }

Pointer to arrays
An array is actually very much like pointer. We can declare the arrays first element as a[0] or as int *a because a[0] is an address and *a is also an address the form of declaration is equivalent. The difference is pointer is a variable and can appear on the left of the assignment operator that is lvalue. The array name is constant and cannot appear as the left side of assignment operator.

Pointer to arrays
/* A program to display the contents of array using pointer*/ main() { int a[100]; int i,j,n; printf(\nEnter the elements of the array\n); scanf(%d,&n); printf(Enter the array elements); for(I=0;I< n;I++) scanf(%d,&a[I]); printf(Array element are); for(ptr=a,ptr< (a+n);ptr++) printf(Value of a[%d]=%d stored at address %u,j+=,*ptr,ptr); } Strings are characters arrays and here last element is \0 arrays and pointers to char arrays can be used to perform a number of string functions.

File I/O in C

Files in C

In C, each file is simply a sequential stream of bytes. C imposes no structure on a file.

A file must first be opened properly before it can be accessed for reading or writing. When a file is opened, a stream is associated with the file.
Successfully opening a file returns a pointer to (i.e., the address of) a file structure, which contains a file descriptor and a file control block.

Files in C

The statement: FILE *fp1, *fp2 ; declares that fptr1 and fptr2 are pointer variables of type FILE. They will be assigned the address of a file descriptor, that is, an area of memory that will be associated with an input or output stream. Whenever you are to read from or write to the file, you must first open the file and assign the address of its file descriptor (or structure) to the file pointer variable.

Opening Files

Syntax:

FILE *fp; fp=fopen(filename,mode);

The statement: fp1 = fopen ( "mydata", "r" ) ; would open the file mydata for input (reading).

Opening Files

The statement: fp = fopen ("results", "w" ) ; would open the file results for output (writing).
Once the files are open, they stay open until you close them or end the program (which will close all files.)

Testing for Successful Open

If the file was not able to be opened, then the value returned by the fopen routine is NULL. For example, let's assume that the file mydata does not exist. Then: FILE *fptr1 ; fptr1 = fopen ( "mydata", "r") ; if (fptr1 == NULL) { printf ("File 'mydata' did not open.\n") ; }

Open Mode
"r Open text file for reading only "w Truncate to 0 length, if existent, or create text file for writing only. "a Append; open or create text file only for writing at end of file "r+ Open text file for update (reading and writing) "w+ Truncate to 0 length, if existent, or create text file for update "a+ Append; open or create text file for update, writing at end of file

File operation functions in C


Function Name Operation

fopen()

Creates a new file for use Opens a new existing file for use
Closes a file which has been opened for use

Fclose()

getc()

Reads a character from a file

putc()

Writes a character to a file

File operation functions in C


fprintf() Writes a set of data values to a file

fscanf()

Reads a set of data values from a file

getw()

Reads a integer from a file

putw()

Writes an integer to the file

File operation functions in C


fseek() Sets the position to a desired point in the file

ftell()

Gives the current position in the file

rewind()

Sets the position to the begining of the file

getc() & putc()


#include< stdio.h > main() { file *f1; printf(Data input output); f1=fopen(Input,w); /*Open the file Input*/
while((c=getchar())!=EOF) /*get a character from key board*/ putc(c,f1); /*write a character to input*/

fclose(f1); /*close the file input*/ printf(\nData output\n); f1=fopen(INPUT,r); /*Reopen the file input*/ while((c=getc(f1))!=EOF) printf(%c,c); fclose(f1);

getw() & putw()


#include< stdio.h > main() { FILE *f1,*f2,*f3; int number I; printf(Contents of the data file\n\n); f1=fopen(DATA,W); for(I=1;I< 30;I++) { scanf(%d,&number); if(number==-1) break; putw(number,f1); } fclose(f1); f1=fopen(DATA,r); f2=fopen(ODD,w); f3=fopen(EVEN,w);

getw() & putw()


while((number=getw(f1))!=EOF)/* Read from data file*/ { if(number%2==0) putw(number,f3);/*Write to even file*/ else putw(number,f2);/*write to odd file*/ } fclose(f1); fclose(f2); fclose(f3); f2=fopen(ODD,r); f3=fopen(EVEN,r); printf(\n\nContents of the odd file\n\n); while(number=getw(f2))!=EOF) printf(%d%d,number); printf(\n\nContents of the even file); while(number=getw(f3))!=EOF) printf(%d,number); fclose(f2); fclose(f3); }

Reading From Files

In the following segment of C language code:

int a, b ; FILE *fptr1, *fptr2 ; fptr1 = fopen ( "mydata", "r" ) ; fscanf ( fptr1, "%d%d", &a, &b) ; the fscanf function would read values from the file "pointed" to by fptr1 and assign those values to a and b.

End of File
The end-of-file indicator informs the program when there are no more data (no more bytes) to be processed. There are a number of ways to test for the end-offile condition. One is to use the feof function which returns a true or false condition:

fscanf (fptr1, "%d", &var) ; if ( feof (fptr1) ) { printf ("End-of-file encountered.\n); }

End of File

There are a number of ways to test for the end-offile condition. Another way is to use the value returned by the fscanf function: int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == EOF ) { printf ("End-of-file encountered.\n) ; }

Writing To Files

Likewise in a similar way, in the following segment of C language code: int a = 5, b = 20 ; FILE *fptr2 ; fptr2 = fopen ( "results", "w" ) ; fprintf ( fptr2, "%d %d\n", a, b ) ; the fprintf functions would write the values stored in a and b to the file "pointed" to by fptr2.

Closing Files

The statements: fclose ( fptr1 ) ; fclose ( fptr2 ) ; will close the files and release the file descriptor space and I/O buffer memory.

Reading and Writing Files


#include <stdio.h> int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ;

outfile = fopen ("testdata", "w") ; fprintf (outfile, "%6.2f%2d%5.2f", a, b, c) ; fclose (outfile) ;

Reading and Writing Files


infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ;

printf ("%6.2f%2d%5.2f\n", a, b, c) ; printf ("%6.2f,%2d,%5.2f\n", e, f, g) ; } 12345678901234567890 **************************** 13.72 5 6.68 13.72, 5, 6.68

fseek()
int fseek ( Stream, Offset, Whence);

where stream -- file pointer offset -- no of position in bytes whence from position
**whence must be one of the values 0, 1, or 2 Whence value: 0 Beginning of the file 1 Current position 2 End of the file.

ftell() & rewind()


Ftell(); FILE *stream; long ftell (stream);

Rewind():

FILE *stream; void rewind (stream);

Pre Processing

in
C

Pre Processing
Refers before compiling the c program. Loads the template before compiling. Syntax #Macro Template Macro Expansion

Types of Macros
Defining Macros File Inclusion Conditional Macros Special cases

Defining Macros
#define <Label>(parameterlist)<Expansion> main() { . <Label> }

Defining Macros
Example: #include <stdio.h> #define PI 3.14 #define AREA(radius) (PI*radius*radius) main() { float areas[3]={AREA(1),AREA(2),AREA(3)}; int count; for (count=0; count <3; count++) { printf("Circle area=%f\n",areas[count]); } return 0; }

File Inclusion
#include<file name> (or) #include filename main() { .. .. }

Conditional Macros
Syntax: #ifdef MACRO controlled text #endif /* MACRO */

Syntax: # if expression controlled text # endif /* expression */

Conditional Macros
Syntax:
#if expression
text-if-true

#else /* Not expression */


text-if-false

#endif /* Not expression */

Example for elif


Example:

#if X == 1 ... #elif X == 2 ... #else /* X != 2 and X != 1*/ ... #endif /* X != 2 and X != 1*/

Thank You.

You might also like