You are on page 1of 129

C Programming Basics

• Introduction to C
• Data types in C
• Variables
• Type conversions
• Standard input/output
• Arithmetic, relational, logical operators
• Header files and libraries
• Loops and decisions
• Scope of variables
• Strings
• Functions, call by value, call by reference
• Arrays
• Structures
• Unions
• Pointers
• Files
History of C-Language
 Developed by Dennis M.Ritchie and Brian
Kernighan of AT&T Bell Labs in 1972
 In 1983 the American National Standards Institute
began the standardisation process

 In 1989 the International Standards Organisation


continued the standardisation process

 In 1990 a standard was finalised, known simply as


“Standard C”
Why teach C?
 C is small (only 32 keywords).
 C is common (lots of C code about).
 C is stable (the language doesn’t change much).
 C is quick running.
 C is the basis for many other languages (Java, C++, awk,
Perl).
 It may not feel like it but C is one of the easiest
languages to learn.
 NOTE: Obviously programmers will find this course easier
than everyone else. BUT, this course is for non-
programmers. If you cannot understand what I say,
please please ask me either in the lecture or afterwards.
Why use C?
 C is not "safe"
– It assumes you know what you're doing
– It has a lot of scope for bugs

 It's a good systems programming language


– Not much is hidden
– Faster than Java, more predictable performance
– It has all the low-level operations
C-Language
Strengths:
1. Efficiency
2. Portability
3. Power
4. Flexibility
5. Standard library
6. Integration with UNIX
Weaknesses:
1. C programs can be error-prone
2. C programs can be difficult to understand
3. C programs can be difficult to modify
The Benefits And Pitfalls Of C
 Benefits
 It’s a powerful language (doesn’t restrict you)
 Fast
 A practical language (real applications)

 Pitfalls
 It’s a powerful language (No programmer fail-
safes)
 Compiled code is not portable
Structured Programming
 C, Pascal, Fortran are procedural programming languages.
 A program in a procedural language is a list of instructions,
augmented with loops and branches.
 For small programs no other organizational principle
(paradigm) is needed.
 Larger programs are broken down into smaller units.
 A procedural program is divided into functions, such that
ideally each has clearly defined purpose and interface to
other functions.
 The idea of breaking a program into functions can be
further extended by grouping functions that perform
similar tasks into modules.
 Dividing a program into functions and modules is the key
idea of structured programming.
Compiling and Linking
1. Preprocessing. The program is first given to a preprocessor,
which obeys commands that begin with # (known as directives).
#include <stdio.h> (include the info in <stdio.h> before compiling)

2. Compiling. The modified program now goes to a compiler,


which translates it into machine instructions (object code).

3. Linking. A linker combines the object code produced by the


compiler with any additional code needed to yield a complete
executable program.

test.c ---> (compiled) ---> test.obj (linked) ---> executable file


Some programmer jargon
– Source code: The stuff you type into the computer. The
program you are writing.
– Compile (build): Taking source code and making a program
that the computer can understand.
– Executable: The compiled program that the computer can run.

– Language: (Special sense) The core part of C central to writing


C code.
– Library: Added functions for C programming which are bolted on
to do certain tasks.
– Header file: Files ending in .h which are included at the start of
source code.
Contd….
 Compiler:
– Translates program written in "source"
language to "target" language
 Interpreter:
– Translate and immediately execute
 Assembler:
– Translate into machine language for
particular machine
 Macro Processor:
– Textual substitutions
Keywords
In Standard C, the keywords in Table 2.1 have special significance
to the compiler and therefore can not be used as identifiers.

Table 2.1 - Keywords

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 goto sizeof volatile
do if static while
The Format of C
 Statements are terminated with semicolons
 Indentation is ignored by the compiler
 C is case sensitive - all keywords and Standard
Library functions are lowercase
 Strings are placed in double quotes
 Newlines are handled via \n
 Programs are capable of flagging success or
error, those forgetting to do so have one or
other chosen randomly!
Variables
 Variables must be declared before use immediately
