complete c slides
DESCRIPTION
C programing language ppt slidesTRANSCRIPT
![Page 1: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/1.jpg)
C LANGUAGE PPT
By
Chandrashekar Reddy.G
Contact
+91406524833
+919985199433
![Page 2: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/2.jpg)
Welcome
![Page 3: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/3.jpg)
C
![Page 4: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/4.jpg)
Introduction
C programming language was developed 1972 by Dennis
Ritchie in Bell Laboratories.
It‟s 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„
![Page 5: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/5.jpg)
History…ALGOL
Traditional C
BCPL
ANSI C
K&R
B
ANSI/ISO C
1960
1967
1970
1972
1978
1989
1990
International Group
Martin Richards
Ken Thompson
Dennis Ritchie
Kernighan & Ritchie
ANSI Committee
ISO Committee
![Page 6: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/6.jpg)
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
![Page 7: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/7.jpg)
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,
![Page 8: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/8.jpg)
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.
![Page 9: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/9.jpg)
Why C used Widely
Pointersit allow reference to memory location
by a name
Memory allocationAllow static as well as
dynamic memory location
RecursionIs a process in which a function can
call itself
Bit ManipulationAllows manipulation of data
in its lowest form of storage
![Page 10: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/10.jpg)
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.
![Page 11: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/11.jpg)
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)
![Page 12: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/12.jpg)
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;
}
![Page 13: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/13.jpg)
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;
}
![Page 14: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/14.jpg)
Simple Programs
# include <stdio.h>
# include <conio.h>
Void main()
{
/*Program to Display The Content*/
clrscr();
printf(“Good Morning..! Have a Nice Day”);
getch();
}
![Page 15: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/15.jpg)
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);
}
![Page 16: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/16.jpg)
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
![Page 17: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/17.jpg)
, .Comma & .Ampersand
. .Period ^ .Caret
; .Semicolon * .Asterisk
: .Colon - .Minus Sign
? .Question Mark + .Plus Sign
' .Aphostrophe < .Opening Angle (Less than sign)
" .Quotation Marks > .Closing Angle (Greater than sign)
! .Exclaimation Mark ( .Left Parenthesis
| .Vertical Bar ) .Right Parenthesis
/ .Slash [ .Left Bracket
\ .Backslash ] .Right Bracket
~ .Tilde { .Left Brace
- .Underscore } .Right Bracket
$ .Dollar Sign # .Number Sign
% .Percentage Sign . .
![Page 18: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/18.jpg)
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
![Page 19: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/19.jpg)
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 .
![Page 20: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/20.jpg)
Constants
Constants
Numeric Constants Character Constants
Integer Real Single
CharacterString
![Page 21: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/21.jpg)
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
Primary data types
Derived data types
User-defined data types
Data Type Bytes Default Range
signed char 1 -128 to 127
Unsigned char 1 0 to 255
short signed int 2 -32768 to 32767
short unsigned int 2 0 to 65535
long signed int 4 -2147483648 to 2147483647
long unsigned int 4 0 to 4294967295
Float 4 -3.4e38 to +3.4e38
Double 8 -1.7e308 to +1.7e308
long double 10 -1.7e4932 to +1.7e493
![Page 22: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/22.jpg)
Operator and Expressions
Operator indicates an operation to be performed on
data that yields a value
1. Arithmetic operators (+,-,*,/,%)
2. Relational operators (>,<,= =,>=,<=,!=)
3. Logical operators (&&,||,!)
4. Increment and decrement operator (++,--)
5. Assignment operator (=)
6. Bitwise operator (&,|,^,>>,<<)
7. Comma operator (,)
8. Conditional operator (?,:)
![Page 23: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/23.jpg)
Operator PrecedenceOperator Description Associativity
()
[]
.
->
++ --
Parentheses (function call) (see Note
1)
Brackets (array subscript)
Member selection via object
name
Member selection via pointer
Postfix increment/decrement (see
Note 2)
left-to-right
++ --
+ -
! ~
(type)
*
&
sizeof
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise
complement
Cast (change type)
Dereference
Address
Determine size in bytes
right-to-left
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <=
> >=
Relational less than/less than or
equal to
Relational greater than/greater
than or equal to
left-to-right
![Page 24: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/24.jpg)
== != Relational is equal to/is not equal toleft-to-right
& Bitwise ANDleft-to-right
^ Bitwise exclusive ORleft-to-right
| Bitwise inclusive ORleft-to-right
&& Logical ANDleft-to-right
|| Logical ORleft-to-right
?: Ternary conditionalright-to-left
=
+= -=
*= /=
%= &=
^= |=
<<= >>=
Assignment
Addition/subtraction assignment
Multiplication/division
assignment
Modulus/bitwise AND
assignment
Bitwise exclusive/inclusive OR
assignment
Bitwise shift left/right
assignment
right-to-left
, Comma (separate expressions)left-to-right
![Page 25: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/25.jpg)
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
![Page 26: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/26.jpg)
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.
![Page 27: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/27.jpg)
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
![Page 28: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/28.jpg)
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
![Page 29: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/29.jpg)
If-Construct
Syntax: ii) if(expr)
i) {
if (expr) statement1;
statement; statement2;
}
where expr is Boolean
Note:
True Boolean values are any integer different from zero.
False Boolean value is the integer zero.
![Page 30: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/30.jpg)
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”);
}
![Page 31: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/31.jpg)
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”);
}
![Page 32: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/32.jpg)
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;
}
![Page 33: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/33.jpg)
Example for Nested ifA=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 isn‟t 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”);
}
![Page 34: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/34.jpg)
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.
![Page 35: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/35.jpg)
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”);
}
![Page 36: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/36.jpg)
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
![Page 37: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/37.jpg)
While Constructs
Syntax:
while(expr)
while (expr) {
Statement; statement1;
statement2;
}
where expr is Boolean
Note:
True Boolean values are any integer different from zero;
False Boolean value is the integer zero.
![Page 38: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/38.jpg)
Example for While Construct
i=0;
while(i<10)
{
printf(“precision\n”);
i++;
}
#include<stdio.h>
int main()
{
int counter, howmuch;
scanf("%d", &howmuch);
counter = 0;
while ( counter < howmuch)
{
counter++;
printf("%d\n", counter);
}
return 0;
}
![Page 39: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/39.jpg)
Do-while Construct
Syntax:
do
do {
Statement; statement1;
while (expr); statement2;
}while(expr);
Note:
while statement executes zero or more iterations of the loop;
do-while statement executes one or more iterations of the loop.
![Page 40: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/40.jpg)
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;
}
![Page 41: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/41.jpg)
For Construct
Syntax:
for(expr1;expr2;expr3)
for(expr1; expr2; expr3) {
Statement; statement1;
statement2;
}
Semantic: equivalent to
expr1;
while (expr2)
{
Statement;
expr3;
}
![Page 42: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/42.jpg)
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;
}
![Page 43: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/43.jpg)
Looping Related Statements
Break
Continue
![Page 44: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/44.jpg)
Break statement
Syntax:
break;
Semantic:
terminates the execution of a loop or a switch
![Page 45: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/45.jpg)
Example for Break Statement
#include<stdio.h>
int main()
{
int i;
i = 0;
while ( i < 20 )
{
i++;
if ( i == 10)
break;
}
return 0;
}
![Page 46: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/46.jpg)
Continue statement
Syntax:
continue;
Semantic:
terminates the current iteration of a loop
![Page 47: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/47.jpg)
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;
}
![Page 48: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/48.jpg)
Unconditional jump statement
Syntax:
goto Label;
where Label:Statement;
belongs to the program
Semantic:
forces control to go to the Statement;
![Page 49: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/49.jpg)
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;
}
![Page 50: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/50.jpg)
Array
One-Dimensional array
Two-Dimensional array
Multi-Dimensional array
![Page 51: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/51.jpg)
One-Dimensional Array
collection of elements of same data type
that are stored contiguous in memory.
1000 1002 1004 1006 1008 1010 1012 1014 1016 1018
10 20 30 35 625 50 45 28 14
data
Address
![Page 52: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/52.jpg)
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.
1000 1002 1004 1006 1008 1010 1012 1014 1016 1018
10 20 30 35 625 50 45 28 14
0 1 2 3 4 5 6 7 8 9
offset
![Page 53: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/53.jpg)
One-Dimensional ArraySyntax:
datatype variablename [size];
Example:
int a[10];
block of 10 contiguous elements in memory.
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
aArray name (Starting address of the array)
offset
![Page 54: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/54.jpg)
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};
![Page 55: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/55.jpg)
Initialization
Example:
#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
![Page 56: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/56.jpg)
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;
![Page 57: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/57.jpg)
Input To Array
Normal Variable:
int a;
scanf(“%d”,&a);
Array Variable:
int a[20];
scanf(“%d”,&a[0]);
- - -
- - -
scanf(“%d”,&a[19]);
Array Variable:
int a[20],i;
for(i=0;i<20;i++)
{
scanf(“%d”, &a[ i ]);
}
20 lines
4 lines
Which one is best ?
Array offset
always start
with 0
![Page 58: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/58.jpg)
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); /* get the input from the keyboard (stdin buffer) */
fflush( stdin); /* clear the stdin buffer */
for(i =0; string[i] != „\0‟; i = i + 1);
printf(“The length of the string is %d \n”, i);
}
![Page 59: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/59.jpg)
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.
![Page 60: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/60.jpg)
Array Addressing
string
100
0 1 2 3 4 5 6 7 8 9 10
100 101 102 103 104 105 106 107 108 109 110
a b c d e f g h i j \0
![Page 61: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/61.jpg)
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
![Page 62: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/62.jpg)
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;
}
![Page 63: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/63.jpg)
Two-Dimensional Array
Syntax:
datatype variablename [rowsize] [columnsize];
Example:
int a[4][3];
block of 15(5*3) contiguous elements in memory.
0
0 1 2
1
2
3
Row offset
value
Column offset
valuea[0][0]
a[0][2]
1000Address
Of a[0][0]
1004
1006
?
![Page 64: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/64.jpg)
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" };
![Page 65: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/65.jpg)
Two-Dimensional ArrayInitialization
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();
}
![Page 66: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/66.jpg)
Input To 2-D Array
1-D Array:
int a[20],i;
for(i=0;i<20;i++)
{
scanf(“%d”, &a[ i ]);
}
2-D Array:
int a[10][5],i,j;
for(i=0;i<10;i++)
{
for(j=0;j<5;j++)
{
scanf(“%d”,&a[i][j]);
}
}
Increment
column index
Increment
row 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.
![Page 67: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/67.jpg)
Two-Dimensional ArrayExample:
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]);
}
}
![Page 68: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/68.jpg)
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)
{ -------
-------
}
![Page 69: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/69.jpg)
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}
![Page 70: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/70.jpg)
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
![Page 71: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/71.jpg)
Rules and Regulations
A function should follows
1.Function Declaration
2.Function call
3.Function Definition
![Page 72: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/72.jpg)
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);
}
![Page 73: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/73.jpg)
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.
For example,
argentina( )
{
statement 1 ;
statement 2 ;
statement 3 ; }
![Page 74: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/74.jpg)
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( ) ;
}
![Page 75: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/75.jpg)
A function can be called any number of times.
For example,
main( )
{
message( ) ;
message( ) ;
}
message( )
{
printf ( "\n Hai Welcome to C Language !!" ) ;
}
![Page 76: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/76.jpg)
Advantages of Functions
Divide and conquer
Manageable program development
Software reusability
Use existing functions as building blocks for new programs
Avoid code repetition
![Page 77: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/77.jpg)
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
![Page 78: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/78.jpg)
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”);
}
![Page 79: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/79.jpg)
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));
}
![Page 80: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/80.jpg)
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);
}
![Page 81: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/81.jpg)
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);
}
![Page 82: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/82.jpg)
Invoking functions
Function can be be invoked by using two ways
1.Call by value
2.call by reference
![Page 83: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/83.jpg)
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.
![Page 84: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/84.jpg)
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*/
}
![Page 85: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/85.jpg)
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.
![Page 86: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/86.jpg)
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*/
}
![Page 87: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/87.jpg)
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
![Page 88: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/88.jpg)
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 */
}
![Page 89: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/89.jpg)
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.
![Page 90: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/90.jpg)
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;
};
![Page 91: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/91.jpg)
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 */
![Page 92: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/92.jpg)
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 */
![Page 93: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/93.jpg)
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);
}
![Page 94: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/94.jpg)
Initializing of a structure
struct empdata
{
int empno;
char name[10];
char job[10];
float salary;
}emprec={101,”Arun”,”Developer”,”20000};
![Page 95: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/95.jpg)
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];
![Page 96: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/96.jpg)
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].combination,&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); }
![Page 97: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/97.jpg)
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;
![Page 98: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/98.jpg)
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.
![Page 99: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/99.jpg)
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);
![Page 100: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/100.jpg)
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.
![Page 101: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/101.jpg)
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;
![Page 102: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/102.jpg)
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);
}
![Page 103: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/103.jpg)
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();
}
![Page 104: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/104.jpg)
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;
}
![Page 105: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/105.jpg)
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
Declarationint *x;
float *f;
![Page 106: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/106.jpg)
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
![Page 107: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/107.jpg)
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
![Page 108: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/108.jpg)
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
Contents1
Contents11
Contents16
ADDR1ADDR2ADDR3ADDR4ADDR5ADDR6
***
ADDR11
**
ADDR16
![Page 109: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/109.jpg)
Syntax:
datatype * variablename;
Example:
int *a;
Indirection operator
identifier
Note: A normal variable(identifier) declared with * symbol is called
pointer variable.
Pointer variable
![Page 110: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/110.jpg)
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.
![Page 111: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/111.jpg)
Consider the statements:
#include <stdio.h>
int main ( )
{
int *aptr ; /* Declare a pointer to an int
*/
float *bptr ; /* Declare a pointer to a
float */
int a =10; /* Declare an int variable */
float b =2.5f; /* Declare a float variable */
![Page 112: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/112.jpg)
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 ;
}
1000 10
1500 2.5
aptr
bptr
1000
1500
a
b
![Page 113: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/113.jpg)
Output:
1000 1000 10 10
1500 1500 2.500000 2.500000
![Page 114: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/114.jpg)
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
![Page 115: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/115.jpg)
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.
![Page 116: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/116.jpg)
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
![Page 117: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/117.jpg)
Arithmetic Operations on Pointers
Example:
int *a;
int b=10;
a=&b;
a++;
1000
a
2.5b
1000
Before this Statement
After this Statement
a++ a=a+1
1000++ a=1000+1
a value is 1002
Integer 1=2bytes
![Page 118: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/118.jpg)
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); }
![Page 119: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/119.jpg)
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.
![Page 120: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/120.jpg)
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.
![Page 121: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/121.jpg)
File I/O in C
![Page 122: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/122.jpg)
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.
![Page 123: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/123.jpg)
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.
![Page 124: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/124.jpg)
Opening Files
Syntax:
FILE *fp;
fp=fopen(“filename”,”mode”);
The statement:
fp1 = fopen ( "mydata", "r" ) ;
would open the file mydata for input (reading).
![Page 125: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/125.jpg)
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.)
![Page 126: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/126.jpg)
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") ;
}
![Page 127: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/127.jpg)
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
![Page 128: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/128.jpg)
File operation functions in C
Function Name Operation
fopen() Creates a new file for use
Opens a new existing file for use
Fclose() Closes a file which has been opened for
use
getc() Reads a character from a file
putc() Writes a character to a file
![Page 129: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/129.jpg)
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
![Page 130: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/130.jpg)
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
File operation functions in C
![Page 131: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/131.jpg)
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); }
![Page 132: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/132.jpg)
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”);
![Page 133: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/133.jpg)
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);
}
![Page 134: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/134.jpg)
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.
![Page 135: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/135.jpg)
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-of-
file 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”);
}
![Page 136: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/136.jpg)
End of File
There are a number of ways to test for the end-of-
file 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”) ;
}
![Page 137: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/137.jpg)
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.
![Page 138: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/138.jpg)
Closing Files
The statements:
fclose ( fptr1 ) ;
fclose ( fptr2 ) ;
will close the files and release the file descriptor
space and I/O buffer memory.
![Page 139: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/139.jpg)
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) ;
![Page 140: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/140.jpg)
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
![Page 141: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/141.jpg)
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.
![Page 142: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/142.jpg)
ftell() & rewind()
Ftell();
FILE *stream;
long ftell (stream);
Rewind():
FILE *stream;
void rewind (stream);
![Page 143: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/143.jpg)
Pre Processing
in
C
![Page 144: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/144.jpg)
Pre Processing
Refers before compiling the c program.
Loads the template before compiling.
Syntax
#Macro Template Macro Expansion
![Page 145: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/145.jpg)
Types of Macros
Defining Macros
File Inclusion
Conditional Macros
Special cases
![Page 146: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/146.jpg)
Defining Macros
#define <Label>(parameterlist)<Expansion>
main()
{
……………
…….
<Label>
}
![Page 147: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/147.jpg)
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;
}
![Page 148: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/148.jpg)
File Inclusion
#include<file name>
(or) #include ”filename”
main()
{
…..
…..
}
![Page 149: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/149.jpg)
Conditional Macros
Syntax:
#ifdef MACRO
controlled text
#endif /* MACRO */
Syntax:
# if expression
controlled text
# endif /* expression */
![Page 150: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/150.jpg)
Conditional Macros
Syntax:#if expression
text-if-true
#else /* Not expression */
text-if-false
#endif /* Not expression */
![Page 151: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/151.jpg)
Example for elif
Example:
#if X == 1
...
#elif X == 2
...
#else /* X != 2 and X != 1*/
...
#endif /* X != 2 and X != 1*/
![Page 152: Complete C Slides](https://reader031.vdocuments.pub/reader031/viewer/2022020217/5527c7b0550346dc358b48e5/html5/thumbnails/152.jpg)
Thank You….