based upon Practical C Programming by Steve Oualline CS550 Operating Systems Variable Names Variable names must start with a letter or an underscore No special characters may be used in variable names ID: 448836
Download Presentation The PPT/PDF document "C Programming Day 2" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
C Programming Day 2based upon Practical C Programming by Steve Oualline
CS550
Operating SystemsSlide2
Variable NamesVariable names must start with a letter or an underscoreNo special characters may be used in variable names
Letters, digits, or underscores may follow the first character in the variable nameSlide3
Variable Name ExamplesValid
avg
_pi
number_of_students
inT
Invalid
int
double
the end
3rd_entry
all$doneSlide4
Escape codes\n new line
\r
return
\t
tab
\' single quote\" double quote\\ backslashSlide5
Floating Point vs. Integer Division
19/10 --> 1
R
emember to truncate after the decimal point for integer division
19.0 / 10.0 --> 1.9
19.0 / 10 --> 1.919 / 10.0 --> 1.9Slide6
Character Data Typechar - denotes the character data type and holds one character
char a;Slide7
Example Code#include <
stdio.h
>
int
main(int argc, char **
argv
)
{
char c; //Declaration
c = 'A'; //Initialization
printf
("%c\n", c); //print contents of c
printf
("%d\n", c); //print c as an
int
printf
(”%u\n", &c); //print the address of c
//Assume the address is 1000
return 0;
}Slide8
OutputA
65
1000
Notice that the ASCII code for 'A' is output
ASCII codes can be found on the web
http://www.asciitable.com/Slide9
Reading Data with scanf
Pretend
a
has an address of 205
&a is 205 in C because the ampersand means “address of”int a;
printf
("Please enter an integer: ");
scanf
("%d", &a); //Read data into
//memory location 205
printf
("a is %d\n", a);
printf
("The address of a is %u\n", &a);Slide10
Running the programgcc
addrEx.c
–o
addrEx.exe
or with the Intel compilericc
addrEx.c
–o
addrEx.exe
Output:
Please enter an integer: 5
a is 5
The address of a is 205Slide11
Multiple inputs with scanf
int
a, b, c;
printf
("Enter 3
ints on one line: ");scanf
("%d %d %d", &a, &b, &c);
printf
("%d %d %d", a, b, c);
Enter 3
ints
on one line:
5 10 15
5 10 15Slide12
Field Width Specifiers
printf
("%c%4c%6c\n", ‘C', 'B', ‘A');
//Use 4 spaces for the 2nd character and 6 for the 3rd character
C___B_____A
printf
(”%2d", 3000);
3000
printf
("%5.2lf\n", 6.537);
__6.54Slide13
Common number of bytes used on 64-bit machineschar
--> 1 byte
float
--> 4 bytes
double
--> 8 byteslong double --> 16 bytesint --> 4 byteslong --> 8 bytes
Try the following:
printf
("%u\n",
sizeof
(char));
Note that
%u
represents an
unsigned
intSlide14
ArraysAn array is a sequence of data items that are of the same type and are stored contiguously in memory.
Elements of an array are accessed using square brackets [].
Arrays in C are indexed from zero.
type name[size]; //Array declaration
//note that the size cannot be changedSlide15
Exampleint
intarr
[1000];
0 1 2 999
+---+---+---+--------------------+---+| | | | . . . | |
+---+---+---+--------------------+---+
Attempting to access data beyond the end of an array will often, but not always, result in a segmentation fault. Slide16
Other Exampleschar
carr
[4];
double
darr
[27];unsigned char ucarr[78];
long
larr
[12];Slide17
More on ArraysAn array's size cannot be changed.
d
ouble
darr
[27];
We use a subscript or index to access an element of an array.darr[0]
darr
[19]Slide18
More on Arraysdarr is the name of the array and represents the address of the first element in the array
darr
== 200
index 0 1 2 26
+---+---+---+--------------------+---+ |2.3|5.4|0.2| . . . |7.3|
+---+---+---+--------------------+---+
200 208 216 408
addressSlide19
Addressing ArraysNotice the address changes by 8 because double values take up 8 bytes.
Example
darr
[20]
darr
+ index*sizeof(double)
darr
is the starting point in memory.
The rest is the offset from the starting point
Notice that
darr
is actually an unsigned integerSlide20
Another Exampleint
arr
[5] = {7, 25, 13, 2, -3};
0 1 2 3 4
+---+---+---+---+---+ | 7 | 25| 13| 2 |-13| +---+---+---+---+---+
We can also use the following and get the same effect
int
arr
[] = {7, 25, 13, 2, -3};Slide21
Yet Another Exampledouble data[5] = { 34.0, 27.0, 45.0, 82.0, 22.0 };
double total,
avg
;
total = data[0] + data[1] + data[2] + data[3] + data[4];
avg
= total / 5.0;
printf
("Total %lf\
nAvg
%lf\n", total,
avg
);Slide22
ASCII Art of the Previous Example 0 1 2 3 4
+-----+-----+-----+-----+-----+
d
ata | 34.0| 27.0| 45.0| 82.0| 22.0|
+-----+-----+-----+-----+-----+
+-----+t
otal |210.0|
+-----+
+-----+
a
vg
| 42.0|
+-----+
Total 210.0
Avg
42.0Slide23
StringsIn C, a string is a one-dimensional array of characters (type char
).
Strings always end with a special character -- the
NULL
character
The NULL character is all caps in CThe character '\0', the integer 0, and
NULL
all represent the same null value in C.Slide24
Exampleschar a = '\0'; //The null character
0 1 2 3
+-----+-----+-----+-----+
"
abc
" | 'a' | 'b' | 'c' | '\0'|
+-----+-----+-----+-----+
The length of this string is 3.
The size of this array is 4.
When declaring an array that will contain a string, be sure to leave
one extra character of space for the null character.Slide25
String Exampleschar name[100];
name[0] = 'H';
name[1] = 'e';
name[2] = 'l';
name[3] = 'l';
name[4] = 'o';name[5] = '\0';
printf
("%s\n", name);
char name[] = "Hello";
char name[] = {'H', 'e', 'l', 'l', 'o', '\0'};Slide26
scanfYou
can
use
scanf
to read in a string.
char name[100];printf("Enter your name: ");scanf("%s", name); //Recall that name is the
//address of the beginning
//of the array (string).Slide27
scanf
Enter your name: Dave
0 1 2 3 4
+-----+-----+-----+-----+-----+---------name | 'D' | 'a' | 'v' | 'e' | '\0'| . . .
+-----+-----+-----+-----+-----+---------Slide28
Math Functions in C#include <
math.h
> //to use math functions
x^y
is
pow(x,y)pow(2,2) --> 2^2 = 4double d;d =
pow
(2,3);
d now contains 8.0Slide29
Math Functions in C A few other math functions:
cos
(x)
tan(x)
sin(x) sqrt(x)
d =
sqrt
(50 + 50);
//d will contain 10.0Slide30
Example
#include <
stdio.h
>
#include <
math.h>int
main() {
double
a,b,c
;
a = 3; b = 4;
//compute the square root of a^2 + b^2
c =
sqrt
(
pow
(a,2) +
pow
(b,2));
printf
("%lf is a, %lf is b, and %lf is c\n", a, b, c);
printf
("%lf is a, %lf is b, and %lf is c\n", a, b,
sqrt
(a*a + b*b) );
return 0;
}Slide31
Problems with strings and scanf
char line[100];
scanf
("%s", line); //line is the address
printf
("%s\n", line);Assume an input of:Hello there
The output will be:
Hello
Why?
scanf
counts white space as a delimiter.Slide32
fgets
fgets
reads an entire line. Similar to
Scanner.readLine
()
Be sure to leave lots of space in your arrays when using fgets.Function call:fgets(
name of string
,
size of string in bytes
,
where the input is coming
from
);Slide33
Example of fgets
char name[50];
printf
("Please enter your name: ");
fgets
(name, sizeof(name),
stdin
);
//
sizeof
(name) returns the number
// of bytes in the array name.
//
stdin
is standard input. That
// means we read from the consoleSlide34
ResultPlease enter your name:
Dave
Monismith
Dave
Monismith
<-- has 14 charactersname 0 1 2 3 4 12 13 14 15
+-----+-----+-----+-----+-----+------+-----+-----+-----+-----+--------
| 'D' | 'a' | 'v' | 'e' | ' ' | . . .| 't' | 'h' | '\n'| '\0'| . . .
+-----+-----+-----+-----+-----+------+-----+-----+-----+-----+--------
Notice that the
'\n'
character is stored within our string.
We need to remove it.Slide35
String FunctionsUse
#include <
string.h
>
strlen
(name of string)Provides the length of the string and excludes null character.
strlen
(name)
is 15
We can remove the return character from
name
as follows:
name[
strlen
(name) - 1] = 0;Slide36
sscanf
sscanf
is string
scanf
sscanf(name of string, control string, variables);Slide37
Example
#include <
stdio.h
>
#include <
string.h>int main(
int
argc
, char **
argv
){
int
a, b;
char line[100];
fgets
(
line,sizeof
(line),
stdin
);
sscanf
(line, "%d %d", &a, &b);
printf
("%d %d\n", a, b);
}Slide38
String FunctionsTo use string functions,
#include <
string.h
>
Sometimes compilers will let you get away without it.
strlen - # of characters in a stringstrcpy - allows you to copy the contents of one string into another
strcpy
(destination, source);
strcat
- allows you to concatenate (add to) a string to the end of another string
strcat
(destination, source);
Do NOT use the + operator as you would in Java
name1 = name1 + name2; //Don't do this in CSlide39
Example
char first[100];
char last[100];
char
full_name
[200];printf("%s%s
","Please enter your ",
"first name: ");
fgets
(first,
sizeof
(first),
stdin
);
fgets
(last,
sizeof
(last),
stdin
);Slide40
Example//Remove newline characters
first[
strlen
(first) - 1] = '\0';
last[
strlen(first) - 1] = '\0';strcpy
(
full_name
, first);
strcat
(
full_name
, " ");
strcat
(
full_name
, last);
printf
("%s\n",
full_name
);Slide41
String Comparison
strcmp
(str1, str2)
result is zero if two strings are lexicographically equivalent
A
--> 65a --> 97Try the following:
strcmp
("a", "a");
strcmp
("A", "a");
strcmp
("a", "A");Slide42
Shorthand Operatorsa = a + 2;
is the same as
a += 2
Other operators include
+= -= *= /=Slide43
Pre/Post Operators++ adds one to a variable/expression (increment)-- subtracts one from a variable or expression (decrement)
a++; //Post increment
++a; //Pre incrementSlide44
Pre Increment Example//Try this
a = 1;
printf
("%d\n", ++a);
//Result is the same as
a = a + 1;printf
("%d\n", a);Slide45
Post Increment Example//Try this
a = 1;
printf
("%d\n", a++);
//Result is the same as
printf("%d\n", a);
a = a +1;Slide46
Problems with Pre/Post Incrementvalue = 1;
//Results from the following assignment
//statement are undefined in the
//C standard
result = (value++ * 5) + (value++ * 3);Slide47
Example Answer 1Evaluation could occur as follows:
1 * 5 = 5
value = 2
2 * 3 = 6
value = 3
result = 11Slide48
Example Answer 2Or:
1 * 3 = 3
value
= 2
2 * 5 = 10
value
= 3
result
= 13Slide49
Assignment OperatorDon't play around with the assignment operator either
a = (b = 2) + (c = 3);
//is a valid C statement
//Don't do this!Slide50
Multi-dimensional Arrays
type
arrayname
[dim1][dim2][dim3]...
int
arr[2][3]; Example
arr
[1][0] = 23;