Você está na página 1de 150

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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 1
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”

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 2
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.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 3
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 4
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 5
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 6
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.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 7
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 8
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.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 9
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 10
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 11
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!

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 12
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 13
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 14
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 15
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 16
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)
to07/12/21
the shell that started the program.
¨˜”°º•Calypso•º°”˜¨ 17
Compilation & Linking
header file
source file stdio.h
helloworld.c
#include <stdio.h>

compiler

object file helloworld.o


linker

executable file
helloworld
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 18
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 19
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’

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 20
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 double 3.4x10-4932 3.4x104932 19 10

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 21
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;
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 22
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
• this can be dangerous!! APPLEPIE  APPLE3.1459E
• convention: reserve CAPITAL letters for constants and use
small caps for variables and functions

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 23
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 */

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 24
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 07/12/21
z = (float) i / j; /* casts¨˜”°º•Calypso•º°”˜¨
i into float before division */ 25
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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 26
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 27
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 28
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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 29
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 30
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 31
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
 For more information on printf and scanf type
 man printf

 man scanf

at the UNIX prompt


07/12/21 ¨˜”°º•Calypso•º°”˜¨ 32
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 */

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 33
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;
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 34
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 35
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 */
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 36
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 37
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
07/12/21 expression
¨˜”°º•Calypso•º°”˜¨ 38
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;
}
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 39
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 40
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);
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 41
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);
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 42
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)


07/12/21 ¨˜”°º•Calypso•º°”˜¨ 43
While Loop
while ( c != ’y’ ) test expression
{

}

test false
expression exit

true

body of loop

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 44
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);
} 07/12/21 ¨˜”°º•Calypso•º°”˜¨ 45
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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 46
Do Loop
do test expression
{ …}
while ( c != ’y’ );

body of loop

false
test
expression exit

true
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 47
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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 48
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’);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 49
If … Else Statement

if ( x > 100) test expression


{

}
else test false
{ expression

}
true

body of if body of else

exit
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 50
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);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 51
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);
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 52
If…Else Statement
if (a>b)
{

}
else
{

}
 the if part is executed if the test statement is true,

otherwise the else part is executed.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 53
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
…07/12/21 ¨˜”°º•Calypso•º°”˜¨ 54
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 =07/12/21
(alpha<beta) ? alpha¨˜”°º•Calypso•º°”˜¨
: beta; /* substitutes if …else */ 55
Switch Statement

true
variable
equals first case body
const 1
false

variable true
equals second case body
const 2
false
default body

07/12/21 ¨˜”°º•Calypso•º°”˜¨ exit 56


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 :

} 07/12/21 ¨˜”°º•Calypso•º°”˜¨ 57
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”);
} 07/12/21 ¨˜”°º•Calypso•º°”˜¨ 58
/* Write a c-program for Counting words*/
#include <stdio.h>
static const int nIN_A_WORD = 1;
static const int nNOT_IN_A_WORD = 0;
void main()
{
int cNextChar = 0;
int nWords = 0;
int nState = nNOT_IN_A_WORD;
while ((cNextChar = getchar()) != EOF)
{
if (cNextChar == '\n' || cNextChar == ' ')
{
nState = nNOT_IN_A_WORD;
}
else if (nState == nNOT_IN_A_WORD)
{
nState = nIN_A_WORD;
++nWords;
}
}
printf("Words:%d\n", nWords);
07/12/21 } ¨˜”°º•Calypso•º°”˜¨ 59
© 1988, Kernighan/Ritchie
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 60
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 */
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 61
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 62
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 63
Strings
 String is collection of Characters (or ) group of
elements.

 Character arrays that are NULL terminated.


[0] [1] [2] [3]
‘h’ ‘i’ NULL ?

 Example

 char arr[4] = “hi”;

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 64
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 65
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]

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 66
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 67
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();
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 68
String Assignment
char s[5]="SIIT"; Make sure that you have eno
char dept[5], *d=dept; ugh memory space to assign t
char name[20]; he string, otherwise some cha
name = “Peter Pan"; rs 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!!");

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 69
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();
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 70
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)

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 71
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.
 Or perhaps variables are NOUNS functions are VERBS.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 72
An example function
#include <stdio.h>
int maximum (int, int); /* Prototype – see later in lecture */

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