after “{”
 Valid characters are letters, digits and “_”
 First character cannot be a digit
 31 characters recognised for local variables (more
can be used, but are ignored)
 Some implementations recognise only 6 characters
in global variables (and function names)!
 Upper and lower case letters are distinct
printf and scanf
 printf writes integer values to screen when
%i is used
 scanf reads integer values from the
keyboard when %i is used
 “&” VERY important with scanf (required to
change the parameter, this will be
investigated later) - absence will make
program very ill
 “&” not necessary with printf because
current value of parameter is used
The Basic Structure Of A C Program
example_program.c
/* Program documentation */
#Preprocessor directives

Global constants

Global variables

Function prototypes
int
main ()
{
Local variables
}
Function definitions
Hello World Program
#include <stdio.h> // input-output library
int main() // function main
{
printf(”Hello World\n”); // send string to standard output
return 0;
}

 Compile the source file helloworld.c with the command


gcc helloworld.c –o helloworld
Hello World Program
#include <stdio.h>
 includes the standard I/O library which allows you to read from the
keyboard (standard in) and write to the screen (standard out)

int main()
 declares the main function. Every C-program must have a function
named main somewhere in the code
{ ... }
 The symbols { and } mark the beginning and end of a block of code.

printf(”Hello World\n”)
 Sends output to the screen. The portion in quotes ”...” is the format
strings and describes how the data is formatted.
return 0;
 This causes the function main to return an error code of 0 (no error)
to the shell that started the program.
Compilation & Linking
header file
source file stdio.h
helloworld.c
#include <stdio.h>

compiler

object file helloworld.o


linker

executable file
helloworld
Variable Declaration
int b;
double x;
unsigned int a;
char c;
 C is a typed language that means a variable has a
– name
– type
 C standard types
– int, double, char, float, short, long, long double
– unsigned char, unsigned short, unsigned int,
unsigned long
Primitive Data-Types
• integer data-types :
char, short, int, long, unsigned char, unsigned short,…
• floating point data-types :
float, double, long double
• character data-type :
char
character constants in single quotes : ’a’, ’\n’
Primitive Data-Types
Type Low High Digits of Bytes
Precision
char -128 127 - 1
short -32768 32767 - 2
int -2147483648 2147483647 - 2
long -2147483648 2147483647 - 4
float 3.4x10-38 3.4x1038 7 4
double 1.7x10-308 1.7x10308 15 8
long 3.4x10-4932 3.4x104932 19 10
double
Variable Definitions
• A declaration introduces a variable’s name into a
program and specifies its type
• A definition is a declaration which also sets asides
memory for that variable (which is usually the case)
• In C it is possible to initialize a variable at the same
time it is defined, in the same way one assigns a value
to an already defined variable.
• Examples of variable definitions:
int a;
double x = 5.9;
char answer = ’n’;
double y=x;
Constants
• constants can be specified using the preprocessor
directive #define
example:
#define PI 3.14159
• the preprocessor replaces the identifier PI by the text
3.14159 throughout the program
• the major drawback of #define is that the data type of
the constant is not specified
• the preprocessor merely replaces all occurences of the
string PI with 3.14159

CONVENTION: reserve CAPITAL letters for constants and use


small caps for variables and functions
Comments
• comments are always a good thing to use because
• not everyone is as smart as you are and needs more
explanation in order to understand your program
• you may not be as smart next month when you have
to change your program
• comments should clarify your code and explain the
rational behind a group of statements
• comment syntax (C style) /* */
/* this is a comment
which can go across multiple
lines of code */
Type Conversions
• C is a hard-typed language, meaning that each variable has
a fixed type that does not change and which determines the
possible assignments and applicable operators
double pi=3.14;
char c=’x’;
• Some type conversions occur automatically for example int
to float or float to double, but also char to int
int i = 17;
float x = i; /* assigns 17 to x */
int j = 2;
float y = i/j; /* assigns 17/2 = 8 to y not 8.5 */
• Type conversions can be forced by a programmer through
a type cast
float z = (float) i / j; /* casts i into float before division */
Library Functions
• Many functionalities in C are carried out by library
functions.
• These functions perform file access, data conversion and
mathematical computations.

#include <math.h> /* include header file for math functions */


int main()
{
double x;
double y;
y=1.57;
x=sin(y);
}
Header Files
• a header file contains the declaration of functions
you want to use in your code
• the preprocessor directive #include takes care of
incorporating a header file into your source file
• example:
#include <math.h>
#include ”myprog.h”
• the brackets <> indicate that the compiler first searches
the standard include directory which contains the
standard C header files first
• the quotation marks indicate that the compiler first
searches
for header files in the local directory
• if you do not include the appropriate header file
you get an error message from the compiler
Header and Library Files
library header file
#include <math.h>
math.h
myprog.c
#include ”myprog.h” user header file
myprog.h

compiler
object file library file

myprog.o libm.a
linker

executable file

myprog
Input / Output
/*Program for print the different data types*/
#include <stdio.h>
int main()
{
int a;
double x;
char c;
printf(“Enter integer:”);
scanf(“%d”,&a);
printf(“\nEnter double:”);
scanf(“%lf”,&x);
printf(“\nEnter character:”);
scanf(“%c”,&c);
printf(“\nThe value of a is %d, of x is %lf, of c is %c\n”,a,x,c);
}
Input / Output
• A stream is an abstraction that refers to a flow of data.

standard
output stdout printf(”%d”,a); variable a
device

standard
input stdin scanf(”%d”,&a); variable a
device
Input / Output
 printf allows you to send output to standard out (screen)
 The special character “\n” represents carriage return line feed
 The symbol %d is a placeholder for an integer variable in the
format string
printf(“the value of a is %d\n”,a)
that will be replaced by the value of the variable a when the
printf statement is executed
 Placeholders:
– integer %d
– long %ld
– float %f
– double %lf
– char %c
– string %s
Input / Output
 scanf allows you to read input from standard in
(keyboard)
 scanf uses the same placeholders as printf
 scanf (“%d”,&a)
the program reads an integer value from the
keyboard and places its value into the integer
variable a
 Notice to put an & in front of the variable, the
reason becomes clear when you learn more
about pointers
Arithmetic and Increment Operators
int a=4;
int b=3;
b=b+a;
b+=3; /* arithmetic assignment operator,
same as b=b+3 */
a++; /* increment operator, same as a=a+1;
*/
a=b++, /* postfix operator */
a=3 * ++b; /* prefix operator */
Arithmetic Operators
• multiplication, summation, subtraction, division
int i = 1/3; /* integer division result 0 */
float x = 1.0/3; /* floating point division result 0.3333 */
int j = 7 % 3; // modulo operator remainder of 7/3
• prefix and postfix-increment operator ++
int i=3;
int j=7;
printf(”%d”,10 * i++); /* outputs 30, i has value 4 afterwards */
Printf(”%d”,10 * ++j); /* outputs 80, j has value 8 afterwards */
• arithmetic assignment operators
float x=6.0;
x+=3.5;
• is equivalent to
x=x+3.5;
Relational Operators
 In C there is no special boolean type. Instead
int is used for boolean expression with the
convention that 0 is false, everything else is
true.
 Relational operators
– > greater
– < less
– >= greater or equal
– <= less or equal
– == equal, not to be confused with assignment =
– != not equal
Relational Operators
• a relational operator compares two values of primitive
in data types such as char, int, float
• typical relationships are equal to, less than and greater than
• the result of a comparison is either true or false, where 0 is
false and any value different from 0 is true
• C provides the following relational operators
<, >, ==, !=, <=, >=
• example:
int x=44;
int y=12;
(x == y) /* false */
(x >= y) /* true */
(x != y) /* true */
Loops
• a loop causes a section of the program to be repeated
multiple times while the loop condition remains true
• C knows three kinds of loops
• for loop
• while loop
• do loop
• the for loop repeats a code segment a fixed number of times
• the for statement contains three expressions usually
refering to the same loop variable separated by semicolons
for ( i=0; i<15; i++ )
initialization expression
test expression
increment expression
For Loop
for ( i=0; i<15; i++ )

initialization expression test expression increment expression


initialization
expression

test false
expression exit
true

body of loop

increment
expression
For Loop
#include <stdio.h>
int main()
{
int a;
int i;
a=1;
for (i=0;i<10;i++)
{
printf(“2 ^ %d = %d\n”,i,a);
a*=2;
}
}
For Loop
for (i=0; i<10;i++)
 initialization expression : i=0;
the initialization statement is called once when the loop
first starts. It gives the loop variable an initial value.
 Test expression : i<10;
the test statement is called each time through the loop,
the body of the loop is executed as long as the test
statement is true
 Increment expression : i++
The increment expression is called at the end of the
loop and changes the value of the loop variable
For Loop
#include <stdio.h>
int main()
{
int number;
int i;
long fact;
fact=1;
printf(“Enter number:”);
scanf(“%d”,&number);
for (i=number; i>0; i--)
fact*=i;
printf(“Factorial of %d is %ld\n”,number,fact);
}
Indendation and Loop Style
• it is good programming practice to indent loops
• there is some variation of the style used for loops
whatever style you use do it consistently
for (i=0; i<10; i++) /* indent body but not the brackets */
{
printf(”%d\n”,i*i);
}
for (i=0; i<10; i++) /* indent body and brackets */
{
printf(”%d\n”,i*i);
}
for (i=0; i<10; i++) { /* opening bracket after loop statement */
printf(”%d\n”,i*i);
}
While / Do-While Loop
while (a>b)
{

}
 the body of the loop is executed as long as the test
statement is true (possibly zero times)
do
{

} while (a>b);
 the body of the loop is executed and then repeated as
long as the test statement is true (at least once)
While Loop
while ( c != ’y’ ) test expression
{

}

test false
expression exit

true

body of loop
While Loop
#include <stdio.h>
int main()
{
int number;
int i;
long fact
fact=1;
printf(“Enter number:”);
scanf(“%d”,&number);
i=number;
while (i>0)
fact*=i--;
printf(“Factorial of %d is %ld\n”,number,fact);
}
While Loop
• the while loop is used when the number of iterations
is unknown before the loop is started
• the while loop is repeated as long as the test expression
remains true

char c=’n’;
while ( c != ’y’)
{
printf(”Do you want to continue: (y/n)\n”);
scanf(”%c”,&c);
}
Do Loop
do test expression
{ …}
while ( c != ’y’ );

body of loop

false
test
expression exit

true
Do - While Loop
#include <stdio.h>
int main()
{

i=number;
do
{
fact*=i--;
} while (i>0); /* do not forget the semicolon */
printf(“Factorial of %d is %ld\n”,number,fact);
}
Do Loop
• in the do loop the test expression is evaluated at the
end of the loop, therefore the body is executed at
least once

char c;
do
{
printf(”Do you want to continue: (y/n)\n”);
scanf(”%c”,&c);
}
while ( c != ’y’);
If … Else Statement
if ( x > 100) test expression
{

}
else test false
{ expression

}
true

body of if body of else

exit
If … Else Statement
• depending on whether the test condition is true or false
either the if or the else branch is executed

int x;
Printf(”Enter a number: ”);
Scanf(”%d”,&x);
if ( x > 100)
printf(”%d is greater than 100\n”,x);
else
printf(”%d is smaller or equal than 100\n”,x);
If…Else Statement
#include <stdio.h>
int main()
{
int a,b;
scanf(“%d %d”,&a,&b);
if (a>b)
printf(“%d is larger than %d\n”,a,b);
else
if (a==b)
printf(“%d is equal to %d\n”,a,b);
else
printf(“%d is smaller than %d\n”,a,b);
}
If…Else Statement
if (a>b)
{

}
else
{

}
 the if part is executed if the test statement is
true, otherwise the else part is executed.
Nested If…Else Statement
if (a>b)
{
if (b>c)
printf(“sorted = %d %d %d\n”,a,b,c);
else
if (a>c)
printf(“sorted = %d %d %d\n”,a,c,b);
else
printf(“sorted = %d %d %d\n”,c,a,b);
}
else
{
if (a>c)
printf(“sorted = %d %d %d\n”,b,a,c);
else

Logical Operators
• logical and : &&
(x >= 5) && ( x <= 15) /* true if x in [5,15] */
• logical or : ||
(x == 5) || ( x == 10) /* true if x=5 or x=10 */
• logical negation : !
! (x == 5) /* true if x is not equal to 5 */
x != 5 /* is equivalent */
• conditional operator : ? … :
<condition> ? <true expression> : < false expression>
if (alpha < beta)
min = alpha;
else
min = beta;
min = (alpha<beta) ? alpha : beta; /* substitutes if …else */
Switch Statement
true
variable
equals first case body
const 1
false

variable true
equals second case body
const 2
false
default body

exit
Switch Statement
• the switch statement is used if there are more than
two alternatives and the decision depends on the value
of the same variable
• the switch statement can replace a ladder of multiple
nested if..else statements

switch(<variable>)
{
case <constant1>:

break;
case <constant2>:

break;
default :

}
Switch Statement
char c;
printf(”Enter your choice (a/b/c) : ”);
Scanf(”%c”,&c);
switch (c)
{
case ’a’:
printf(”You picked a!\n”);
break;
case ’b’:
printf(”You picked a!\n”);
break;
case ’c’:
printf(”You picked a!\n”);
break;
default:
printf(”You picked neither a,b,c !\n”);
}
Scope of Variables
• a block is a section of code delimited by a pair
of brackets { … }

• a declaration introduces a variable into a scope


( a specific part of program text)

• the scope of a variable is the block within which


the variable is declared

• a variable declared outside a function is global.

• a declaration of a variable in an inner block can hide


a declaration in an enclosing block or a global variable
Scope of Variables
visibility of outer i
int i; /* global variable */ lifetime of outer i

int main()
{
int i=3; /* local variable */
{
int j=5; /* local variable */
int i=7; /* local i hides outer i */
printf(”%d\n” i); /* outputs 7 */
} /* end of scope of j and inner i */
printf(”%d\n” i); /* outputs 3 */
} /* end of scope of outer i */
Characters
 Type char
 Characters are small integers (0-255)
 Character constants are integers that
denote corresponding characters
– '0','1','A','B','a','b','\n
'
 ASCII code maps characters to integers
ASCII Code

0 1 2 3 4 5 6 7 8 9
48 49 50 51 52 53 54 55 56 57
A B C D E F G H I J
65 66 67 68 69 70 71 72 73 74
a b c d e f g h i j
97 98 99 100 101 102 103 104 105 106
NULL BEL TAB NEWLINE SPACE
(\0) (\g) (\t) (\n)
0 7 9 10 32
Strings
 String is collection of Characters (or )
group of elements.
 Character arrays that are NULL
terminated.
Example
char arr[4] = “hi”;
[0] [1] [2] [3]

‘h’ ‘i’ NUL ?


L
Strings
 Two interpretations
– Arrays whose elements are characters
– Pointers pointing to characters
 Strings are always terminated with a NULL character
('\0' or 0)
char a[]="hello\n"; /* size? */
char* b=“hello\n”;

a[0] a[1] a[2] a[3] a[4] a[5] a[6]


*b *(b+1) *(b+2) *(b+3) *(b+4) *(b+5) *(b+6)
h e l l o \n null
104 101 108 108 111 10 0
String Initialization
 Initialization
– char m[9] = “I like C”;
– char m[ ] = “I like C”;
– char m[] = { ‘I’, ‘ ’, ‘l’, ‘i’, ‘k’, ‘e’, ‘ ’,’C’ };

‘I’ ‘l’ ‘i’ ‘k’ ‘e’ ‘C’ \0

m[0] m[1] m[2] m[3] m[4] m[5] m[6] m[7] m[8]


String Initialization
char s[30] = "c programming "; // ok, preferred
char s[30] = {"c programming "}; // ok, redundant

char s[30] = {c programming }; // illegal


char s[30] = {c,p,i}; // illegal

char s[30] = {’S',’I',’I',’T'}; // ok, inconvenient


char string_var[30]; // ok, not initialize
char* s = “c++”; //s[0]=‘c’,s[1]=‘+’,s[2]=‘+’, s[3]=0; // ok, initialize
char str[20] = “Initial value”; // ok, initialize

t v ?
I n i i a l a l u e \0 ? ? ? ? ?

Null character
Null is the end of it
#include <vcl.h>
#include <conio.h>
#include <stdio.h>
#include <string.h>
int main()
{
char x[ ];
strcpy(x,"Snoopy is not a cat");
x[11] = '\0';
printf("x = %s",x);
getch();
}
String Assignment
char s[5]="SIIT"; Make sure that you have e
char dept[5], *d=dept; nough memory space to a
char name[20]; ssign the string, otherwise
name = “Peter Pan"; some chars will be lost.
strcpy(name,“Peter Pan");
strcpy(dept,"IT");
printf("%s %s %s\n",d,s,dept);
d = strcpy(s,"EE");
printf("%s %s %s %s\n",name,d,s,dept);

char c1[30], c2[30]=“This is new c1 string”;


char s[30] = "c programming ";
char str1[30];
char *str;
strcpy(c1, c2);
str = strcat(s,"is great!!");
str1 = strcat(s,"is great!!");
In-Class Example

void main()
{ char first[100], last[100];
int i;

strcpy(first,"Peter");
sprintf(last, "Pan");
printf("my name is %s, %s\n", last, first);
for (i=0; i<5; i++)
printf("%s \n",last);
getch();
}
Functions
• a function groups a number of program statements
into a unit and gives it a name
• the function can be invoked from other parts of the program
• dividing a program into functions is one way to structure
your program (structured programming)
• a function declaration specifies the name of the function
the type of the value returned and the number and
type of arguments that must be supplied in a call of
the function
• a function definition contains the body of the function
• typically function declarations take place in header files (.h)
whereas the function definitions are stored in source
files (.c)
What is a function?
 The function is one of the most basic things
to understand in C programming.
 A function is a sub-unit of a program which
performs a specific task.
 We have already (without knowing it) seen
one function from the C library – printf.
 We need to learn to write our own functions.
 Functions take arguments (variables) and
may return an argument.
 Think of a function as extending the C
language to a new task.
An example function
#include <stdio.h>
int maximum (int, int); /* Prototype – see later in lecture */

int main(int argc, char*argv[])


{
int i= 4; Prototype the function
int j= 5;
int k;
Call the function
k= maximum (i,j); /* Call maximum function */
printf ("%d is the largest from %d and %d\n",k,i,j);
printf ("%d is the largest from %d and %d\n",maximum(3,5), 3, 5);
return 0;
}

int maximum (int a, int b) function header


/* Return the largest integer */
{
if (a > b)
The function itself
return a; /* Return means "I am the result of the function"*/
return b; /* exit the function with this result */
}
Factorial program (and thoughts)
int main() number= 4
{ answer= 1
int number= 4; count= 4
int answer; enter while loop
int count; answer= 1*4=4
count=3
answer= 1; enter while loop
count= number; answer=4*3= 12
while (count >= 0) { count=2
answer= answer* count; enter while loop
count--; answer=12*2= 24
} count= 1
printf ("%d! = %d\n", enter while loop
number,answer); answer= 24*1= 24
return 0; count= 0
} enter while loop
answer= 24*0= 0
Functions
int fac(int n); /* function declaration */
int x=7;

printf(”fac(%d)=%d\n”,x, fac(x)); /* call function fac()*/

int fac(int n) /* function definition */


{
int i;
int result=1;
for (i=1; i<=n; i++)
result*=i;
return result; /* exits function and returns value */
}
Functions
int pow(int a, int b); /* function declaration */
int a=3;
Int b=4;
printf(”%d ^ %d =%d\n”,a,b,pow(a,b)); /* call function fac()*/

int pow(int a, int b) /* function definition */


{
int result=1;
int i;
for (i=1; i<=b; i++)
result*=a;
return result; /* exits function and returns value */
}
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.
POINTERS
 A pointer is an address of a storage location
 By convention, zero represents the "null"
pointer
 A pointer is a number, and must itself be
stored
 The size of a pointer depends on the amount
of memory to be addressed
 A 16-bit pointer can address 64K locations
 A 32-bit pointer can address 4 trillion
locations
POINTERS
 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.
Pointers
 Each variable in a program occupies a part of
the computer’s memory, for example an
integer variable occupies 2 bytes of memory
 The location of the piece of memory used to
store a variable is called the address of that
variable
 An address is some kind of number similar to
house numbers in a street that is used to
locate the information stored in that particular
variable
Pointers
 Pointers are used to:
– Access array elements
– Passing arguments to functions when the
function needs to modify the original argument
– Passing arrays and strings to functions
– Obtaining memory from the system
– Creating data structures such as linked lists
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
/*Program to swap the values of two variables in memory

#include<stdio.>
void exchange(int*,int*)
int main()
{ int a,b;
pf(“Enter values of a and b”); sf(“%d%d”&a,&b);
pf(“Before exchange a=%d b=%d”,a,b);
exchange(&a,&b); pf(“After exchange a=%d b=%d”,a,b);
return 0;
}
void exchange(int *aptr, int *bptr)
{ int temp;
temp=*aptr;
*aptr=*bptr;
*bptr=temp;
}
POINTER VARIABLES
 A pointer variable is a variable that holds address values
 Each data type has its own pointer variable, pointer to
int, pointer to double, pointer to char, …
 C uses the address-of operator & to get the address of
an variable
 C uses the indirection or contents-of operator * to
access the value of the variable pointed by
int i=17;
int* ptr; /* defines a pointer variable for integer variables */
ptr= &i; /* assign the address of i to pointer */
printf(”the value of i can be printed as %d or %d\n”, *ptr, i);
printf(”the address of i is %d\n”, ptr);
Pointer Variables
int i; 0x1054
o f 17
int *ptr; ss
d re o f
ad t s
e n
nt
ptr=&i; co

printf(”value of i = %d\n”,*ptr);
Pointer Variables
int v; // defines variable v of type int
int w; // defines variable w of type int
int *p; // defines variable p of type pointer to int
p=&v; // assigns address of v to pointer p
v=3; // assigns value 3 to v
*p=7; // assigns value 7 to v
p=&w; // assigns address of w to pointer p
*p=12; // assigns value 12 to w

 Using the indirection operator *p to access the


contents of a variable is called indirect addressing
or dereferencing the pointer
Pass–by-Value
• when passing arguments by value, the function creates
new local variables to hold the values of the variable
argument
• the value of the original variable are not changed

void f(int val) /* the parameter val holds a local copy of the
variable argument */
{
val++;
}

int x=4;
f(x); /* call function f passing x by value */
printf(”x=%d\n”,x); /* x still has the value 4 */
Pointers as Function Arguments
 C offers two different ways to pass arguments to a
function
– by value : void f(int x);
– by reference : void f(int* x);
 In pass-by-value the function obtains only a local
copy of the variable, so that changes to the local
variable have no impact on the argument with which
the function was invoked
 In pass-by-reference the function manipulates the
original variable rather than merely its copy
Pass-by-Reference
void swap( double* ptr1, double* ptr2)
{
double tmp=*ptr1;
*ptr1=*ptr2; /* de-referencing pointer */
*ptr2=tmp;
}
int main()
{
double a=3.0;
double b=5.0
swap(&a, &b); /* call by reference using the addresses of a and b */
printf(“a=%lf, b=%lf\n”,a,b);
}
*/Factorial of a given number using pointers*/

 main()
{ int n,factorial;
printf(“enter a number”);
scanf(“%d”,&n);
factcompute(n,&factorial);
printf(“the factorial of %d”,n,factorial);
}
factcompute(a,b)
int a,*b;
{
int m; *b=1;
for(m=1;m<=a;m++)
*b=*b*m;
}
Arrays
 The idea of an array is to group similar
objects into units.
 Arrays are structures that group items
of the same data type.
 The elements of an array are accessed
by an index number that allows random
access.
Arrays
int poweroftwo[10]; /*array definition */
int poweroftwo[0]=1; /* first element has index number 0 */
int i;
for (i=1;i<10,i++)
poweroftwo[i]=poweroftwo[i-1]*2;
for (i=0;i<10,i++)
printf(“2 ^ %d = %d\n”,i,poweroftwo[i]);
Arrays
double avg(int sz, double array[]); /* function definition*/
double x[5]={1.2, 2.5, 1.7, 4.2, 3.9} /* initialize array */
printf(“average is %lf\n”,avg(5,x));

double avg(int sz, double array[])


{
int i;
double sum;
for (i=0; i<sz; i++)
sum+=array[i];
return sum/sz;
}
Multi-Dimensional Arrays
#define ROWS 5
#define COLS 6
double matrix[ROWS][COLS];
double a[COLS];
double b[ROWS];
int i,j;

for(i=0;i<ROWS,i++)
{
b[i]=0.0;
for(j=0;j<COLS;j++)
b[i]+=matrix[i][j]*a[j];
}
/* Write a c-program to find the largest number in
an array */
 #include<stdio.h>
#define MAXSIZE 100
main()
{
int n,I,max=0,elements[MAXSIZE];
printf(“enter the no of elements”);
scanf(“%d”,&n);
for(i=0, i<n, i++)
{
printf(“enter value for element %d:”,i);
scanf(%d”,&elements);
}
for(i=0;i<n;i++)
{
if(max<elements[i])
max=elements[i];
}
printf(the maximum is %d”,max);
}
Arrays in Pointers
 Array indexing is syntactic sugar for pointers
 a[i] is treated as *(a+i)
 To zero out an array:
– for (i = 0; i < size; i++) a[i] = 0;
– for (i = 0; i < size; i++) *(a+i) = 0;
– for (p = a; P < a+size; p++) *p = 0;

 Because a[i] means *(a+i), i[a] is equally legal!


Pointers and Arrays
 There is a close association between pointers and arrays
 Arrays can be accessed using pointers
 The name of an array is also a constant pointer to the data
type of the elements stored in the array

int array[5] = { 23, 5, 12, 34, 17 }; /* array of 5 ints */


for (int i=0; i<5; i++)
printf(”%d\n”,array[i]); /* using index to access elements */
for (int i=0; i< 5; i++)
printf(”%d\n”, *(array+i)); /* using pointer to access elements
*/
/* the variable array is of type pointer to integer */
Arrays and Strings
 In C there is no particular type for strings.
Instead strings are stored in arrays of type
character.

#include <strings.h>
char lastname[256]=“Hansen”;
char firstname[256]=“Ole”;
char fullname[512];
strcpy(fullname,firstname);
strcat(fullname,” “);
strcat(fullname,lastname);
printf(“full name is %s\n”,fullname);
Structures
 A structure is a collection of simple variables, that can be of
different type.
 The data items in a structure are called members of the structure.

struct complex /* structure declaration */


{
double re; /* members of the structure */
double im;
};
complex mult(struct complex a, struct complex b);
struct complex a,b,c; /* variable declaration of type complex */
a.re=2.0; /* accessing members of struct complex */
a.im=1.5;
b.re=2.3;
b.im=-1.8;
c=mult(a,b);
C Structures
 Collection of related variables under one name
 Derived data types
 Variables declared within the braces of the structure
definition are the members of the structure
 Members of the same structure type must have
unique names
 Two different structure types can contain members of
the same name without conflict

struct card {
int face;
char suit[20];
};

struct card aCard, deck[52], *cardPtr;


Structures
 Structures are collections of variables of
different types, as in the following
example.

struct abc Structure


{ Type
int a; Name
Structure
Definition long b;
char c;
}
MyStruct; variable
declaration
C Structures and Functions
struct point makepoint(struct point pt, int x, int y) {
pt.x = x;
pt.y = y;
return pt;
}
int main() {
struct point pt;
pt = makepoint (pt, 5, 6);
printf(“pt.x = %d pt.y = %d\n”, pt.x, pt.y);
}
C Structures and Functions
void makepoint(struct point *pt, int x, int y) {
pt->x = x;
pt->y = y;
}
int main() {
struct point pt;
makepoint (&pt, 5, 6);
printf(“pt.x = %d pt.y = %d\n”, pt.x, pt.y);
}

For very large structures, pass the pointer to it!


/*Program to display the month names of both dates*/
 Struct mydate
{ int yyyy;
int mmdd;
};
main()
{ struct mydate date1,date2;
int month1,month2;
char *months[]={“ “,”jan”,”feb”,”mar”,….”dec”};
pf(“enter first date(mmdd)”); sf(“%d”,&date1.mmdd);
pf(“enter second date(mmdd)”); sf(“%d”,&date2.mmdd);
month1-date1.mmdd/100;month2=date2.mmdd/100;//take month alone
pf(“firstt month is %s”,months[month1];”
pf(“second month is %s”,months[month2]);
}
/*Program to illustrate the use of structure pointer

 Struct currency
{ int rupees;
int paise;
};
main()
{ struct currency mycurr={123,25};
showit(&mycurr);
}
showit(struct currency *myptr)
{
pf(“rupees %d,%d”,myptrrupees,myptrpaise);
}
Unions
 Unions look similar to structures. They have identical
declaration syntax and member access, but they serve a
very different purpose.

union Utype {
int ival;
float fval;
char *sval;
};

union Utype x, y, z;

 Accessing members of a union is via “.” member operator


or, for pointers to unions, the -> operator.
Unions
 A union holds the value of one-variable at a time.
 The compiler allocates storage for the biggest member
of the union.
 The type retrieved from the union must be the type
most recently stored. Otherwise, the result is
implementation dependent.

union Utype x;
x.fval = 56.4; /* x holds type float. */
printf("%f\n", x.fval); /* OK. */
printf("%d\n", x.ival); /* Implementation
dependent. */
Unions
 Unions are used to store one of a set of different types.

 Commonly used to implement a “variant” array. (This is


a form of generic programming.)

 There are other uses also, but they are quite advanced
(e.g., concern the alignment properties of unions).
/* Write a c-program for student marks
using an array of structures */
 struct marks
{ int sub1; int sub2;
int sub3; int total; };
main()
{ int i;
static struct marks student[3]={ {56,45,65},
{59,55,75},45,65,75}};
static struct marks total;
for(i=0;i<=2;i++) {
student[i].total=student[i].sub1+student[i].sub2+student[i].sub3;
total.sub1=total.sub1+student[i].sub1;
total.sub2=total.sub2+student[i].sub2;
total.sub3=total.sub3+student[i].sub3;
}
Contd..

printf(“STUDENT TOTAL”);
for(i=0;i<=2;i++)
printf(“student[%d] %d”,i+1,student[i].total);
printf(“SUBJECT TOTAL”);
printf(“%s%d%s%d%s%d”,
”subject 1”, total.sub1,
”subject 2”, total.sub2,
”subject 3”, total.sub3);
printf(“Grand total=%d”,total.total);
}
File Input In C
The C type, “FILE” allows for a consistent approach to input
regardless of the actual physical device

stre
Default: stdin am

FILE
C program
stream
File Output In C
Similar to file input, the C type “FILE” allows for a consistent
approach to output regardless of the actual physical device

Default: stdout

str
ea
m

stream FILE
C program
t r eam
s
Declaring a FILE Variable
 Format:
 FILE *<name of pointer to file>;

 Example:
 FILE *fp;

 Be sure to include the following


preprocessors:
 #include <stdio.h>
 #include <stdlib.h>
Opening Files
 Format:
 FILE * fopen (const char * filename, const char *
mode);

 Example:
 fp = fopen (“data”, “r”);
 fp = fopen (“/home/profs/tamj/data”, “r”);

Error conditions
 File does not exist.
 Insufficient permissions to open the file.
Opening Files (2)
 Filename
– Must reside in the same directory as C program being run
– Alternatively you can include the path to the file

Some File open modes


Mode Effect
r Open text file for reading
w Open text file for writing
a Open text file for writing, start writing at
the end
r+ Open file for reading and writing
w+ Open file for writing and reading
Closing Files
 Disassociates the file with the physical device
 Remaining contents of the stream a flushed
 Format:
 int fclose (FILE * fp);

 Example:
 fclose(fp);
Writing To A File “fprintf”
Format:
 fprintf (FILE *fp, “const char *control_string”,
arguments);

Example:
 char arr[8] = “hiya”;
 fprintf(fp, “%s”, arr);

 Similar to printf except you can also write to a file other


than the screen (standard out).
Reading From A File “fscanf”
Format:
 fscanf (FILE *fp, “<control string>”,
addresses);

Example:
 char arr[8];
 fscanf (fp, “%s”, chunk);

Similar to scanf except you can also read from a


file other than the keyboard (standard in)
Reading From A File “fgets”
 Format:
fgets(char *line, int n, FILE *fp);

 Example:
 fgets(chunk, 80, fp);
File I/O: First Example
The full example can be found in C:

#include <stdio.h>
#include <stdlib.h>
int const LENGTH = 80;
main ()
{
 FILE *fp_in, *fp_out ;
 char arr[LENGTH];
 char fn_in [LENGTH];
 char fn_out [LENGTH];

 printf("Enter name of input file: ");


 scanf("%s", fn_in);
 printf("Enter name of output file: ");
 scanf("%s", fn_out);
File I/O: First Example (2)
 fp_in = fopen(fn_in, "r");
 fp_out = fopen(fn_out, "w");

 if (!fp_in)
 {
 printf("Can't open input file\n");
 return(-1);
 }

 if (!fp_out)
 {
 printf("Can't open output file\n");
 return(-1);
 }
File I/O: First Example (3)
 while (feof(fp_in) == 0)
 {
 // Using fscanf it stops scanning at whitespace
 fscanf(fp_in, "%s", arr);
 fprintf(fp_out, "%s-", arr);
 }
 return(0);
 }
File I/O: Second Example

This example is identical to the first example except for the


loop:

while (feof(fp_in) == 0)
{
 // Grabs whole line up 79 characters or the end-of-file
(whichever comes first)
 fgets (arr, 80, fp_in);

 // Writes out to output file as-is.


 fprintf (fp_out, "%s", arr);
}
File I/O: Third Example

#include <stdio.h>
#include <stdlib.h>

intconst LENGTH = 80;


main ()
{
 FILE *fp_in;
 char arr[LENGTH];
 char fn_in [LENGTH];

 printf("Enter name of input file: ");


 scanf("%s", fn_in);
File I/O: Third Example (2)
 fp_in = fopen(fn_in, "r");
 if (!fp_in)
 {
 printf("Can't open input file\n");
 return(-1);
 }

 while (feof(fp_in) == 0)
 {
 // Grabs whole line up 79 characters or the end-of-file
 fgets(arr, 80, fp_in);

 // Writes out to output file as-is. Output file is the screen


 fprintf(stdout, "%s", arr);
 }
 return(0);
 }
/* Write a program to detect error while opening a file that
does not exist.*/
 #include<stdio.h>
main()
{ char *filename;
FILE *fp1,*fp2;
int i, number;
fp1=fopen(“TEST”,”w”);
for(i=10;i<=100;i+=10){
putw(I,fp1);
fclose(fp1);
printf(“ Input File Name”);
open_file;
scanf(“%s”,filename);
if((fp2=fopen(filename,”r”))==NULL){
printf(“Cannot open the file”);
printf(“Type filenme again”)
goto open_file;
}
Contd../*ERROR HANDLING IN FILE OPERATIONS*/
 else
for(i=1;i<=20;i++)
{
number=getw(fp2);
if(feof(fp2))
{
printf(“Ran out of data”);
break;
}
else
printf(“%d”,number);
}
fclose(fp2);
}
RECURSION
It is the process of calling of a function by itself. The function
which calls itself is known as recursive function.

EXAMPLE: TO CALCUALTE FACTORIAL OF A NUMBER

int factorial(int);
void main()
{
int num,f;
printf(“enter number whose factorial is to be
calculated”);
scanf(“%d”,&num);
f=factorial(num);
printf(“%d”,f);
}

Contd…
int factorial(int x)
{
if(x==1)
return 1;
else
return x*factorial(x-1);
}
THANX

You might also like