C Language PDF
C Language PDF
C Language PDF
Overview
Lecture 1-2
Character set, Variables and Identifiers, Built-in Data
Types, Variable Definition ,Expressions,Constants and
Literals ,Simple assignment statement, Basic input/output
statement, Simple C Programs
C Programming Language
• What is C?
– C is a structured, relatively low-level, portable
programming language.
• Why study C?
– Many popular software tools are written in C.
– Has strongly influenced many other languages.
• C-shell, java, C++, Perl, etc.
– Forces the user to understand fundamental aspects of
programming.
– Very concise language.
History of C
• C
– Evolved by Ritchie from two previous
programming languages, BCPL and B
– Used to develop UNIX
– Used to write modern operating systems
• Hardware independent (portable)
– By late 1970's C had evolved to "traditional C"
C, cont.
• Is C object-oriented?
– No. C++ (its successor) is.
• Can a non OO language be useful?
– Yes.
• Is C a hard language to learn?
– No, but it does take a little getting used to.
• What is the ANSI part?
– American national standards institute – uniform
standard definition of C for portability.
A Hello World Program
/*The first program.*/ Result is :
Hello,world!
#include <stdio.h>
int main(void) //main function
{
printf(“Hello, world!\n”);
return 0;
}
Terms
• Source code
– Text of a program.
– The input to the C compiler.
• Object code
– Translation of the source code of a program into
machine code.
– The input to the linker.
• Linker
– A program that links separately compiled modules
into one program.
– The output is an executable program.
Terms (cont.)
• Library
– The file containing the standard functions that
a program can use.
• Complier time
– The time during which a program is being
compiled.
• Run time
– The time during which a program is executing.
Language Types
• Three types of programming languages
1. Machine languages
• Strings of numbers giving machine specific
instructions
• Example:
+1300042774
+1400593419
+1200274027
2. Assembly languages
• English-like abbreviations representing elementary
computer operations (translated via assemblers)
• Example:
Load BASEPAY
Add overpay
Store GROSSPAY
Language Types, Cont.
3. High-level languages
• Codes similar to everyday English
• Use mathematical notations (translated via
compilers)
• Example:
grossPay = basePay +
overTimePay
High-level Languages
• “high-level” is a relative term
• C is a relatively low-level high-level language
• Pascal, Fortran, COBOL are typical high-level
languages
• Java, Python, Perl, VB are examples of high-level
high-level languages
• Application specific languages (Matlab,
Javascript, VBScript) are even higher-level.
What is Data types in C
• A Data type is a collection of values with
shared properties
• Using types makes a program easier to read
and understand
• Using types makes it easier for the compiler
• Types makes it easier to detect certain
programming errors
Data types Contd……
• Each variable has a type and a value
– The type determines the meaning of the operations that can
be applied to the value
int i,j;
double d;
float x;
determine the operations and space requirements of the
variables
• The data type of every variable must be declared before that
particular variable can appear in a statement
Data types Contd….
• Four basic types
– char – a single byte capable of holding just one
character
– int – an integer
– float – single-precision floating point
– double – double precision floating point
• No boolean type in C
– True and false are represented by 1 and 0
Fundamental Data Types
char signed char unsigned char
a+u=22, b+u=-14
Integer overflow
• At run-time a variable may be assigned an
incorrect value. If a value is greater than the
maximum value which can be stored in a
variable of type int, we get integer overflow
Floating points
• A real or floating point number has an integral part
and a fractional part, separated by a decimal point,
e.g. 0.02, 170.234, 3e+5
• Floating point numbers can be either positive or
negative – always signed in C
• 3 floating types in ANSI C:
– float, double, long double
• The working floating type in C is double, not float
Floating points contd….
• The type float denotes normal precision real
numbers
• Single precision floating point numbers are
declared
float variable_name;
Floating points contd….
• The type double denotes double precision
real numbers
• Double precision floating point numbers are
declared
double variable_name;
Floating points contd….
• The possible values assigned to a floating
type are described in terms of attributes
called precision and range
– The number of significant decimal places that a
floating value carries is called precision
– The limits of the largest and smallest positive
floating point values that can be represented in
a variable of that type is called range
Lexical Elements of the C Language
– Keywords.
– Identifiers.
– Constants.
– String constants.
– Operators.
– Punctuators.
Keywords
• Reserved words.
• Cannot be redefined or used in other
contexts.
• Case sensitive.
• Have a special predefined meaning.
Reserved Words (Keywords) in C
int long
• auto break register return
• case char short signed
• const continue sizeof static
• default do struct switch
• double else
typedef union
• enum extern
unsigned void
• float for
volatile while
• goto if
Constants
• They refer to fixed values that the program
may not alter.
• They can be of any of the basic data types.
Integer: 1. Decimal 0, 77
23.7
.16
1.604
2e3
H e l l o ! \0
“A” is actually A followed by the null character
„\0‟.
String Constants (cont.)
“a string of text”
“ a = b + c; ” // nothing is executed
Punctuators
• They are located by the compiler as tokens and
are used to separate language elements.
Parentheses ( ) Braces {}
Commas , Semicolons ;
int main(void)
{
int a, b=3, c=6;
a = 17 * (b + c);
…
}
Comments
• Multi-Line comments: /* this is a multiline
comment */
x=a+b
z + 2 = 3(y - 5)
• Remember that variables in algebra are
represented by a single alphabetic character.
Naming Variables
• Variables in C may be given representations
containing multiple characters. But there are
rules for these representations.
• Variable names in C
– May only consist of letters, digits, and underscores
– May be as long as you like, but only the first 31
characters are significant
– May not begin with a number
– May not be a C reserved word (keyword)
Naming Conventions
• C programmers generally agree on the following
conventions for naming variables.
– Begin variable names with lowercase letters
– Use meaningful identifiers
– Separate “words” within identifiers with underscores
or mixed upper and lower case.
– Examples: surfaceArea surface_Area
surface_area
Case Sensitivity
• C is case sensitive
– It matters whether an identifier, such as a variable
name, is uppercase or lowercase.
– Example:
area
Area
AREA
ArEa
are all seen as different variables by the compiler.
Declaring Variables
• Before using a variable, you must give the
compiler some information about the
variable; i.e., you must declare it.
• The declaration statement includes the
data type of the variable.
• Examples of variable declarations:
int balls ;
float area ;
Declaring Variables (con‟t)
• When we declare a variable
– Space is set aside in memory to hold a value of the
specified data type
– That space is associated with the variable name
– That space is associated with a unique address
• Visualization of the declaration
int balls ; balls
garbage
More About Variables
C has three basic predefined data types:
• Integers (whole numbers)
– int, long int, short int, unsigned int
• Floating point (real numbers)
– float, double
• Characters
– char
Using Variables: Initialization
• Variables may be be given initial values, or
initialized, when declared. Examples:
length
int length = 7 ; 7
diameter
initial
–
–
–
Example: Declarations and Assignments
(cont‟d)
–
–
–
printf (“Its depth at sea: \n”) ;
printf (“ %d fathoms \n”, fathoms) ;
printf (“ %d feet \n”, feet) ;
printf (“ %d inches \n”, inches) ;
return 0 ;
}
Input and Output Using stdio.h
• printf
– Provides formatted input and output
– Input for printf is a format specification followed
by a list of variable names to be displayed
– printf(“variable %d is %f\n”, myint, myfloat);
• scanf
– Provided an input format and a list of variables
– scanf(“%d”, &myint);
Escape characters
Escape Description
Sequenc
e
\n Newline, position cursor at the start of a new
line
\t Horizontal tab, move cursor to the next tab
stop
\r Carriage return. Position cursor to the
beginning of the current line; do not
advance to the next line.
\a Alert, sound system warning beep
\\ Backslash, print a backslash character in a
printf statement
\” Double quote print a double quote character
in a printf statement.
Format Specifiers for printf and scanf
Data Type Printf specifier Scanf specifier
long double %Lf %Lf
double %f %lf
float %f %f
unsigned long %lu %lu
int
long int %ld %ld
unsigned int %u %u
int %d %d
short %hd %hd
char %c %c
A simple C Program that reads in two
numbers,stores them and prints out the sum
main()
{
int x,y; /* places to store numbers */
printf("Enter x ");
scanf("%d",&x);
printf("Enter y ");
scanf("%d",&y);
printf("The sum of x and y was %d\n",x+y);
}
C Program Read string and show output.
#include <stdio.h>
int main(void)
{
char str[80];
printf("Enter a string: ");
scanf(''%s", str);
printf("Here's your string: %s", str);
return 0;}
How to read characters
• You can read char values with the scanf
function
• C provides a function called getchar()
which allows you to read characters one at a
time from a line of input.
getchar()
• Function contained in stdio.h
• getchar() returns an int code for a character
typed on the standard input (the keyboard)
char c;
c = getchar() ;
How to print a char
• Can use printf with a format control string of %c.
• For example,
printf( “The character is %c\n”, c );
• Can use another function in stdio.h called
putchar()
• For example,
putchar( c ) ;
putchar()
• Prints a character to the standard output
(screen)
• Is a function also referenced in stdio.h
Using getchar() example
#include <stdio.h>
int main()
{char c; /* declare character variable */
/* read a character and store it in c */
c = getchar() ;
/* print it twice, two different ways */
printf("%c\n", c );
putchar( c ) ;/* one character at a time so here‟s the
newline */
c = '\n' ;
putchar( c );} /* end program */
Field Width Specification
c) The symbols _____ and ______ mark the beginning and end
of a comment.
Part B
• Special Operators
Arithmetic Operators
Operator Action
– Subtraction, also unary minus
+ Addition
* Multiplication
/ Division
% Modulus
-- Decrement
++ Increment
Precedence and Associativity
• Precedence of the Arithmetic operators:
High ++ --
- (unary minus)
* / %
Low + -
-a*b–c ((- a) * b) – c
• Expressions inside parentheses are evaluated
first.
1 * (2 - 3)
1 + 2 + 3 + 4 –5
(((1 + 2) + 3) + 4) –5
Increment & Decrement Operators
• Provide a concise notation for incrementing or
decrementing a variable by 1.
Are unary operators.
• ++x or x++ --x or x--
x = x + 1;
int i = 3, j = 2, k;
i++; i 4
j = ++i; j 5 i 5
k = i++; k 5 i 6
k = (--j+3) k 7 j 4
l = 4;
n = 3;
m = 2;
x = l * n + m++; x 14
int b = 2, d = 4;
7--b*++d 7-((-
b)*(++d)) ?
int j = 2, k = 3, m = 4;
j*=k=m+5
j=(j*(k=(m+5))) ?
int a,b;
a = 1;
b = 12;
Logical Operators:
Operator Action
&& AND
|| OR
! NOT
Precedence and Associativity
High !
> >= < <=
= = !=
&&
Low ||
5 && 3 ?
int i, j = 1;
1) (i=2) i 2
2) && j 1 && 2
true && true 1
3) = j 1
j 1 i 2
j = j && (i = = 3); ( ) not needed
1) (i = = 3) false 0
2) && j 1 && 0 0
3) = j 0
j 0 i 2
1) (i/2) (2/2) 1
2) || j 0 || 1 true 1
3) = j 1
j 1 i 2
j = !j && (i = i + 1);
1) i+1 3
2) = i 3
3) ! !j !1 0
4) && 0 && 3
5) = j 0
The Comma Operator
Lowest precedence of all the operators.
Causes a sequence of operations, “do this
and this and this…”.
Is a binary operator.
expression_1, expression_2
Associates left to right.
int i = 2;
j = 4;
j = i++, i - j;
*i 3
*j -1 (3-4)
• It allows multiple initializations and
multiple processing of indices.
will output?
3rd expression in the for statement is a comma
expression.
int main(void)
{
char s[80];
s[3] = 'X';
printf(''%c", s[3]);
return 0;
}
The Conditional Operator
?
• Ternary operator.
• A powerful and convenient operator that
replaces certain statements of the if-then-
else form.
Exp1 ? Exp2: Exp3
x = 10;
x = 10;
y = x>9 ? 100 : 200; if(x>9)
y = 100;
else
y = 200;
( ) not needed
int i, h, j = 2;
k get max of I
k = (i>j) ? i:j; or j
This statement does what?
; /* an NULL statement */
Null Statement: ; [A semi-colon
alone by itself].
e) a = 5;
while(a--) printf("hello");
• General form:
if (expression) statement;
else
if (expression) statement;
else
if (expression) statement;
.
.
.
else statement;
• The conditions are evaluated from the top
downward.
• As soon as a true condition is found, the
statement associated with it is executed and the
rest of the ladder is bypassed.
x = 10;
x = 10;
y = x>9 ? 100 : 200; if(x>9)
y = 100;
else
y = 200;
#include <stdio.h>
int f1(int n);
int f2(void);
int main(void)
{
int t;
printf("Enter a number: ");
scanf("%d", &t);
t ? f1(t) + f2() : printf("zero entered.");
printf("\n");
return 0;
}
/* Divide the first number by the second. */
#include <stdio.h>
int main(void)
{
int a, b;
printf("Enter two numbers: ");
scanf(''%d%d", &a, &b);
if(b) printf("%d\n", a/b); if(b != 0) printf("%d\n", a/b);
else printf("Cannot divide by zero.\n");
return 0;
}
switch statement
• switch is a multiple-branch selection
statement, which successively tests the
value of an expression against a list of
integer or character constants (floating
point expression, for example, are not
allowed).
void menu(void)
{
char ch;
case '2':
correct_errors ();
break;
case '3':
display_errors ();
break;
default :
printf("No option selected");
}
}
int flag, k; /* Assume k is initialized */
•The break inside flag = -1;
the switch is
switch(k) {
optional. case 1: /* These cases have common */
case 2: /* statement sequences. */
•If the break is case 3:
omitted, flag = 0;
execution will break;
case 4:
continue on into
flag = 1;
the next case until case 5:
either a break or error(flag);
the end of the break;
switch is reached. default:
process(k);
}
Calculates the range of marks a student has scored
Int calculate_marks (char grade)
{ switch (grade)
{ case `S‟:
printf (“Marks between 91-100”); break;
case `A‟:
printf (“Marks between 81-90”); break;
case `B‟:
printf (“Marks between 71-80”); break;
case `C‟:
printf (“Marks between 61-70”); break;
case `P‟:
printf (“Marks less than 50”); break;
default:
printf (“Invalid grade”); break; }}
Nested Switch
• You can have a switch as a part of the
statement sequence of an outer switch.
int main(void)
{
int x;
for(x=1; x <= 100; x++)
printf("%d ", x);
return 0;
}
for(x=100; x != 65; x -= 5)
{
z = x*x;
printf(''The square of %d, %d", x, z);
}
The Elements of the For-loop
• The initialization, testing and
incrementation can be any valid C
expression.
for( ; ; ) {
•Terminate ch = getchar(); /* get a character */
the infinite if(ch == 'A') break; /* exit the loop */
}
loop printf("you typed an A");
For Loops With No Bodies
• A loop body may be empty.
• Execution:
– Check the test condition at the top of the loop.
– The loop iterates while the condition is true.
– When the condition becomes false, program control
passes to the line of code immediately following the
loop.
Example
char wait_for_char(void)
{
char ch;
ch = '\0'; /* initialize ch */
while(ch != 'A') ch = getchar();
return ch;
}
while((ch=getchar()) != 'A') ;
Example 2:
void func1()
{
int working;
working = 1; /* i.e., true */
while (working) {
working = process1();
if (working)
working = process2();
if (working)
working = process3();
}
}
For loop Vs While Loop
A-(Assignment), T-(testing), I-(Increment)
A;
for (A; T; I)
While (T)
{
{
Body;
} Body;
I;
}
NESTED LOOPS
Nested 1 loop syntax coded inside another
Loop syntax.
main()
{ int cnt = 0, j , k , m,n;
n=7;
for(j = 0; j <= N; ++j)
for( k = 0; k <= N; ++k)
for( m = 0: m <= N; ++m)
if ( j + k + m == N) {
++cnt;
printf(“%d%d%d”, j , k , m);
}
printf(“\n Count: %d\n”, cnt);
}
How many times will “if” be executed?
8 * 8 * 8 = 512
do-while Loop
• General form:
do {
statement;
} while(condition);
• Execution:
– Always executes at least once.
– Iterates until condition becomes false.
do {
scanf(''%d", &num);
} while(num > 100);
•The most common use of the do-while
loop is in a menu selection function.
void menu(void)
{
char ch;
putchar(ch+1);
}}
Exercise
What will be displayed in each of the following :
a) a = 7;
b = a++;
printf ("%d", b);
b) a = 7
b = ++a;
printf ("%d", b);
c) a = 5;
while(a)
{
printf("Hello");
a--;
}
• Exercise Contd……..
d) a = 5;
while(--a) printf("hello");
e) a = 5;
while(a--) printf("hello");
2.Write a program that converts each lower-case
character in the standard input to uppercase and
each uppercase character to lower case. Pass all other
characters unchanged.
3. Write a program that reads nos. from the standard
input and prints the largest
value entered, the smallest value, the sum of all
values read and the mean of all values inputted.
Question
Write a program that prints the number of occurrences of the
character ! in the
standard input.
• What is an "array"?
• A way to collect together data of a single
type in a single object
• A linear sequence of data objects e.g.
– array of ints
– array of chars (string)
Creating and using arrays
• One-dimensional array of three ints:
• int arr[3];
int sum;
arr[0] = 1;
arr[1] = 22;
arr[2] = -35;
sum = arr[0] + arr[1] + arr[2];
One-dimensional arrays (1)
• Arrays can be
– initialized
– partially initialized
– not initialized
• Uninitialized space contains?
– "garbage"
One-dimensional arrays (2)
• Examples:
int my_array[10];
/* not initialized */
int my_array[5] = { 1, 2, 3, 4, 5 };
/* initialized */
int my_array[] = { 1, 2, 3, 4, 5 };
/* OK, initialized */
int my_array[4] = { 1, 2, 3, 4, 5 };
/* warning */
int my_array[10] = { 1, 2, 3, 4, 5 };
/* OK, partially initialized */
One-dimensional arrays (3)
int i;
int my_array[10];
for (i = 0; i < 10; i++) {
my_array[i] = 2 * i;
}
Usually the best approach
One-dimensional arrays (5)
int arr[2][3];
/* initialize... */
/* arr[0] is array of 3 ints */
/* arr[1] is another array of 3 ints */
Two-dimensional arrays (4)
• Picture of arr:
1 23 -12 arr[0]
85 46 99 arr[1]
Two-dimensional arrays (5)
int arr[2][]
= { { 1, 2, 3 }, { 4, 5, 6 } };
/* invalid */
int arr[][]
= { { 1, 2, 3 }, { 4, 5, 6 } };
/* invalid */
int arr[][3]
= { { 1, 2, 3 }, { 4, 5, 6 } };
/* OK */
Two-dimensional arrays (7)
int my_array[][3]
= { 1, 2, 3, 4, 5, 6 };
/* warning with -Wall */
int my_array[][3]
= { { 1, 2, 3 }, { 4, 5 } };
/* OK; missing value = 0 */
char w[MAXWORD];
w[0] = „A‟;
w[1] = „\0‟;
/*….*/
• When declaring a character array that
will hold a string, you need to declare it
to be one character longer than the
largest string that it will hold.
• WHY?
char str[11];
String Initialization
• General form:
char array_name[size] = “string”;
char str[9] = {'I', ' ', 'l', 'i', 'k', 'e',' ', 'C', '\0'};
if(!strcmp(s1, s2))
printf("The strings are equal\n");
strcat(s1, s2); hellohello
printf (''%s\n", s1); This is a test
e is in hello
found hi
strcpy(s1, "This is a test.\n");
printf(s1);
General form:
IF re-enter the
Block? _________
Memory is reallocated.
Call by Reference with Auto
Parameters
1) When the block is suspended, such as when it
calls another function,the variable is suspended
but can still be accessed and changed(e.g.
actual argument in a func call).
register int i ;
for (i = d, i <LIMIT, ++i){
…
}
register i ;
Static Storage Class
A static variable can be defined inside a
block(local) or in the global area of the
program. Its characteristics differ slightly
depending on where it is defined.
Local Static Variables
Static variable is defined inside a block:
void f(int a)
{
…….. /* g() is available here,
} but not in other files */
int main(void)
{
sp_to_dash("this is a test");
return 0;
}
a) #include <stdio.h>
main()
{
int i = 3;
{
int i = 5;
printf("%d\n", i);
}
printf("%d\n", i);
}
Functions and Structured
Programming
Lecture 10-13
Structured Programming
• Structured programming is a problem-solving
strategy and a programming methodology.
– The construction of a program should embody top-
down design of the overall problem into finite
subtasks.
– Function types
– Function variables
– Function arguments
– Function scopes
– Return values
– Function prototypes
– Recursion
General syntax:
– Inside functions:
local variables
if(t==l) {
char s[80]; /* this is created only upon
entry into this block */
/* do something . . . */
}
– Call by Value.
– Call by Reference.
Call by Value
* When an Argument (variable, constant, or
expression) is passed to a matching parameter
(declared in Function Heading), A Copy of the
Argument is made and is passed to the
parameter.
Arguments Parameters
in calling in called
Module. Module.
* Changes made to the parameter have no effect on
the argument. i.e., the parameter is implemented
as a local variable which is initialized to the value
passed from the Argument.
Call by Reference
• It is often convenient to have functions modify
the values of the variables referred to in the
Argument list.
int main(void)
{
int t=10;
printf("%d %d", sqr(t), t);
return 0;
}
int sqr(int t)
{
t = t*t;
return t;
}
Placement of Functions:
Before the compiler sees a call to a function
it wants to know the Number and Type of
its Parameters and the type of the Return
Value of the Function.
int main(void) {
int test1, test2, test3;
double avg;
scanf(“%d%d%d%d”, &test1, &test2, &test3);
avg = average(test1, test2, test3);
printf(“ The average is: %f”‟, avg);
}
/* This function returns the average of 3 exam
scores which are passed call-by-value. */
x = power(y);
for(ch=getchar(); isdigit(ch); ) . . . ;
The exit( ) Function
• General form
void exit(int return_code);
#include <stdlib.h>
int main(void)
{
if(!virtual_graphics()) exit(1);
play();
...
}
Exercise
Fill in the blanks
• The region where a variable name can be used is called the
_______ of the variable.
• The variables declared inside a function or blocks have
______ scope.
• The three kinds of score are ____, _______ and ________.
• ________ and _______ variables have block scope by
default.
• Auto variable cannot be _______ variables.
• Functions have _________ scope.
• Functions have _______ scope.
• Labels have _____ scope.
• Variable declared outside a block have _______ scope.
• Function declaration should be done ______ a function
call.
Exercise Contd…. (true/false)
• Function scope can be told as a form of block scope.
• Allocated memory in a block is automatically released
before the block ends.
• Variables with the same name in different block use the
same memory locations.
• Block variables can be global variables also.
• File scope variables can be accessed by all functions in the
file.
• File scope variables can be local variables also.
• It is possible to jump out of functions using labels.
• Using global variables allows sharing of data between
functions.
• Using global variables increased the structural organization
of a program.
• It is must to declare functions before they are used.
Exercise contd…..
#include <stdio.h>
main()
{
printf("hello");
main();
}
2 + 4 + 6 + _ _ _ _ + 2n
Dereference Operator: *
m = &count;
m receives the address of count.
m count
100
* Operator
* is the complement of &. It is a unary
operator that returns the value located at
the address that follows.
* “at address”
q = *m;
q receives the value at address m. ?
#include <stdio.h>
int main(void)
{
Put the int target, source=10;
value 10 int *m;
into a m = &source;
variable target = *m;
called target. printf("%d", target);
return 0;
}
Pointer Assignments
• You can use a pointer variable on the
right-hand side of an assignment statement
to assign its value to another pointer.
main( )
{ int i = 777, *p = &i;
printf (“value of i:%d\n”, *p);
printf (“Addr of i:%u or %p\n”, p, p);
}
Output Value of i: 777
Address of i: 234880259 or dfffcfc
1 ? ?
i:10 j:20 k:30
1. j = &i;
1 10 ?
i:10 j:20 k:30
2. *j = 2;
1 2 10 ?
i:10 j:20 k:30
Stores 2 at the memory location pointed to by j.
3. i = *j + 1;
12 3 10 ?
i:10 j:20 k:30
3 10 10
i:10 j:20 k:30
output: 3
Example 2
int a=42, b=53, *p1, *p2;
p1 = &a;
p2 = p1;
p2 = &b;
p2 9 p2 9
*p1 = *p2;
before after
p1 8 p1 9
p2 9 p2 9
Example 4
# include <stdio.h>
main( )
{
int j, i, *intptr;
scanf(“%d%d”, &i, &,j);
intptr = i > j ? &i:&j;
printf(“%d\n”, *intptr);
}
Address of the larger var is stored in ? :
then the larger number is output.
Example 5
int a=3,b=7,*p; p = &b;
3 7
a b p
*p=2**p–a;
1) 2 * *p 2*7
2) 14 – 3 11
11
3) Which is assigned? b
Pointer Initialization
int i, *p = &i; correct
p = (int *) 1307;
cast to pointer to int.
1307 is an absolute address in
memory.
int i = 3, j = 5, *p = &i, *q = &j, *r;
double x;
r
3 5 ?
i:10 j
p:50 q ? x
i:10 p:5
4) 7 * *p / *q + 7 i:10 j
3 5
Dereference Right to Left p q
1. *q 5
2. *p 3
3. 7 * 3 [21]
4. 21/5 4
5 4 + 7 11
5) *(r = &j) *= *p
4 2 1 5 3 j - int var
p - pointer to int
j i r - pointer to int
5 3
r p
1. &j - Address of j 1
2. r = 1 r points to j
3. *p contents of thing
pointed to by p i.e., 3
4. *( ) Location pointed to by r, i.e., j.
5. *= *r *= *p; *r = *r * *p;
Pointer Arithmetic
int *v=(int *)100; Byte Address.
100 v
102 v+1
104 v+2
106 v+3
108 v+4
assume int
are 2 bytes long.
Pointer Arithmetic (cont.)
return 0;
}
void swap(int *x, int *y)
{
int temp;
Name 30 bytes
Street 40 bytes
City 20 bytes
State 3 bytes
Zip 4 bytes
Assume 4-byte long integers
You can declare one or more
objects when declare a struct type
struct addr {
char name[30];
char street[40];
char city[20];
char state[3];
unsigned long int zip;
} addr_info, binfo, cinfo;
Initialization of Structures
• General form:
object-name.member-name
e.g., addr_info.zip = 12345;
printf("%lu", addr_info.zip);
gets(addr_info.name);
printf("%d", y.a);
return 0;
}
Array of Structures
WHY?
printf("%lu", addr_list[2].zip);
addr_list[2].name[0] = 'X';
Passing Structures to Functions
#include <stdio.h>
struct Example_type {
int a, b;
char ch;
};
void f1(struct Example_type parm);
int main(void)
{
struct Example_type arg;
arg.a = 1000;
f1(arg);
return 0; struct_type
} must match
void f1(struct Example_type parm)
{
printf(''%d", parm.a);
}
In Header File: cl_info.h
p = &person;
The Structure Pointer Operator
–>
Used to access the members of a structure via a
pointer.
p–>balance
Forms:
(*pointer-To-Struct). member
or
pointer-To-Struct member
struct student temp, *p = &temp;
temp.grade = „A‟;
temp.last_name = “Bushker”;
temp.student_id = 590017;
struct student {
char *last_name;
int student_id;
char grade;
};
Expression Equivalent Value
(*p).student_id 590017
Parenthesis are necessary
(dot) has higher priority than *
Arrays and Structures Within
Structures
Structure y.
y.a[3][7]
Structures within Structures
struct emp {
struct addr address; /* nested structure */
float wage;
} worker;
worker.address.zip = 93456;
Using sizeof to Ensure Portability
Type Size in Bytes struct s {
char 1 char ch;
int 4 int i;
double 8 double f;
} s_var;
sizeof(s_var) is 13 (8+4+1).
struct s *p;
p = malloc(sizeof(struct s));
typedef
• You can define new data type names by using
the keyword typedef
BALANCE over_due;
E.g., The declaration for an array of
pointers to strings.
Char * stringPtrAry[20];
STRING StrPtrAry[20];
Typedef with Structures
typedef struct
{ char id[10];
char name[26];
int gradepts;
} STUDENT; A typename not
a variable.
STUDENT pupil;
• General form:
• General form:
do {
ch = getc(fp);
} while(ch!=EOF);
/* KTOD: A key to disk program. */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{ KTOD TEST
FILE *fp; Reads characters from the
char ch; keyboard and writes them to a
disk file until the user types a
if(argc!=2) { dollar sign.
printf(''You forgot to enter the filename.\n");
exit(1);
}
if((fp=fopen(argv[1], "w"))==NULL) {
printf(''Cannot open file.\n");
exit (1);
}
do {
ch = getchar();
putc(ch, fp);
} while (ch != '$');
fclose(fp);
return 0;
}
feof( )
• General form:
int feof(FILE *fp);
while(!feof(fp)) ch = getc(fp);
Working with Strings
• fputs( )
• General form:
• General form:
• General form:
gets(str);
if(toupper(*str)= ='Y')
if(remove(argv[1])) {
printf("Cannot erase file.\n");
exit(1);
}
return 0;
if((fp=fopen("test","r")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
return 0;
}
Questions
Suppose that the file data.dat is
ABCDEFGHIJKLMNOPQRSTUVWXYZ
What is printed ?
#include <stidio.h>
main()
{
char 1;
FILE *fp;
fp = fopen (“data.dat”, “rb”);
1 = getc (fp);
printf(“%c\n”, 1)
fseek (fp, OL, 2);
if (( 1 = getc(f[)) = = EOF)
printf(„ EOF \n);
else
pintf(“%c\n”, 1);
fseek(fp, -5L, 2);
1 = getc (fp);
printf(“%c”, 1);
}
LINKED LIST
LINKED LIST
DATA STRUCTURE
• A Linked List is an ordered collection of data in
which each element contains 2 parts: data and
link.
typedef struct
{ KEY_TYPE key;
… /* other data fields */
} DATA;