{ Prototype the function
int i= 4;
int j= 5; Call the function
int k;
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;
} function header
int maximum (int a, int b)
/* Return the largest integer */
{
The function itself
if (a > b)
return a; /* Return means "I am the result of the function"*/
return b; /* exit the function with this result */
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 73
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ AHA – I see!!! 74
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 */
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 75
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 */
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 76
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.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 77
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 78
POINTERS
 Examples of pointer declarations:
FILE *fptr;
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.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 79
Pointers
 Each variable in a program occupies a part of the computer’s
memory, for example an integer variable occupies 4 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

int i; address of i 0x1054 10101011


0x1055 00001111
0x1056 10001000
0x1057 11100011
char c; address of c 0x1058 00111011
short s; address of s 0x1059 10111100
07/12/21 0x1060
¨˜”°º•Calypso•º°”˜¨ 11001100 80
POINTERS
 Consider the statements:
#include <stdio.h>
int main ( )
{
FILE *fptr1 , *fptr2 ; /* Declare two file pointers */
int *aptr ; /* Declare a pointer to an int */
float *bptr ; /* Declare a pointer to a float */
int a ; /* Declare an int variable */
float b ; /* Declare a float variable */

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 81
POINTERS

/* Then consider the statements: */

aptr = &a ;
bptr = &b ;
fptr2 = fopen ( "my_out_file.dat" , "w" ) ;
fptr1 = fopen ( "my_in_file.dat" , "r" ) ;
if ( fptr1 != NULL )
{
fscanf ( fptr1, "%d%f" , aptr , bptr ) ;

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 82
POINTERS

fprintf ( fptr2, "%d %d\n" , aptr , bptr ) ;


fprintf ( fptr2, "%d %f\n" , *aptr , *bptr ) ;
fprintf ( fptr2, "%d %f\n" , a , b ) ;
fprintf ( fptr2, "%d %d\n" , &a , &b ) ;
return 0 ;
}
Assuming that the above is part of a program that runs
without error and the the input file does open, what
would be printed to the file
By the first fprintf? By the second fprintf?
By the third fprintf? By the fourth fprintf?

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 83
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 84
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 85
/*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;
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 86
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);
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 87
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);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 88
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 89
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 */
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 90
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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 91
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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 92
*/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;
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 93
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.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 94
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]);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 95
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;
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 96
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];
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 97
/* 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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 98
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!

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 99
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 */
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 100
Write a c program to arrange the given names
in alphabetical order using pointers
 #define COUNT 5
main()
{ char *names[5],temp[20]; int m, n;
for(m=0;m<COUNT;m++) {
printf(“enter name[%d]:”,m);
names[m]=(char *) malloc(20);
scanf(“%s”,name[m]); }
for(m=1;m<=COUNT;m++)
for(n=1;n<=COUNT – m; n++)
if(strcmp(names[n-1],names[n])>0)
{ strcpy(temp,names[n-1]);
strcpy(names[n-1],names[n]);
strcpy(names[n],temp);
temp[0]=‘\0’;
} printf(“sorted list is”);
for(m=0;m<COUNT;m++)
printf(“%s”,names[m]);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 101


BubbleSort
void bsort (double *ptr, int n)
{
int j,k;
for (j=0; j<n-1; j++) /* outer loop */
for(k=j+1; k<n; k++) /* inner loop */
if(*(ptr+j) > *(ptr+k))
swap(ptr+j,ptr+k);
}
double array[6] = { 2.3, 4.5, 1.2, 6.8, 0.8, 4.9 };
bsort(array,n); /* sort the array */

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 102


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);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 103


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);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 104


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;

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 105


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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 106


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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 107


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!

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 108


/*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]);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 109


/*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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 110


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.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 111


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. */

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 112


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).

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 113


