Escolar Documentos
Profissional Documentos
Cultura Documentos
• 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
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.
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 3
Why use C?
C is not "safe"
It assumes you know what you're doing
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)
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 8
Some programmer jargon
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.
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 13
printf and scanf
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;
}
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
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
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 21
Variable Definitions
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.
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
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
!= not equal
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 35
Relational Operators
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;
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
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
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
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
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,
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
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 { … }
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'
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
0 7 9 10 32
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 63
Strings
String is collection of Characters (or ) group of
elements.
Example
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 64
Strings
Two interpretations
Arrays whose elements are characters
Initialization
char m[9] = “I like C”;
char m[ ] = “I like C”;
char m[] = { ‘I’, ‘ ’, ‘l’, ‘i’, ‘k’, ‘e’, ‘ ’,’C’ };
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 66
String Initialization
char s[30] = "c programming "; // ok, preferred
char s[30] = {"c programming "}; // ok, redundant
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);
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 */
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
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
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 81
POINTERS
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 83
Pointers
Pointers are used to:
Access array elements
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 84
Use of & and *
When is & used?
When is * used?
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
an variable
C uses the indirection or contents-of operator * to
printf(”value of i = %d\n”,*ptr);
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 88
Pointer Variables
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);
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
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));
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
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 99
Pointers and Arrays
#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);
struct card {
int face;
char suit[20];
};
Struct currency
{ int rupees;
int paise;
};
main()
{ struct currency mycurr={123,25};
showit(&mycurr);
}
showit(struct currency *myptr)
{
pf(“rupees %d,%d”,myptrrupees,myptrpaise);
}
union Utype {
int ival;
float fval;
char *sval;
};
union Utype x, y, z;
union Utype x;
x.fval = 56.4; /* x holds type float. */
printf("%f\n", x.fval); /* OK. */
printf("%d\n", x.ival); /* Implementation dependent. */
There are other uses also, but they are quite advanced
(e.g., concern the alignment properties of unions).
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;
}
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);
}
stre
Default: stdin am
FILE
C program
stream
Default: stdout
str
ea
m
stream FILE
C program
t r eam
s
Format:
FILE *<name of pointer to file>;
Example:
FILE *fp;
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
Filename
Must reside in the same directory as C program being run
Example:
fclose(fp);
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)
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)
Format:
fgets(char *line, int n, FILE *fp);
Example:
fgets(chunk, 80, fp);
#include <stdio.h>
#include <stdlib.h>
main ()
{
char arr[LENGTH];
if (!fp_in)
{
printf("Can't open input file\n");
return(-1);
}
if (!fp_out)
{
printf("Can't open output file\n");
return(-1);
}
while (feof(fp_in) == 0)
{
// Using fscanf it stops scanning at whitespace
fscanf(fp_in, "%s", arr);
fprintf(fp_out, "%s-", arr);
}
return(0);
}
This example is identical to the first example except for the loop:
while (feof(fp_in) == 0)
{
#include <stdio.h>
#include <stdlib.h>
{
FILE *fp_in;
char arr[LENGTH];
while (feof(fp_in) == 0)
{
// Grabs whole line up 79 characters or the end-of-file
fgets(arr, 80, fp_in);
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);
}
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);
}
int
main (int argc, char *argv[])
{
int i;
{
return(0);
}
Problem:
recursively
The base case is when n ≤ 0.
3.
With this equation you can use numbers 1 through
3² (9).
Each number can only be used once.
4 3 8
9 5 1
2 7 6
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 144
07/12/21 ¨˜”°º•Calypso•º°”˜¨ 145
Definition continued…
Magic constant
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
}