/* 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;
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 114


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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 115


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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 116


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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 117


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>

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 118


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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 119


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

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 120


Closing Files

 Disassociates the file with the physical device


 Remaining contents of the stream a flushed
 Format:
 int fclose (FILE * fp);

 Example:
 fclose(fp);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 121


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)

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 122


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)

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 123


Reading From A File “fgets”

 Format:
fgets(char *line, int n, FILE *fp);

 Example:
 fgets(chunk, 80, fp);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 124


File IO: 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);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 125


File IO: 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);
 }

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 126


File IO: 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);
 }

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 127


File IO: 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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 128


File IO: Third Example

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

int const LENGTH = 80;


main ()

{

 FILE *fp_in;

 char arr[LENGTH];

 char fn_in [LENGTH];

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


 scanf("%s", fn_in);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 129


File IO: 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);
 }

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 130


/* 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;
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 131


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);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 132


Random Numbers

 Apply a mathematical function


 e.g., f (n) = f (n-1) % 2

 With f(0) = 3 the function yields 1, 1, 1…


 The starting point for the function is called the seed

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 133


Random Numbers In C

 Need to include the standard library:


 #include <stdlib.h>

 Seeding the random number generator in C:


 srand(time(NULL));

 Generating a random integer in C (calling the


function):
 int rand(void);

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 134


A Simple Random Number Generator (1)
 #include <stdlib.h>
 int const DIE_SIZE = 6;
 int const NO_DICE = 3;
 int roll_score ();
 int main ()
 {
 int strength, dexterity, constitution;
 srand(time(NULL));
 strength = roll_score ();
 dexterity = roll_score ();
 constitution = roll_score ();
 printf("\nThe ability scores of your brave adventurer are...\n");
 printf("STR=%d DEX=%d CONST=%d\n\n", strength,
dexterity, constitution);
 return(0);
 }

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 135


A Simple Random Number Generator (2)

 int roll_score ()
 {
 int i, total, die_roll;
 total = 0;
 for (i = 0; i < NO_DICE; i++)
 {
 die_roll = (rand () % DIE_SIZE) + 1;
 total = total + die_roll;
 }
 return (total);
 }

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 136


A Simple Program To Read Command Line
Arguments (C Language Version)

The full example can be found in Unix:


/home/profs/tamj/233/examples/c_examples/pointers/command_line.c

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

{

 int i;

 for (i = 0; i < argc; i++)

 {

 printf("argv[%d] = %s\n", i, argv[i]);


 }

 return(0);

}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 137


Problem: The Tower of Hanoi

 Problem:

 Initially, peg A has some number of disks starting


with the largest one at the bottom and successively
smaller ones on top
 The objective of the problem is to move the disks
one at a time from peg to peg, never placing a
larger one on top of a smaller one, eventually
ending with all disks on peg C

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 138


Solution: The Tower of Hanoi

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 139


How to Solve the Tower of Hanoi with
Recursion

 Recursive Solution: Divide and Conquer


 The problem of moving n smallest disks from A to C

can be thought of two sub-problems of size n – 1


 First, move the smallest n -1 disks from A to B

 Then, move the nth disk from A to C

 Finally, move the smallest n – 1 disks from B to C

 The underlined sub-problems can also be solved

recursively
 The base case is when n ≤ 0.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 140


Sketch of the Algorithm

void hanoi(int n, char a, char b, char c)


{
if (n > 0) {
hanoi(n-1, a, c, b);
printf(“%c -> %c\n”, a, c);
hanoi(n-1, b, a, c);
}
}
main() {
int number;
printf(“Enter number of disks : ”);
scanf(“%s”, &number);
hanoi(number, ‘a’, ‘b’, ‘c’);
}

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 141


What is a Magic Square?

 A magic square is a quadratic scheme of numbers which


adds up vertically, horizontally and diagonally to the
same sum.
 Only the numbers 1 through n² can be used.
 Ex. If you have a 3x3 magic square your n will equal

3.
 With this equation you can use numbers 1 through

3² (9).
 Each number can only be used once.

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 142


What is a Magic Square?

 an arrangement of the distinct positive integers from


1 to n2 in an nxn matrix,
 each number occurs exactly once

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 143


The Magic Square with C

4 3 8

9 5 1

2 7 6
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 144
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 145
Definition continued…

Magic constant

 The numbers are arranged so that the sum of the numbers in


any horizontal, vertical, or main diagonal line is always the same
number
 That number is known as the magic constant

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 146


There are many different
Variations…

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 147


Main Variations…

 The 1 X 1 magic square

 The 3x3 magic square

 The 4x4 magic square

07/12/21 ¨˜”°º•Calypso•º°”˜¨ 148


Magic-Square .c
#include <stdio.h>
/* input: a 3x3 matrix as nine integers: a(1,1), a(1,2), ..., a(3,3) */
/* output: is the matrix a magic square (equal sum in rows, cols, and main diagonals) */
/* a sample magic square: 6 1 8 / 7 5 3 / 2 9 4 */
int IsMagic (int mat[3][3]);
int main (void)
{
int mat[3][3];
int row, col, ret;
/* read integers from the user */
for (row=0; row<3; ++row)
for (col=0; col<3; ++col)
{
ret = scanf ("%d", &mat[row][col]);
if (!ret || ret == EOF)
{
printf ("Error, input needs to be nine integers.\n");
return -1;
}
}
if (IsMagic (mat) == 1)
printf ("the input is a magic square.\n");
else
printf ("the input square is NOT a magic square.\n");

return 0;
}
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 149
/* function: check if a square is a magic square */
/ * input: a 3x3 matrix of integers */
/ * output: 1 - if it is a magic square 0 – otherwise */
int IsMagic (int mat[3][3])
{
int i, j;
int sum_r, sum_c, ref_sum, r_diag, l_diag;
/* init ref_sum with first row sum */
ref_sum = 0;
for (j=0; j<3; j++)
ref_sum += mat[0][j]; /* check rows and cols together */
for (i=0; i<3; i++)
{ sum_r = sum_c = 0;
for (j=0; j<3; j++)
{
sum_r += mat[i][j];
sum_c += mat[j][i];
}
if (sum_r != ref_sum || sum_c != ref_sum)
return 0;
} /* check main diagonals */
r_diag = l_diag = 0;
for (i=0; i<3; i++)
{
r_diag += mat[i][i];
l_diag += mat[i][2-i];
}
if (r_diag != ref_sum || l_diag != ref_sum)
return 0;
return 1;
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 150
}

Você também pode gostar