C-Michigan State University
-
Upload
ahmed-sharif -
Category
Documents
-
view
24 -
download
0
description
Transcript of C-Michigan State University
![Page 1: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/1.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C1
Getting Started
Sakti Pramanik(Instructor)
2148 E. B.
office hours
Thu 2-4
Soroor Soltani(TA and grading)
Classroom: 3353 Engineering Building
![Page 2: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/2.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C2
Structure of the Course
Get a quick intro to C programming
Learn enough Unix to use it
Get some experience with
C-oriented tools.Get some experience
writing code
![Page 3: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/3.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C3
What is C?
C is a rather old programming language (1972, Richie, Bell Labs)
Originally designed as a systems software platform (OS and the
like)
Procedural, block oriented language
(no object-oriented programming)Dennis RitchieInventor of the
C Programming Language
![Page 4: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/4.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C4
Why learn C?• Small, extensible language. Progenitor of many
languages.• Many applications and much support due to its
age and general use• Many tools written to support C development.• Close to the hardware, programmer manages
memory• Common embedded systems language• Can be fast, efficient (most cited reason)
![Page 5: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/5.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C5
Disadvantages of C?• Flexible language allows programmers to commit
many sins without warning• Hard to debug, fix code• Speed depends on programmer as much as the
language• Managing memory can be dangerous, difficult,
painful• Lacks modern features (OOP, exceptions, etc.)
![Page 6: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/6.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C6
Course Structure
![Page 7: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/7.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C7
Course will be Lecture/Step
This is a 1 credit course, meets only 15 times
Lecture/Step approach
pend some time on a lecture topic.
pend some time doing “hands-on”work.
ach lecture/step will have some exercise you will have to turn in at the
end
![Page 8: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/8.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C8
Grading
3 projects, each for 15% of the grade, total 45%
13-15 Step assignments, exercises, total 55%
That’s it. No exams, no quizzes
![Page 9: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/9.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C9
Attendance is important
We drop the lowest step assignment grade!
Should go without saying that in a course like this attendance is important.
![Page 10: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/10.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C10
Step exercises
• These can be collaborative, done with discussion and help from anyone during lab. Talk to people, ask questions.
• Lab time is a time to figure stuff out
![Page 11: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/11.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C11
Projects are individual
• No collaboration on projects• They will be checked by cheat check• Just don’t do it. Do your own work
• No makeups! There are only 3 and I’ll give plenty of notice. Get it in on time.
![Page 12: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/12.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C12
Get Started, booting
![Page 13: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/13.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C13
Rebooting to linux
• Machines are split to run either linux (a unixvariant) or Windows
• You can reboot to run “diskless” and bring any machine up in linux.
• Let’s do that now!
![Page 14: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/14.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C14
Booting
If your machine says “press control-alt-delete to log in”, do so, but use the red button in the lower right corner to shut the machine down. Then restart, selecting “diskless” when prompted.
Before logging in, use the Session menu to select GNOME as your session.
Once logged in, select Applications/Internet/IceweaselWeb Browser.
Go to http://www.cse.msu.edu/~cse251
Initial password is your PID (starts with A)
0
![Page 15: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/15.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C15
Bringing up…
Bring up a terminal Window
Applications/Accessories/Terminal
Type:
cal 2011
![Page 16: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/16.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C16
Directories
![Page 17: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/17.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C17
What is a directory/folder?
Be it Windows, Linux or OS X, all OS’s maintain a
directory structure.
A directory is a container of files or other directories
These directories are arranged in a hierarchy or
tree
![Page 18: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/18.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C18
Directory StructureHas a root node, with branch nodes, ends in leaf nodes
The directory structure is a tree
Each directory can hold files and ‘point to’ parent and children directories
Root
Branches
Leaves
/user /bin
/
/cse251
/exercises
hello.c
a.out
/john
a.out
ls
myhello.c
![Page 19: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/19.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C19
File PathA path to a file is a path through the hierarchy to the node that contains a file or directory
/user/cse251/exercises/hello.c myhello.c
/user /bin
/
/cse251
/exercises
hello.c
a.out
/john
a.out
ls
Path is from root node /, to user directory, to cse251 directory, to exercises directory, where the file hello.c resides.
![Page 20: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/20.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C20
The current directory
As you type in the command shell, you are presently “in” one current directory
Many commands are available to navigate by changing your current directory
![Page 21: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/21.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C21
Unix command caution(s)
Names are short. This is to avoid typing. Get used to it
Most commands take “switches”, parameters which modify the behavior of the command. Usually preceded by a ‘-’
All commands, all switches, all paths, all filenames are case sensitive
![Page 22: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/22.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C22
Some Unix Commands
pwd – Displays the current working directory
ls – Lists the contents of the current directory
cd – Changes the current directory
mkdir – Creates a new directory
1
![Page 23: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/23.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C23
Path String
a valid path string is a series of directories (separated by ‘/’) which indicates a valid path in the directory structure
‘/user/cse251/exercises/hello.c’ is a valid path string but ‘/cse251/hello.c’ is not
![Page 24: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/24.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C24
Three special directory names• ‘.’ is shortcut for current directory you are in
• ‘./a.out’ is the same as ‘/user/cse251/exercises/a.out’ if you’re currently in /user/cse251/exercises directory
• ‘..’ is shortcut for the name of the parent directory of the current directory you are in• ‘../a.out’ is the same as ‘/user/cse251/a.out’ if you’re
currently in /user/cse251/exercises directory
• ‘~’ is a shortcut for your home directory• ‘~/myhello.c’ is the same as ‘/user/john/myhello.c’ if your
login name is john
2
![Page 25: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/25.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C25
mv (changes a file)mv is the move command. Rename a file in place or move to a new directory
• mv file.c newFile.c• rename file.c to newFile.c in current directory
• mv file.c /user/ptan/• move file.c in the current directory to /user/ptan. The target
directory must already exist
• mv ~/file.c ./newFile.c• move file.c in home directory to the current directory with the
name newFile.c
![Page 26: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/26.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C26
cp, copy a file
• cp file.c newFile.c• Create a new file called newFile.c in current directory
from the file file.c, which is also in current directory• cp ../file.c ~/programs
• cp file.c in parent directory to the sub-directory programs under the home directory
![Page 27: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/27.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C27
rm, remove a file
Cannot be undone, be careful• rm /user/cse251/exercises/a.out
• remove the file called a.out• rm ./file.c
• remove file.c in the current directory• rm –i ./file.c
• interactive, are you sure?
3
![Page 28: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/28.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C28
man
man pages exist on Unix, providing documentation (a lot of documentation) on each command
• man ls• man page on the ls command
• man -k graphics or apropos graphics• every man page that has “graphics” as a word
• man -S 2 mount• man page for section 2 of mount
![Page 29: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/29.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C29
Better man pages
• Almost every distribution of Linux provides a better way to view man pages
• On Debian/Ubuntu, the program yelp (the help program) will show man pages
• yelp, then man ls• show man page on ls in a nice way
• yelp runs using the “lifesaver” icon. Go to Advanced options, man pages
4
![Page 30: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/30.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C30
What’s the shell
• the shell is the program that interacts with you through the terminal window
• there are many, and you can change it easily• csh• ksh• tcsh• bash
• by default, you are using tcsh
![Page 31: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/31.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C31
Prompt
Default prompt looks like:• <47 nelson:/usr/include >
• 47, which command in the history this is• nelson, the name of the machine you are on• /usr/include, current directory
can be configured differently• [19:19][31][cse251@nelson]~• >
• two lines: time, history, who@machine, path
![Page 32: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/32.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C32
Job control
Only one job runs in foreground (sending text to console), but many can run in background
Foreground job controls the console
• emacs myFile.c &• & mean run emacs in background. Console remains
responsive to commands
• jobs• lists all jobs running in background. Numbers can be used to
control job
![Page 33: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/33.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C33
ps: List of processes
• Typically, each job that is executing is called a process• Sometimes, a job can produce (fork) multiple
processes
• Use “ps” command to list all your current processes (including those that were suspended or running in background)• It also shows the background processes (including
the shell program you’re using)
5
![Page 34: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/34.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C34
Command completion
Type a partial command, followed by tab. it will complete as much as it can
![Page 35: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/35.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C35
Compiling
![Page 36: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/36.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C36
compile to make an executable
• In C, you cannot directly execute the source code. You go through a process called compilation
• Compilation makes sure you “followed the rules of C” (even if you did something stupid), and makes an executable
• Compilation errors are rule “mistakes”. A compilation error means no executable
• The executable file is the thing you run
![Page 37: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/37.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C37
gcc: gnu compiler
• There are others, but this is a good one and it is free (and on all Linux distributions, can be added to the MacOS and runs under Cygwin on windows)
• Has just around a zillion switches. Can be pretty impressive if you read the man page.
![Page 38: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/38.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C38
Example gcc usage
• gcc file.c• if it compiles, makes an executable called a.out in the
same directory as file.c• can run a.out by typing ./a.out (meaning the a.out in
the current directory)• gcc -o myExec file.c
• make the executable called myExec
![Page 39: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/39.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C39
Compilation errors
• You didn’t follow the rules• You have to fix the source code before the
compiler can make an executable• Errors can be cryptic, but at the very least they
list the line number where it went wrong• Doesn’t prevent run-time errors
![Page 40: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/40.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C40
Editors
![Page 41: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/41.jpg)
CSE 251 Dr. Charles B. OwenProgramming in C41
Many Editors
Examples: • gedit• vi • emacs• pico• kate
6
I’m going to suggest using gedit in this course.
![Page 42: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/42.jpg)
Introducing C
1. Please get logged in.
2 Open a new terminal window Applications/Accessories/Terminal2. Open a new terminal window Applications/Accessories/Terminal
3. Open a web browser Applications/Internet/Iceweasel Web Browser
4. Go to http://www.cse.msu.edu/~cse251
5. Open Step 2: Introducing C
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 43: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/43.jpg)
Hello World
#include <stdio.h>
/*/* This is my first program in CSE 251*/
int main(){{printf("Hello, and welcome to CSE 251!!!\n");
}
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 44: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/44.jpg)
Hello World
#include <stdio.h>
/*
#include statement
I l d th d i t/* This is my first program in CSE 251*/
Includes other source code into your program. One use is to tell your program about libraries you
int main(){
your program about libraries you are using. We are using the Standard Input/Output library {
printf("Hello, and welcome to CSE 251!!!\n");}
right now: stdio. The file stdio.h is the header that defines the S d d I/O LibStandard I/O Library.
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 45: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/45.jpg)
Hello World
#include <stdio.h>
/*
Comment
/* This is my first program in CSE 251*/
int main(){
A Comment is a note to yourself. In C we start a comment with /* and end it with */ Everything in{
printf("Hello, and welcome to CSE 251!!!\n");}
and end it with */. Everything in between is ignored.
Programs can be cryptic and hard to read. You need to remind yourself what you were thinking when you wrote something.
CSE 251 Dr. Charles B. OwenProgramming in C4
That’s what comments are for.
![Page 46: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/46.jpg)
Hello World The main function
#include <stdio.h>
/*main() is the starting point for a C
I ’ h h/* This is my first program in CSE 251*/
program. It’s where the computer begins execution. Note the syntax: the code is contained in curly
int main(){
the code is contained in curly braces.
{printf("Hello, and welcome to CSE 251!!!\n");
}
CSE 251 Dr. Charles B. OwenProgramming in C5
![Page 47: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/47.jpg)
Hello World A printf function call
#include <stdio.h>
/*/* This is my first program in CSE 251*/
printf() is a library function that prints. It’s the main way we will get output from our C programs
int main(){
get output from our C programs.
{printf("Hello, and welcome to CSE 251!!!\n");
}
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 48: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/48.jpg)
printf statement in more detailA f i ll ( h d i )A function call (what we are doing)Always a name followed by (, optional arguments, ), and ;.
A string – Content between " and " is our way of telling the computer about
{printf("Hello and welcome to CSE 251!!!\n");
our way of telling the computer about text we want to print.
printf( Hello, and welcome to CSE 251!!!\n );}
\n means “newline”.
C statements end with a ;
CSE 251 Dr. Charles B. OwenProgramming in C7 1
![Page 49: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/49.jpg)
Escape characters
Characters that are hard to express:• \n newline• \t tab• \’ print a single quote\ p g q• \\ print a backslash• many othersmany others
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 50: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/50.jpg)
Variable Declarations
Here is how C deals with memory:• Imagine the system memory as a nice, flat stretch of beach• You want a variable, you need to dig a hole in the sand and dump the value in
• How big a hole?How big a hole?
The holes in C are very specialized. Once dug, they can only hold one type of thing Our holethey can only hold one type of thing. Our hole might hold integers, floating point values, or characters, for example.
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 51: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/51.jpg)
Declare variable before useDeclare variable before use
• When you declare a variable, you are telling the y y gcompiler the kind of value the variable may hold (its type)
• You cannot change the type of value a variable can hold once declared (well, pretty much anyway)
• In fact, everything needs a type in C and it must be declared before use!
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 52: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/52.jpg)
Common types, “regular” C
• int : an integer, usually 4 bytes• float: float, usually 4 bytes• double : float, usually 8 bytes• char : single char, value in single quotesg , g q
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 53: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/53.jpg)
Must declare before use
• Every variable must be declared before it can be used (its type must be indicated)
• Syntax:<variable_type> <variable_name> [ =<initial_value> ];
(optional)
• Example: int length;
CSE 251 Dr. Charles B. OwenProgramming in C12
![Page 54: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/54.jpg)
Must declare before use
• Every variable must be declared before it can be used (its type must be indicated)
• Syntax:<variable_type> <variable_name> [ =<initial_value> ] ;
(optional)
• Example: double width = 10;
CSE 251 Dr. Charles B. OwenProgramming in C13
![Page 55: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/55.jpg)
Rules for Variable Names
• Must begin with a letter• Any combination of letters, digits andAny combination of letters, digits and underscore
• Up to 31 characters long• Up to 31 characters long• Cannot match with a C keyword
– E.g., int int; int long;
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 56: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/56.jpg)
Some C Keywordsyauto double int structbreak else long switchbreak else long switchcase enum register typedefh t t ichar extern return unionconst float short unsigned
fcontinue for signed voiddefault goto sizeof volatiledo if static while
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 57: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/57.jpg)
Some Variable Declarations
int numLots = 7;double width1;double width2;float carHP = 420.7;i bint a, b, c;
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 58: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/58.jpg)
printf: a new feature
You can use printf to output variables as well as strings. Put a “descriptor” in the string you print:
int numLots = 10;double totalArea = 100;double totalArea 00;printf(“There are %d lots\n”, numLots);printf(“The %d lots have a total area of %f\n”, numLots, totalArea);
Follow the string with variables.Each descriptor is replaced with a variable’s value.p p
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 59: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/59.jpg)
Many descriptors
• %s : string• %d : decimal (integer)• %d : decimal (integer)• %e : floating point exponent• %f : floating point decimal• %u : unsigned integer• %u : unsigned integer• and others
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 60: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/60.jpg)
Full Format stringg
• The format string contains a set of format descriptors that describe how an object is to be printedthat describe how an object is to be printed
% -#0 12 .4 h d ConversionType
startifi ti d h
sizemodifier
Type (d for decimal)
specification
Flags
Width
Precision
(h for short int)
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 61: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/61.jpg)
Examplesf(“ f\ ” )• printf(“%f\n”,M_PI);
– 3.141593
i f(“% 4f\ ”M PI)• printf(“%.4f\n”,M_PI);– 3.1416 (4 decimal points of precision, with rounding)
i tf(“%10 2f\ ”M PI)• printf(“%10.2f\n”,M_PI);– 3.14 (10 spaces total including the number and the decimal point)decimal point)
• printf(“%‐10.2f is PI\n”,M_PI);– 3.14 is PI (10 spaces, but left justified)( p , j )
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 62: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/62.jpg)
Examplesi t L t 10int numLots = 10;double totalArea = 100.7883;float current = 22.7;
printf("There are %d lots with a total area of %f\n", numLots, totalArea);/* Output: There are 10 lots with a total area of 100.788300 */
printf("The area is %6.2f\n", totalArea);/* Output: The area is 100.79 */
printf("The meter reads %.1f amps\n", current);/* Output: The meter reads 22.7 amps */
CSE 251 Dr. Charles B. OwenProgramming in C21 2
![Page 63: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/63.jpg)
Expression
An expression is written in pretty standard mathematical notation:
wins + losseswidth * heightwidth heightarea / widthx * y * z – qM PI * 2M_PI * 2
printf(“We played %d games\n”, wins + losses);
We can put expressions where we have been putting variables.
CSE 251 Dr. Charles B. OwenProgramming in C22
![Page 64: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/64.jpg)
Types determine results
• For integers: +,‐,*,/ all yield integers. Thus division can lead to truncation (2/3 has value 0). % gives the remainder
• For floats: +,‐,*,/ all work as advertised. No remainder.
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 65: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/65.jpg)
Mixed computation
• As with most languages, C expects to work with like types. 1 + 1, 3.14 + 4.56
• When mixing, errors are common except where C can “help”
• It will promote a value to a more “detailed” type when required
• 1 + 3.14 yields a float (1 promoted to 1.0)
CSE 251 Dr. Charles B. OwenProgramming in C24
![Page 66: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/66.jpg)
Assignment
An assignment puts a value in a variable. It is of the form:
variable = expression ;variable = expression ;
Do everything on the right hand side, get a value.Dump the value into the variable.
double area, circumference;, ;area = width * height;circumference = radius * 2 * M_PI;
Declare first, assign later!Don’t forget the semicolon.
CSE 251 Dr. Charles B. OwenProgramming in C25
![Page 67: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/67.jpg)
Expression and Assignment Examples
double volume, diameter, hypot;int games;
volume = radius * radius * M_PI;diameter = radius * 2;diameter = radius 2;games = wins + losses;hypot = sqrt(near * near + pow(far, 2));yp q p
To use M_PI or math functions: #include <math.h> and compile with –lm switch.
CSE 251 Dr. Charles B. OwenProgramming in C26 3
![Page 68: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/68.jpg)
scanf
printf("Please enter the yards of pipe used: ");scanf(”%f",&yardsOfPipe);
Scanf is an input routine• Useful for reading in string input and doing• Useful for reading in string input and doing conversion to the correct type, all at once
• Syntax is “kind of like” printfSyntax is kind of like printf• Note the use of the & operator!!!
CSE 251 Dr. Charles B. OwenProgramming in C27
![Page 69: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/69.jpg)
Basic form
• To understand input, it is probably better to start with an example.
scanf(“%d, %f”, &myInt, &myFloat); floatint
…is waiting for input of the exact form
floatint
25, 3.14159
Use %f for float and %lf for double (That’s the letter l not the number 1)Use %f for float and %lf for double. (That’s the letter l, not the number 1)
CSE 251 Dr. Charles B. OwenProgramming in C28
![Page 70: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/70.jpg)
format string the same
• What is typed in the format string is the same as what the input expects, in this case:– a decimal number– a comma
fl i i b– a floating point number
CSE 251 Dr. Charles B. OwenProgramming in C29
![Page 71: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/71.jpg)
The &
• Hard to explain at the moment, but any variable that gets read in needs that ampersand character
• It is the address of the variable• more on that later
CSE 251 Dr. Charles B. OwenProgramming in C30
![Page 72: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/72.jpg)
scanf examples
printf("Input the radius: ");scanf("%lf", &radius);
printf("Input the height: ");f("%lf" &h i h )scanf("%lf", &height);
printf("Input the number of cylinders: ");printf( Input the number of cylinders: );scanf("%d", &numCylinders);
CSE 251 Dr. Charles B. OwenProgramming in C31 4
![Page 73: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/73.jpg)
Flow Control and Booleans
1. Please get logged in.
2 Open a new terminal window Applications/Accessories/Terminal2. Open a new terminal window Applications/Accessories/Terminal
3. Open a web browser Applications/Internet/Iceweasel Web Browser
4. Go to http://www.cse.msu.edu/~cse251
5. Open Step 3: Flow Control and Booleans
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 74: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/74.jpg)
Today: Flow Control and Booleans
Flow Controlif, switch
Boolean Logic<, <=, ==, >=, >, !=
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 75: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/75.jpg)
rlc.c#include <stdio.h>#include <math.h>
/* /* Simple program to compute the resonant frequency of * an RLC circuit*/
int main(){
double l; /* Inductance in millihenrys */double c; /* Capacitance in microfarads */; / p /double omega; /* Resonance frequency in radians per second */double f; /* Resonance frequency in Hertz */
printf("Enter the inductance in millihenrys: ");p ( y );scanf("%lf", &l);
printf("Enter the capacitance in microfarads: ");scanf("%lf", &c);( , );
omega = 1.0 / sqrt((l / 1000) * (c / 1000000));f = omega / (2 * M_PI);printf("Resonant frequency: %.2f\n", f);
CSE 251 Dr. Charles B. OwenProgramming in C3
p ( q y , );}
![Page 76: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/76.jpg)
rlc.c#include <stdio.h>#include <math.h>
/* /* Simple program to compute the resonant frequency of * an RLC circuit*/ Note the use of comments to tell: a) what
the program does, b) what some lines ofint main(){
double l; /* Inductance in millihenrys */double c; /* Capacitance in microfarads */
the program does, b) what some lines of code do, and c) what the variables are.
; / p /double omega; /* Resonance frequency in radians per second */double f; /* Resonance frequency in Hertz */
printf("Enter the inductance in millihenrys: ");p ( y );scanf("%lf", &l);
printf("Enter the capacitance in microfarads: ");scanf("%lf", &c);( , );
omega = 1.0 / sqrt((l / 1000) * (c / 1000000));f = omega / (2 * M_PI); /* Convert radians per sec to Hertz */printf("Resonant frequency: %.2f\n", f);
CSE 251 Dr. Charles B. OwenProgramming in C4
p ( q y , );}
![Page 77: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/77.jpg)
rlc.c#include <stdio.h>#include <math.h>
/* /* Simple program to compute the resonant frequency of * an RLC circuit*/ Note the use of indentation
int main(){
double l; /* Inductance in millihenrys */double c; /* Capacitance in microfarads */; / p /double omega; /* Resonance frequency in radians per second */double f; /* Resonance frequency in Hertz */
printf("Enter the inductance in millihenrys: ");p ( y );scanf("%lf", &l);
printf("Enter the capacitance in microfarads: ");scanf("%lf", &c);( , );
omega = 1.0 / sqrt((l / 1000) * (c / 1000000));f = omega / (2 * M_PI);printf("Resonant frequency: %.2f\n", f);
CSE 251 Dr. Charles B. OwenProgramming in C5
p ( q y , );}
![Page 78: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/78.jpg)
rlc.c#include <stdio.h>#include <math.h>
/* /* Simple program to compute the resonant frequency of * an RLC circuit*/ Indentation is necessary to
make your program readable!int main(){double l; /* Inductance in millihenrys */double c; /* Capacitance in microfarads */
make your program readable!
; / p /double omega; /* Resonance frequency in radians per second */double f; /* Resonance frequency in Hertz */printf("Enter the inductance in millihenrys: ");scanf("%lf", &l);( , );printf("Enter the capacitance in microfarads: ");scanf("%lf", &c);omega = 1.0 / sqrt((l / 1000) * (c / 1000000));f = omega / (2 * M PI);g ( _ );printf("Resonant frequency: %.2f\n", f);}
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 79: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/79.jpg)
Sequential Execution
Statement 1
Statement 2
...
Statement n
CSE 251 Dr. Charles B. OwenProgramming in C7
![Page 80: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/80.jpg)
Selective Execution
booleanexpression
true false
statement 1 statement 2statement 1 statement 2
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 81: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/81.jpg)
if statements
The if statementif(age > 39)Fundamental means of flow controlHow we will make decisions
( g )printf(“You are so old!\n”);
Boolean expressionsThe actual determination of
the decision
age > 39c == 0l <= 0(age >= 18) && (age < 65)the decision (age > 8) && (age < 65)
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 82: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/82.jpg)
Structure of an if statement
If expression1 is true, execute statement1.
Otherwise test to see if expression2 is true If
if(expression1)
Otherwise, test to see if expression2 is true. If so, execute statement2.
Otherwise, execute statement3.statement1;
else if(expression2) /* Optional */statement2;
Otherwise, execute statement3.
statement2;else /* Optional */
statement3;The expressions are boolean expressions thatThe expressions are boolean expressions that resolve to a true or a false.
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 83: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/83.jpg)
Basic Boolean Expressions Some operators:
truefalse
< Less than<= Less than or equal to
age < 18divisor == 0size > 1000000
== Equal!= Not equal>= Greater than or equal tosize > 1000000
ch == ‘X’q
> Greater than
Important: The test for equality is ==, not =. This is the most common error in a C programa C program.
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 84: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/84.jpg)
Example if statements < Less than<= Less than or equal to
E lif(age < 18)
printf(“Too young to vote!\n”);
== Equal!= Not equal>= Greater than or equal to> Greater than
if(area == 0)printf(“The plot is empty\n”);
else
> Greater than
elseprintf(“The plot has an area of %.1f\n”, area);
if(val < 0)( )printf(“Negative input is not allowed\n”);
else if(val == 0)printf(“A value of zero is not allowed\n”);
elseprintf(“The reciprocal is %.2f\n”, 1.0 / val);
Note the indentation
CSE 251 Dr. Charles B. OwenProgramming in C12 1
Note the indentation
![Page 85: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/85.jpg)
Blocks Single Statementprintf(“This is a statement\n”);
{Block
{printf(“All items in a curly brace\n”);printf(“as if there are one statement”);printf(“They are executed sequentially”);
}}
CSE 251 Dr. Charles B. OwenProgramming in C13
![Page 86: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/86.jpg)
Where is this useful? If the expression is true, all of the statements in
if(value > 0){
result = 1.0 / value;i tf("R lt %f\ " lt)
the block are executed
printf("Result = %f\n", result);}
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 87: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/87.jpg)
Where is this useful? Will these two sections of code work
if(value > 0){
result = 1.0 / value;i tf("R lt %f\ " lt)
differently?
printf("Result = %f\n", result);}
if(value > 0)result = 1.0 / value;printf("Result = %f\n", result);printf( Result %f\n , result);
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 88: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/88.jpg)
Where is this useful? Yes!
if(value > 0){
result = 1.0 / value;i tf("R lt %f\ " lt)printf("Result = %f\n", result);
}
if(value > 0)result = 1.0 / value;printf("Result = %f\n", result);
Will always execute!
printf( Result %f\n , result);
CSE 251 Dr. Charles B. OwenProgramming in C16 2
![Page 89: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/89.jpg)
Nested Blocks What does this do?
if(bobsAge != suesAge) /* != means "not equal" */{
printf("Bob and Sue are different ages\n");if(b b A > A )if(bobsAge > suesAge){
printf("In fact, Bob is older than Sue\n");if((bobsAge ‐ 20) > suesAge)(( g ) g ){
printf("Wow, Bob is more than 20 years older\n");}
}}}
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 90: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/90.jpg)
Importance of indentation See how much harder this is to read?
if(bobsAge != suesAge) /* != means "not equal" */{printf("Bob and Sue are different ages\n");if(b b A > A )if(bobsAge > suesAge){printf("In fact, Bob is older than Sue\n");if((bobsAge ‐ 20) > suesAge)(( g ) g ){printf("Wow, Bob is more than 20 years older\n");}}}}
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 91: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/91.jpg)
Boolean Expressions
• An expression whose value is true or false• In C:
– integer value of 0 is “false”– nonzero integer value is “true”
• Example of Boolean expressions:
Relational operator– age < 40– graduation_year == 2010
Relational operator
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 92: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/92.jpg)
#include <stdio.h>#include <stdbool.h>
Library that defines: bool, true, false
int main(){
const bool trueVar = true, falseVar = false; const int int3 3 int8 8;const int int3 = 3, int8 = 8;
printf("No 'boolean' output type\n");printf("bool trueVar: %d\n",trueVar);printf("bool falseVar: %d\n\n",falseVar);printf("int int3: %d\n",int3);printf("int int8: %d\n",int8);
}
What does the output look like?
}
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 93: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/93.jpg)
#include <stdio.h>#include <stdbool.h>
Library that defines: bool, true, false
int main(){
const bool trueVar = true, falseVar = false; const int int3 3 int8 8;const int int3 = 3, int8 = 8;
printf("No 'boolean' output type\n");printf("bool trueVar: %d\n",trueVar);printf("bool falseVar: %d\n\n",falseVar);printf("int int3: %d\n",int3);printf("int int8: %d\n",int8);
}
What does the output look like?
}
CSE 251 Dr. Charles B. OwenProgramming in C21
![Page 94: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/94.jpg)
// E l 3 ( ti d )// Example3 (continued…)
printf("\nint3 comparators\n");printf( \nint3 comparators\n );
printf("int3 == int8: %d\n",(int3 == int8));
printf("int3 != int8: %d\n",(int3!=int8));printf( int3 ! int8: %d\n ,(int3! int8));
printf("int3 < 3: %d\n",(int3 < 3));
printf("int3 <= 3: %d\n",(int3 <= 3));
Comparing values of two integer constants
printf("int3 > 3: %d\n",(int3 > 3));
printf("int3 >= 3: %d\n",(int3 >= 3));
What does the output look like?
CSE 251 Dr. Charles B. OwenProgramming in C22
![Page 95: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/95.jpg)
// E l 3 ( ti d )// Example3 (continued…)
printf("\nint3 comparators\n");printf( \nint3 comparators\n );
printf("int3 == int8: %d\n",(int3 == int8));
printf("int3 != int8: %d\n",(int3!=int8));printf( int3 ! int8: %d\n ,(int3! int8));
printf("int3 < 3: %d\n",(int3 < 3));
printf("int3 <= 3: %d\n",(int3 <= 3));
printf("int3 > 3: %d\n",(int3 > 3));
printf("int3 >= 3: %d\n",(int3 >= 3));
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 96: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/96.jpg)
More Examples
• char myChar = ‘A’; – The value of myChar==‘Q’ is false (0)
• Be careful when using floating point equality comparisons, especially with zero, e.g. myFloat==0
CSE 251 Dr. Charles B. OwenProgramming in C24
![Page 97: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/97.jpg)
Suppose?
What if I want to know if a value is in a range?
Test for: 100 ≤ L ≤ 1000?
CSE 251 Dr. Charles B. OwenProgramming in C25
![Page 98: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/98.jpg)
You can’t do… This code is WRONG and will fail.
if(100 <= L <= 1000){
printf(“Value is in range \n”);printf( Value is in range…\n );}
CSE 251 Dr. Charles B. OwenProgramming in C26
![Page 99: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/99.jpg)
Why this fails… C Treats this code this way
if((100 <= L) <= 1000){
printf(“Value is in range \n”);printf( Value is in range…\n );}
Suppose L is 5000. Then 100 <= L is true, so (100 <= L) evaluates to true, which, in C, is a 1. Then it tests 1 <= 1000, which also returns true, even though you expected a false., g y p
CSE 251 Dr. Charles B. OwenProgramming in C27
![Page 100: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/100.jpg)
Compound Expressions
• Want to check whether ‐3 <= B <= ‐1– Since B = ‐2, answer should be True (1)
• But in C, the expression is evaluated as– ((‐3 <= B) <= ‐1) (<= is left associative)– (‐3 <= B) is true (1)– (1 <= ‐1) is false (0)Th f i 0!– Therefore, answer is 0!
CSE 251 Dr. Charles B. OwenProgramming in C28
![Page 101: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/101.jpg)
Compound Expressions
• Solution (not in C): (‐3<=B) and (B<=‐1)
• In C: (‐3<=B) && (B<=‐1)• Logical Operatorsg p
– And: &&– Or: ||– Not: !
CSE 251 Dr. Charles B. OwenProgramming in C29
![Page 102: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/102.jpg)
Compound Expressions#i l d tdi h#include <stdio.h>
int main() {{const int A=2, B = ‐2;
printf("Value of A is %d\n", A);printf("0 <= A <= 5?: Answer=%d\n", (0<=A) && (A<=5));
printf("Value of B is %d\n", B);printf("‐3 <= B <= ‐1?: Answer=%d\n", (‐3<=B) && (B<=‐1));
}
CSE 251 Dr. Charles B. OwenProgramming in C30
![Page 103: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/103.jpg)
Compound Expressions#include <stdio h>#include <stdio.h>
int main() {const int A=2, B = ‐2;
printf("Value of A is %d\n", A);printf("0 <= A <= 5?: Answer=%d\n" (0<=A) && (A<=5));printf( 0 <= A <= 5?: Answer=%d\n , (0<=A) && (A<=5));
printf("Value of B is %d\n", B);printf("‐3 <= B <= ‐1?: Answer=%d\n", (‐3<=B) && (B<=‐1));
Correct Answer!!!
} True (1) True (1)
CSE 251 Dr. Charles B. OwenProgramming in C31
![Page 104: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/104.jpg)
Compound Expressions#include <stdio h>#include <stdio.h>
int main() {const int A=2, B = ‐2;
printf("Value of A is %d\n", A);printf("0 <= A <= 5?: Answer=%d\n" (0<=A) && (A<=5));printf( 0 <= A <= 5?: Answer=%d\n , (0<=A) && (A<=5));
printf("Value of B is %d\n", B);printf("‐3 <= B <= ‐1?: Answer=%d\n", (‐3<=B) && (B<=‐1));
Correct Answer!!!
} True (1) True (1)
&&
True (1)
&&
CSE 251 Dr. Charles B. OwenProgramming in C32
![Page 105: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/105.jpg)
Truth TablesN A d O
p q !p p && q p || qNot And Or
True True
True FalseTrue False
False True
False False
CSE 251 Dr. Charles B. OwenProgramming in C33
![Page 106: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/106.jpg)
Truth TablesN A d O
p q !p p && q p || q Not And Or
True True False
True False FalseTrue False False
False True True
False False True
CSE 251 Dr. Charles B. OwenProgramming in C34
![Page 107: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/107.jpg)
Truth TablesN A d O
p q !p p && q p || q Not And Or
True True True
True False FalseTrue False False
False True False
False False False
CSE 251 Dr. Charles B. OwenProgramming in C35
![Page 108: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/108.jpg)
Truth TablesN A d O
p q !p p && q p || q Not And Or
True True True
True False TrueTrue False True
False True True
False False False
CSE 251 Dr. Charles B. OwenProgramming in C36
![Page 109: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/109.jpg)
Truth TablesN A d O
Our comparison operators: < <= == != >= >
p q !p p && q p || q Not And Or
True True False True True
True False False False TrueTrue False False False True
False True True False True
False False True False False
CSE 251 Dr. Charles B. OwenProgramming in C37 3
![Page 110: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/110.jpg)
Precedence & AssociativityCan you guess what’s the answer?Can you guess what s the answer?
Relational operators have precedence and associativity(just like arithmetic operators)Use ( ) when in doubt
CSE 251 Dr. Charles B. OwenProgramming in C38
![Page 111: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/111.jpg)
( ((A + B) > 5) && ( ((A=0) < 1) > ((A + B) – 2)) )
( (6 > 5) && ( ((A=0) < 1) > ((A + B) – 2)) )
( 1 && ( ( 0 < 1) > ((A + B) – 2)) )( 1 && ( ( 0 < 1) > ((A B) 2)) )
( 1 && ( 1 > ( 2 – 2) ) )
( 1 && ( 1 > 0 ) )
( 1 && 1 )( )
Answer: 1 Precedence: +/‐> <
CSE 251 Dr. Charles B. OwenProgramming in C39
&&
![Page 112: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/112.jpg)
Associativity
“=“ is right associativeExample: X=Y=5
right associative: X = (Y=5)right associative: X (Y 5)expression Y=5 returns
value 5: X = 5
CSE 251 Dr. Charles B. OwenProgramming in C40
![Page 113: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/113.jpg)
You should refer to theYou should refer to the C operator precedence and associative table
See for example, http://www.difranco.net/cop2220/op‐prec.htmp
Or just useOr just use parentheses whenever you’re unsure about
d dprecedence and associativity
CSE 251 Dr. Charles B. OwenProgramming in C41
![Page 114: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/114.jpg)
Switch StatementA less general substitute for the multibranch if. It is used for selecting among discrete values (int), i.e. not continuous valuescontinuous values.
switch (int_expression){
case_list: statement list; _ ;
case_list: statement_list;
default:default: statement_list;
}
CSE 251 Dr. Charles B. OwenProgramming in C42
Switch & Functions
![Page 115: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/115.jpg)
Behavior
• The int_expression is evaluated. If the value is in a case_list, execution begins at that statement_list and continues through subsequent statement_lists until: break, return or end of switchreturn, or end of switch.
CSE 251 Dr. Charles B. OwenProgramming in C43
Switch & Functions
![Page 116: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/116.jpg)
#include <stdio.h>
void main() { int gender; printf("Enter your gender (male=1, female=2): ");
f("%d" & d )scanf("%d",&gender);
switch(gender) {{
case 1: printf("You are a male\n"); break;break;
case 2:printf("you are a female\n"); break;
default:printf("Not a valid input\n"); break;
CSE 251 Dr. Charles B. OwenProgramming in C44
} }
![Page 117: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/117.jpg)
switch(gender) {
case 1: printf("You are a male\n"); break;
case 2:i f(" f l \ ")printf("you are a female\n");
break; default:printf("Not a valid input\n");printf( Not a valid input\n ); break;
}
CSE 251 Dr. Charles B. OwenProgramming in C45 4
![Page 118: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/118.jpg)
Loops and Repetition
condition
true
false
statement
true
int count = 1
t 5true falsecount <= 5
statement
true
count ++
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 119: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/119.jpg)
First, the tax programdouble income;int filingStatus;int numDependents;int children;int children;double standardDeduction;double deductions;double taxableIncome;double tax;
printf("Enter your annual income: ");scanf("%lf" &income);scanf( %lf , &income);
if(income < 9350){
printf("You may be poor, but you owe no taxes\n");exit(0);
}
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 120: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/120.jpg)
printf("What is your filing status? \n1) single\n”);printf(“2) married filing jointly\n3) married filing separately\n");printf("Please enter a number: ");scanf("%d", &filingStatus);
switch(filingStatus){
case 1:numDependents = 1;standardDeduction = 5700;break;
case 2:printf("How many children do you have? ");printf( How many children do you have? );scanf("%d", &children);numDependents = children + 2;standardDeduction = 11400;break;
case 3:numDependents = 1;standardDeduction = 5700;break;break;
default:printf("Invalid input!\n");exit(1);b k
CSE 251 Dr. Charles B. OwenProgramming in C3
break;}
![Page 121: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/121.jpg)
deductions = standardDeduction + numDependents * 3650;taxableIncome = income ‐ deductions;
if(taxableIncome < 0)( ){
tax = 0;}else if(taxableIncome <= 16750)( ){
tax = taxableIncome * 0.10;}else if(taxableIncome <= 68000)( ){
tax = 1675 + 0.15 * (taxableIncome ‐ 16750);}else if(taxableIncome <= 137300)( ){
tax = 9362.50 + 0.25 * (taxableIncome ‐ 68000);}else{
tax = 26687.50 + 0.28 * (taxableIncome ‐ 137300);}
CSE 251 Dr. Charles B. OwenProgramming in C4
printf("%.2f\n", tax);
![Page 122: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/122.jpg)
Loops and Repetition
Loops in programs allow us to repeat blocks of code.p
Useful for:Trying again for correct inputCountingRepetitive activitiesRepetitive activitiesPrograms that never end
CSE 251 Dr. Charles B. OwenProgramming in C5
![Page 123: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/123.jpg)
Three Types of Loops/Repetition in C • while
– top‐tested loop (pretest)
• for– counting loop– forever‐sentinel
• do– bottom‐tested loop (posttest)
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 124: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/124.jpg)
The while loopd l ( )Top‐tested loop (pretest)
while (condition)statement;
Note that, as in IF selection, only one statement is executed. You need a block to repeat more than one statement (using { })
CSE 251 Dr. Charles B. OwenProgramming in C7
![Page 125: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/125.jpg)
while(condition)statement;
conditionfalse
true
statement
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 126: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/126.jpg)
Similar to the if statement
• Check the boolean condition• If true, execute the statement/block
Repeat the above until the boolean is falsep
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 127: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/127.jpg)
Examplebool valid = true; // Until we know otherwise
printf("Enter the inductance in millihenrys: ");scanf("%lf", &l);
/* Test to see if the user entered an invalid value */ if(l <= 0){printf("You moron, you entered an invalid inductance!\n");valid = false;
}elseelseprintf("Okay, I guess that's reasonable\n");
Remember this? What if weRemember this? What if we input invalid values?
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 128: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/128.jpg)
Example with while loop
bool valid = false; /* Until we know otherwise */
while(!valid) /* Loop until value is valid */{{
printf("Enter the inductance in millihenrys: ");scanf("%lf", &l);
/* Test to see if the user entered an invalid value */ / /if(l < 0){
printf("You moron, you entered a negative inductance!\n");}}else if(l == 0){
printf("You are really dumb, you entered zero.\n");}}else{
printf("Okay, I guess that's reasonable\n");valid = true;;
}} What does this do different?
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 129: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/129.jpg)
while
condition falsewhile (condition)
statement;
t t t
truewhile (condition){
statement1;statementstatement2;
}
hil (! lid) /* L til l i lid */while(!valid) /* Loop until value is valid */{
printf("Enter the inductance in millihenrys: ");scanf("%lf", &l);
int i = 10;while(i > 0){
if(l > 0){
valid = true;}
}
{printf("i=%d\n", i);i = i ‐ 1;
}
CSE 251 Dr. Charles B. OwenProgramming in C12
}
1
![Page 130: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/130.jpg)
Forever loops and never loops
Because the conditional can be “always true” or “always false”, you can get a loop that runs forever
t llor never runs at all.
int count=0;while(count !=0)
What is wrong with these statements?while(count !=0)
printf(“Hi Mom”);
while (count=1) //insidious error!!!while (count 1) //insidious error!!!count = 0;
CSE 251 Dr. Charles B. OwenProgramming in C13
![Page 131: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/131.jpg)
How to count using while
First, outside the loop, initialize the counter variableTest for the counter’s value in the booleanDo the body of the loopLast thing in the body should change the value of the g y gcounter! i = 1;
while(i <= 10){{
printf("i=%d\n", i);i = i + 1;
}}
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 132: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/132.jpg)
The for loop
The while loop is pretty general. Anything that can be done using repetition can be done with a while loop
Because counting is so common, there is a specialized construct called a for loop.
A for loop makes it easy to set up a counting loop
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 133: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/133.jpg)
Three parts for(count=1;count<=5; count++)statement;
Three parts to a for loop (just like the while):• Set the initial value for the counterSet the initial value for the counter• Set the condition for the counter• Set how the counter changes each time through the• Set how the counter changes each time through the loop
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 134: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/134.jpg)
for(count=1; count<=5; count++)printf(“count=%d\n”, count);printf( count %d\n , count);
count = 1
falsecount <= 5true
false
printf
count ++
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 135: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/135.jpg)
Ascending for<=,++
for (control_var=init_value; control_var <=limit_value; control var++) statement;,
control_var = init_value
control_var++) statement;
true falsecontrol_var<= limit_value
true false
statement
control_var ++
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 136: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/136.jpg)
Descending for>
for (control_var=init_value; control_var >=limit_value; control var ) statement;>=,‐‐
control_var = init_value
control_var‐‐) statement;
control_var>= limit_value
true false
statement
control_var ‐‐
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 137: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/137.jpg)
Commentsd l l l• It is dangerous to alter control_var or limit_var
within the body of the loop.
• The components of the for statement can be a arbitrary statements e g the loop condition mayarbitrary statements, e.g. the loop condition may be a function call.
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 138: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/138.jpg)
for(count=1; count<=5; count++)printf(“count=%d\n”, count); count = 1printf( count %d\n , count);
count <= 5truefalse
for(i=1; i<=10; i++){ count <= 5
printf
trueprintf("%d\n", i);}
for(t = 1.7; t < 3.5; t = t + 0.1)
count ++
( ; ; ){
printf("%f\n", t);}
for(i=1; i<5; i++){for(j=1; j<4; j++){
printf("%d * %d = %d\n", i, j, i * j);}
}
CSE 251 Dr. Charles B. OwenProgramming in C21 2
}
![Page 139: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/139.jpg)
Top‐tested Equivalencep q
The following loopfor(x=init; x<=limit; x++)for(x=init; x<=limit; x++)
statement_listis equivalent tois equivalent to
x=init;while (x<=limit){while (x<=limit){
statement_list;x++;x++;
}
CSE 251 Dr. Charles B. OwenProgramming in C22
![Page 140: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/140.jpg)
Some Magic Statements
s += 12; /* Equivalent to s = s + 12; */s ‐= 13; /* Equivalent to s = s – 13; */
These work fine for integers or floating point
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 141: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/141.jpg)
break;
The break statement exits the containing loop immediately!while(true) /* Loop until value is valid */{{
printf("Enter the inductance in millihenrys: ");scanf("%lf", &l);
/* Test to see if the user entered an invalid value *// Test to see if the user entered an invalid value / if(l <= 0){
printf("You moron, you entered an invalid inductance!\n");}}else{
printf("Okay, I guess that's reasonable\n");break;break;
}}
CSE 251 Dr. Charles B. OwenProgramming in C24
![Page 142: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/142.jpg)
The do/while loop Often just called a “do loop”.
• do/while– bottom‐tested loop (posttest)
do{
angle += 2 * M PI / 20;angle + 2 M_PI / 20;sinVal = sin(angle);printf(“sin(%f) = %f\n”, angle, sinVal);
} while(sinVal < 0.5);} ( )
CSE 251 Dr. Charles B. OwenProgramming in C25
![Page 143: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/143.jpg)
Bottom‐tested Loop: do
• Bottom‐tested (posttest)• One trip through loop is guaranteed, i.e.
i d lstatement is executed at least once
do do {statement
while (loop_condition);
{statement1;statement2;
}}while (loop_condition);
Usually!
CSE 251 Dr. Charles B. OwenProgramming in C26
![Page 144: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/144.jpg)
do { statement; } while(condition)
statement;
conditiontrue false
CSE 251 Dr. Charles B. OwenProgramming in C27
![Page 145: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/145.jpg)
do/while Examples i = 0;do
angle = M_PI / 2;do{
do{
i++;printf("%d\n", i);
} hil (i 10){angle ‐= 0.01;cosVal = cos(angle);printf("cos(%f)=%f\n", angle, cosVal);
} while(i < 10);
p ( ( ) \ , g , );} while(cosVal < 0.5);
do{
printf("Enter a value > 0: ");printf( Enter a value > 0: );scanf("%lf", &val);
} while(val <= 0);
CSE 251 Dr. Charles B. OwenProgramming in C28
![Page 146: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/146.jpg)
Bottom‐tested Equivalence• Bottom tested do loop (posttest)• Bottom‐tested do loop (posttest)
do {
statement;}while (condition);( );
• Similar to bottom‐tested forever loopfor (;;){{
statement_list;if (!condition) break;
}
CSE 251 Dr. Charles B. OwenProgramming in C29
![Page 147: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/147.jpg)
The “one off” error for(i=1; i<10; i++){
It is easy to get a for loop to be “one off” of the
{}
for(i 1; i< 10; i++)number you want. Be careful of the combination of init value
for(i=1; i<=10; i++){}
combination of init_valueand < vs. <= for(i=0; i<10; i++)
{
Counting from 0, with <, is a good combination
{}
is a good combination and good for invariants as well.
CSE 251 Dr. Charles B. OwenProgramming in C30
![Page 148: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/148.jpg)
The “one off” error for(i=1; i<10; i++){ 9 l 1 9It is easy to get a for loop
to be “one off” of the
{}
for(i 1; i< 10; i++)
9 values: 1 to 9
number you want. Be careful of the combination of init value
for(i=1; i<=10; i++){}
10 values: 1 to 10combination of init_valueand < vs. <= for(i=0; i<10; i++)
{
Counting from 0, with <, is a good combination
{} 10 values: 0 to 9
is a good combination and good for invariants as well.
CSE 251 Dr. Charles B. OwenProgramming in C31
![Page 149: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/149.jpg)
while, for, do/whilefor(i=1; i<=10; i++){
printf("%d\n", i);}
for(t 1 7; t < 3 5; t t + 0 1)for(t = 1.7; t < 3.5; t = t + 0.1){
printf("%f\n", t);}
do{
printf("Enter a value > 0: ");scanf("%lf" &val);
i = 0;do{
i++;printf("%d\n" i);
scanf( %lf , &val);} while(val <= 0);
for(i=1; i<5; i++){
hil (! lid) /* L til l i lid */
printf( %d\n , i);} while(i < 10); for(j=1; j<4; j++)
{printf("%d * %d = %d\n", i, j, i * j);
}} i t i 10while(!valid) /* Loop until value is valid */
{printf("Enter the inductance in millihenrys: ");scanf("%lf", &l);
if(l > 0) angle = M_PI / 2;
} int i = 10;while(i > 0){
printf("i=%d\n", i);i = i ‐ 1;if(l > 0)
{valid = true;
}}
do{angle ‐= 0.01;cosVal = cos(angle);printf("cos(%f)=%f\n" angle cosVal);
;}
CSE 251 Dr. Charles B. OwenProgramming in C32
printf( cos(%f)=%f\n , angle, cosVal);} while(cosVal < 0.5);
3
![Page 150: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/150.jpg)
Functions
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 151: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/151.jpg)
Moon Landings
Time Fuel Velocity
Will Cyr 13 86.20 ‐0.49
Yongjiao Yu 13 86.00 ‐1.82
Bin Tian 13 87 00 ‐1 69Bin Tian 13 87.00 ‐1.69
Nan Xia 13 87.00 ‐1.69
Chenli Yuan 13 87.00 ‐1.69
Scott Oliver 13 87.70 ‐2.74
Mike Robell 13 87.88 ‐3.00
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 152: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/152.jpg)
Triangle Area Computation 12 ppa −=
p2=(x2 y2)
p3=(x3,y3)23
13
ppc
ppb
−=
−=c
p2=(x2,y2)
ab
22 )12()12( yyxxa −+−=
p1=(x1,y1) ))()((cba
cpbpapparea++
−−−=
2cbap ++
=
How would you write this program?
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 153: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/153.jpg)
Variablesint main(){
double x1=0 y1=0;double x1=0, y1=0;double x2=17, y2=10.3;double x3=‐5.2, y3=5.1;
double a, b, c; /* Triangle side lengths */double p; /* For Heron's formula */double area;
12 ppa −=
23
13
ppc
ppb
pp
−=
−=
pp
22 )12()12( yyxxa −+−=
CSE 251 Dr. Charles B. OwenProgramming in C4
![Page 154: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/154.jpg)
Lengths of Edges
a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));b = sqrt((x1 ‐ x3) * (x1 ‐ x3) + (y1 ‐ y3) * (y1 ‐ y3));c = sqrt((x2 ‐ x3) * (x2 ‐ x3) + (y2 ‐ y3) * (y2 ‐ y3));
13
12
ppb
ppa
−=
−=
23 ppc −=
22p2=(x2,y2)
p3=(x3,y3)c
22 )12()12( yyxxa −+−=
ab
))()(( cpbpapparea =p1=(x1,y1)
2
))()((cbap
cpbpapparea++
=
−−−=
CSE 251 Dr. Charles B. OwenProgramming in C5
![Page 155: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/155.jpg)
Areap = (a + b + c) / 2;area = sqrt(p * (p ‐ a) * (p ‐ b) * (p ‐ c));q (p (p ) (p ) (p ));
printf("%f\n", area); ))()(( cpbpapparea −−−= ))()(( cpbpapparea −−−=
2cbap ++
=2
cbap ++=
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 156: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/156.jpg)
Whole Programint main(){
double x1=0, y1=0;Wh if I d i kdouble x2=17, y2=10.3;
double x3=‐5.2, y3=5.1;
double a, b, c; /* Triangle side lengths */
What if I made a mistake on the edge length equation?
double a, b, c; / Triangle side lengths /double p; /* For Heron's formula */double area;
t(( 1 2) * ( 1 2) ( 1 2) * ( 1 2))a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));b = sqrt((x1 ‐ x3) * (x1 ‐ x3) + (y1 ‐ y3) * (y1 ‐ y3));c = sqrt((x2 ‐ x3) * (x2 ‐ x3) + (y2 ‐ y3) * (y2 ‐ y3));
p = (a + b + c) / 2;area = sqrt(p * (p ‐ a) * (p ‐ b) * (p ‐ c));
printf("%f\n" area);printf( %f\n , area);}
CSE 251 Dr. Charles B. OwenProgramming in C7
![Page 157: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/157.jpg)
Functions
• Functions are subprograms that perform some operation and return one value
• They “encapsulate” some particular operation, so it can be re‐used by others (for example, the abs() or
() f i )sqrt() function)
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 158: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/158.jpg)
Characteristics
• Reusable code– code in sqrt() is reused often
• Encapsulated code– implementation of sqrt() is hidden
• Can be stored in libraries– sqrt() is a built‐in function found in the math library
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 159: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/159.jpg)
Writing Your Own Functions
• Consider a function that converts temperatures in Celsius to temperatures in Fahrenheit.– Mathematical Formula:
F C * 1 8 32 0F = C * 1.8 + 32.0
– We want to write a C function called CtoF– We want to write a C function called CtoF
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 160: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/160.jpg)
Convert Function in C
double CtoF ( double paramCel ) {
return paramCel*1.8 + 32.0; }
• This function takes an input parameter called paramCel (temp in degree Celsius) and returns aparamCel (temp in degree Celsius) and returns a value that corresponds to the temp in degree Fahrenheita e e
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 161: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/161.jpg)
How to use a function?
#include <stdio.h>
double CtoF( double );
/************************************************************************* Purpose: to convert temperature from Celsius to Fahrenheit ************************************************************************/int main() {
double c, f;printf(“Enter the degree (in Celsius): “);scanf(“%lf”, &c);
f = CtoF(c);printf(“Temperature (in Fahrenheit) is %lf\n”, f);
}
double CtoF ( double paramCel) {
return paramCel * 1.8 + 32.0;}}
CSE 251 Dr. Charles B. OwenProgramming in C12
![Page 162: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/162.jpg)
TerminologyD l ti d bl Ct F( d bl )• Declaration: double CtoF( double );
• Invocation (Call): Fahr CtoF(Cel);• Invocation (Call): Fahr = CtoF(Cel);
• Definition:• Definition: double CtoF( double paramCel ) {{ return paramCel*1.8 + 32.0;
}}
CSE 251 Dr. Charles B. OwenProgramming in C13
![Page 163: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/163.jpg)
Function Declarationl ll d f• Also called function prototype:
return_type function_name (parameter_list)
double CtoF(double)• Declarations describe the function:
– the return type and function name
( )
– the type and number of parameters
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 164: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/164.jpg)
Function Definition
return_type function_name (parameter_list) {
….function body….
}
double CtoF(double paramCel) {{
return paramCel*1.8 + 32.0;}
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 165: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/165.jpg)
Function Invocation1 C ll i
int main() { …f = CtoF(c);
1. Call copies argument c to
tf CtoF(c); } parameter
paramCel
double CtoF ( double paramCel ){
2. Control f {
return paramCel*1.8 + 32.0;}
transfers to function “C F”“CtoF”
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 166: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/166.jpg)
Invocation (cont)
int main() { …
f = CtoF(c); }
3. Expression in “CtoF” is
} evaluated
double CtoF ( double paramCel ){
return paramCel*1 8 + 32 0;
4. Value of expression return paramCel*1.8 + 32.0;
}expression is returned to “main”to main
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 167: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/167.jpg)
Local Objects
• The parameter “paramCel” is a local object which is defined only while the function is executing. Any attempt to use “paramCel” outside the function is an error.
• The name of the parameter need not be the same as th f th t T tthe name of the argument. Types must agree.
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 168: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/168.jpg)
Can we do better than this?
int main(){double x1=0, y1=0;double x2 17 y2 10 3double x2=17, y2=10.3;double x3=‐5.2, y3=5.1;
double a, b, c; /* Triangle side lengths */double p; /* For Heron's formula */double area;
a = sqrt((x1 x2) * (x1 x2) + (y1 y2) * (y1 y2));a = sqrt((x1 ‐ x2) (x1 ‐ x2) + (y1 ‐ y2) (y1 ‐ y2));b = sqrt((x1 ‐ x3) * (x1 ‐ x3) + (y1 ‐ y3) * (y1 ‐ y3));c = sqrt((x2 ‐ x3) * (x2 ‐ x3) + (y2 ‐ y3) * (y2 ‐ y3));
p = (a + b + c) / 2;area = sqrt(p * (p ‐ a) * (p ‐ b) * (p ‐ c));
printf("%f\n" area);printf( %f\n , area);}
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 169: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/169.jpg)
What should we name our function?a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));
“Length” sounds like a good ideaLength sounds like a good idea.
??? Length( ??? ){{}
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 170: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/170.jpg)
What does our function need to know?a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));
(x, y) for two different points:
??? Length(double x1, double y1, double x2, double y2)
{{}
CSE 251 Dr. Charles B. OwenProgramming in C21
![Page 171: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/171.jpg)
What does our function return?a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));
A computed value which is of type double
double Length(double x1, double y1, double x2, double y2)
{{}
CSE 251 Dr. Charles B. OwenProgramming in C22
![Page 172: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/172.jpg)
How does it compute it?a = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));
A computed value which is of type double
double Length(double x1, double y1, double x2, double y2)
{{double len;len = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));return(len);return(len);
}
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 173: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/173.jpg)
Using This#include <stdio.h>#include <math.h>
/* Declaration */double Length(double x1, double y1, double x2, double y2);
/* * Program to determine the area of a triangle*/
int main(){
Declaration
{double x1=0, y1=0;double x2=17, y2=10.3;double x3=‐5.2, y3=5.1;
double a, b, c; /* Triangle side lengths */d bl /* ' f l */double p; /* For Heron's formula */double area;
a = Length(x1, y1, x2, y2);b = Length(x1, y1, x3, y3);c = Length(x2, y2, x3, y3);
Invocations
p = (a + b + c) / 2;area = sqrt(p * (p ‐ a) * (p ‐ b) * (p ‐ c));
printf("%f\n", area);}}
/* Definition */double Length(double x1, double y1, double x2, double y2){
double len;len = sqrt((x1 ‐ x2) * (x1 ‐ x2) + (y1 ‐ y2) * (y1 ‐ y2));
Definition
CSE 251 Dr. Charles B. OwenProgramming in C24
len sqrt((x1 x2) (x1 x2) (y1 y2) (y1 y2));return(len);
}
1
![Page 174: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/174.jpg)
Potential Errors#include <stdio.h>double convert( double );
int main()int main() {
double c, f;printf(“Enter the degree (in Celsius): “);scanf(“%lf”, &c);scanf( %lf , &c); f= convert(c);printf(“Temp (in Fahrenheit) for %lf Celsius is %lf”, paramCel, f);
} Error! paramCel is not defined
double CtoF( double paramCel) {
return c * 1.8 + 32.0;} Error! C is not defined
Scope – Where a variable is known to existError! C is not defined known to exist.
No variable is known outside of the curly braces that contain it, even if the same name is used!
CSE 251 Dr. Charles B. OwenProgramming in C25
![Page 175: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/175.jpg)
Another Example
#include <stdio.h>
double GetTemperature();p ();double CelsiusToFahrenheit( double );void DisplayResult( double, double );
int main()
Declarationsint main(){
doubleTempC, // Temperature in degrees CelsiusTempF; // Temperature in degrees Fahrenheit
TempC = GetTemperature();TempF = CelsiusToFahrenheit(TempC); InvocationsTempF = CelsiusToFahrenheit(TempC);DisplayResult(TempC, TempF);
return 0;}
CSE 251 Dr. Charles B. OwenProgramming in C26
![Page 176: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/176.jpg)
Function:GetTemperature
double GetTemperature(){
double Temp;p;
printf("\nPlease enter a temperature in degrees Celsius: ");scanf("%lf", &Temp);return Temp;return Temp;
}
CSE 251 Dr. Charles B. OwenProgramming in C27
![Page 177: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/177.jpg)
Function: CelsiusToFahrenheitdouble CelsiusToFahrenheit(double Temp){
return (Temp * 1.8 + 32.0);}}
CSE 251 Dr. Charles B. OwenProgramming in C28
![Page 178: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/178.jpg)
Function: DisplayResultvoid DisplayResult(double CTemp, double FTemp){
printf("Original: %5.2f C\n", CTemp);printf("Equivalent: %5 2f F\n" FTemp);printf( Equivalent: %5.2f F\n , FTemp);
return;}
CSE 251 Dr. Charles B. OwenProgramming in C29
![Page 179: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/179.jpg)
Declarations (Prototypes)
double GetTemp( ); double CelsiusToFahrenheit( double );double CelsiusToFahrenheit( double );void Display( double, double );
• voidmeans “nothing”. If a function doesn’t return a gvalue, its return type is void
CSE 251 Dr. Charles B. OwenProgramming in C30
![Page 180: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/180.jpg)
Abstraction 1. Get Temperature2. Convert Temperature
int main(){doubleTempC // Temperature in degrees Celsius
p3. Display Temperature
TempC, // Temperature in degrees CelsiusTempF; // Temperature in degrees Fahrenheit
TempC = GetTemperature();( )TempF = CelsiusToFahrenheit(TempC);
DisplayResult(TempC, TempF);
return 0; We are hiding details on how somethingreturn 0;}
We are hiding details on how something is done in the function implementation.
CSE 251 Dr. Charles B. OwenProgramming in C31
![Page 181: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/181.jpg)
Another Way to Compute Factorial
Pseudocode for factorial(n)
if n == 0 thenresult = 1
else result = n * factorial(n – 1)result = n factorial(n – 1)
After all, 5! = 5 * 4 * 3 * 2 * 1 = 5 * 4!
CSE 251 Dr. Charles B. OwenProgramming in C32
![Page 182: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/182.jpg)
Factorial function contains an invocation of itself.
Recursive Functionsinvocation of itself.
We call this a: recursive call.
int Factorial(int n){
if(n == 0)t 1return 1;
else return n * Factorial(n‐1);
}
Recursive functions must have a base case
}
This works much like proof by induction (if n == 0): why?proof by induction.
if n == 0 thenif n 0 thenresult = 1
else result = n * factorial(n 1)
CSE 251 Dr. Charles B. OwenProgramming in C33
result = n * factorial(n – 1)
![Page 183: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/183.jpg)
Infinite Recursion What if I omit the “base case”?
int Factorial(int n){
return n * Factorial(n‐1);}
This leads to infinite recursion!
}
Factorial(3)=
cbowen@ubuntu:~/cse251$ ./combi1Input n: 5Input k: 3Factorial(3)=
3 * Factorial(2) = 3 * 2 * Factorial(1) = 3 * 2 * 1 * Factorial(0) =
Input k: 3Segmentation fault
3 2 1 Factorial(0) 3 * 2 * 1 * 0 * Factorial(‐1) = …
CSE 251 Dr. Charles B. OwenProgramming in C34
![Page 184: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/184.jpg)
Psuedocode and Function if n == 0 thenresult = 1
int Factorial(int n){
if(n == 0)t 1
else result = n * factorial(n – 1)Base Case
return 1;else
return n * Factorial(n‐1);}}
Declaration: int Factorial(int n);
Invocation: f = Factorial(7);Invocation: f Factorial(7);
Definition:
int Factorial(int n){
if(n == 0)freturn 1;
else return n * Factorial(n‐1);
}
CSE 251 Dr. Charles B. OwenProgramming in C35 2
![Page 185: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/185.jpg)
Pointers and Reference parameters
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 186: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/186.jpg)
Today’s Lecture
Pointers are variables that Address Variable Value
0 4520 B 181 store memory addresses0x4520 B 181
0x4524 pB 0x4520
Address Variable ValueBefore we learn about
Memory Address
0x4520 B 181
0x4524 pB 0x4520
pointers, we must learn more about addresses
Pointer Value
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 187: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/187.jpg)
Computer Memory
Memory is just a long list of numbers one after the otherMy laptop has over 4 Billion of these numbersthese numbers
Each number is 8 bits (BYTE)We combine them to make
integers and floating point valuesintegers and floating point values
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 188: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/188.jpg)
Computer Memory
int (21) float (18.2)
CSE 251 Dr. Charles B. OwenProgramming in C4
![Page 189: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/189.jpg)
Memory AddressesMemory addresses in computers are often 32 bits (or nowadays, 64‐bits) long, e.g.
01111111111111111111101010001100
Another way to represent an address is to use hexadecimal:
0x 7ffffa8c
CSE 251 Dr. Charles B. OwenProgramming in C5
![Page 190: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/190.jpg)
Hexadecimal (Base‐16) 0000 = 0 1000 = 80001 = 1 1001 = 90010 = 2 1010 = 10 = a0011 = 3 1011 = 11 = b
I have included this chart on your
0100 = 4 1100 = 12 = c0101 = 5 1101 = 13 = d0110 6 1110 14
yworksheet so you can refer to it.
0110 = 6 1110 = 14 = e0111 = 7 1111 = 15 = f
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 191: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/191.jpg)
Addressesb dd ( )32‐bit address (Binary):
0111 1111 1111 1111 1111 1010 1000 11007 f f f f a 8 c
32‐bit address (Hex): 0x 7 f f f f a 8 cNotes:
– In C “0x” indicates a Hexadecimal number– Convert every four bits to a hex digit
CSE 251 Dr. Charles B. OwenProgramming in C7
![Page 192: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/192.jpg)
Arithmetic (in Hex) 0000 = 0 1000 = 80001 = 1 1001 = 9
Sum: 0x 90 + 0x 04
0001 1 1001 90010 = 2 1010 = 10 = a0011 = 3 1011 = 11 = b
0x 94 0100 = 4 1100 = 12 = c0101 = 5 1101 = 13 = d0110 = 6 1110 = 14 = e0111 = 7 1111 = 15 = f
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 193: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/193.jpg)
Arithmetic (in Hex) 0000 = 0 1000 = 80001 = 1 1001 = 9
Sum with carry: 0x 8c + 0x 04
0001 1 1001 90010 = 2 1010 = 10 = a0011 = 3 1011 = 11 = b
0x ?? 0100 = 4 1100 = 12 = c0101 = 5 1101 = 13 = d0110 = 6 1110 = 14 = e0111 = 7 1111 = 15 = f
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 194: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/194.jpg)
Arithmetic (in Hex)
Sum with carry: 0x 8c + 0x 04 0x ??
– What is “c + 4”? – In decimal it is “12 + 4 = 16”
hi h i H “10” (0 d 1)which is Hex “10” (0 and carry 1)
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 195: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/195.jpg)
Arithmetic (in Hex)1
Sum with carry: 0x 8c + 0x 04 0x ??
– What is “c + 4”? – In decimal it is “12 + 4 = 16”
hi h i H “10” (0 d 1)which is Hex “10” (0 and carry 1)
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 196: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/196.jpg)
Arithmetic (in Hex)1
Sum with carry: 0x 8c + 0x 04 0x 90
– What is “c + 4”? – In decimal it is “12 + 4 = 16”
hi h i H “10” (0 d 1)which is Hex “10” (0 and carry 1)
CSE 251 Dr. Charles B. OwenProgramming in C12 1
![Page 197: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/197.jpg)
Bytes and Words
Remember
byteword
8 bits = 1 byte32 bits = 4 bytes = 1 word.
32‐bit address machines are addressed by bytes so
consecutive words haveconsecutive words have addresses that differ by four
CSE 251 Dr. Charles B. OwenProgramming in C13
![Page 198: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/198.jpg)
32‐bit AddressesH h i 32 bi dd (i H ) f dHere are three consecutive 32‐bit addresses (in Hex) of words:
0x00712050 dc bb 21 000x00712054 01 00 00 000x00712058 00 00 00 00
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 199: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/199.jpg)
PointersPointers are variables that contain addresses
Just like other variables, they must be declared before being usedbeing used
Declaration: int *p; /* instead of int p for integers */
int * means p is a pointer variable that stores the addressint * means p is a pointer variable that stores the address of an integer variable
CSE 251 Dr. Charles B. OwenProgramming in C15
Pointers and Ref parameters
![Page 200: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/200.jpg)
Pointer Initialization
Declaration: int a = 2; /* a is an integer */i t * A & /* A i i t t i iint *pA = &a;/* pA is a pointer containing
the address of a */
“&” operator means “address of”Read it as “at”Read it as “at”
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 201: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/201.jpg)
The Address Game int a = 2; int *pA = &a;
a
pAp
An Intel processor is called a little endianprocessor because it stores values with the leastprocessor because it stores values with the least significant byte first. You read it in reverse order.
0x00602104 in memory will be: 04 21 60 00
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 202: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/202.jpg)
Example Program“%x” prints the hexadecimal value
Operators:
int a = 21;int *pA = &a;
p& “address of”* “dereference”
printf("%d\n", a);printf("%x\n", a);printf("% \n" &a);
2115f
Output
printf("%x\n", &a);printf("%x\n", pA);printf("%d\n", *pA);printf("%x\n", &pA);
bfee861cbfee861c21bfee8618p ( p ) bfee8618
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 203: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/203.jpg)
#include<stdio.h>
int main() {{
int a = 15, b = 38;int *c = &a;printf("%x : %d\n", &a, a);p ( \ , , );printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);
a = 49;a = 49;printf("%x : %d\n", &a, a);printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);p ( \ , , , );
c = &b;printf("%x : %d\n", &a, a);printf("%x : %d\n" &b b);printf( %x : %d\n , &b ,b);printf("%x : %x : %d\n", &c, c, *c);
}
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 204: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/204.jpg)
#include<stdio.h>
int main() {{
int a = 15, b = 38;int *c = &a;printf("%x : %d\n", &a, a);p ( \ , , );printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);
a = 49;a = 49;printf("%x : %d\n", &a, a);printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);p ( \ , , , );
c = &b;printf("%x : %d\n", &a, a);printf("%x : %d\n" &b b);printf( %x : %d\n , &b ,b);printf("%x : %x : %d\n", &c, c, *c);
}
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 205: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/205.jpg)
First SectionDeclares a and b as integersDeclares c as a pointer that contains the address of a (“points to a”)
int a = 15 b = 38;Address Memory Name
address of a ( points to a )
int a = 15, b = 38;int *c = &a;printf("%x : %d\n", &a, a);
0xeffffa94
0 ffff 90
a
b
15
38printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);
0xeffffa90
0xeffffa8c
b
c
38
0xeffffa94
CSE 251 Dr. Charles B. OwenProgramming in C21
![Page 206: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/206.jpg)
First SectionDeclares a and b as integersDeclares c as a pointer that contains the address of a (“points to a”)
int a = 15 b = 38;Address Memory Name
address of a ( points to a )
int a = 15, b = 38;int *c = &a;printf("%x : %d\n", &a, a);
0xeffffa94
0 ffff 90
a
b
15
38printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);
0xeffffa90
0xeffffa8c
b
c
38
0xeffffa94
Output:effffa94 15effffa90 38effffa8c effffa94 15
CSE 251 Dr. Charles B. OwenProgramming in C22
![Page 207: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/207.jpg)
First SectionDeclares a and b as integersDeclares c as a pointer that contains the address of a (“points to a”)
int a = 15 b = 38;
address of a ( points to a )
Note the difference betweenint a = 15, b = 38;int *c = &a;printf("%x : %d\n", &a, a);
Note the difference between *C in variable declaration and *C in printf
printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);
Output:effffa94 15effffa90 38effffa8c effffa94 15
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 208: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/208.jpg)
#include<stdio.h>
int main() {{
int a = 15, b = 38;int *c = &a;printf("%x : %d\n", &a, a);p ( \ , , );printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);
a = 49;a = 49;printf("%x : %d\n", &a, a);printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);p ( \ , , , );
c = &b;printf("%x : %d\n", &a, a);printf("%x : %d\n" &b b);printf( %x : %d\n , &b ,b);printf("%x : %x : %d\n", &c, c, *c);
}
CSE 251 Dr. Charles B. OwenProgramming in C24
![Page 209: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/209.jpg)
Second SectionAddress Memory Namey
0xeffffa94 A
B
15 49
38
a = 49;printf("%x : %d\n", &a, a);printf("%x : %d\n", &b ,b);
0xeffffa90
0xeffffa8c
B
C
38
0xeffffa94
printf("%x : %x : %d\n", &c, c, *c);
CSE 251 Dr. Charles B. OwenProgramming in C25
![Page 210: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/210.jpg)
Second ExampleAddress Memory Namey
0xeffffa94 A
B
15 49
38
a = 49;printf("%x : %d\n", &a, a);printf("%x : %d\n", &b ,b);
0xeffffa90
0xeffffa8c
B
C
38
0xeffffa94
printf("%x : %x : %d\n", &c, c, *c);
Output:effffa94 49effffa90 38effffa8c effffa94 49
CSE 251 Dr. Charles B. OwenProgramming in C26
![Page 211: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/211.jpg)
#include<stdio.h>
int main() {{
int a = 15, b = 38;int *c = &a;printf("%x : %d\n", &a, a);p ( \ , , );printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);
a = 49;a = 49;printf("%x : %d\n", &a, a);printf("%x : %d\n", &b ,b);printf("%x : %x : %d\n", &c, c, *c);p ( \ , , , );
c = &b;printf("%x : %d\n", &a, a);printf("%x : %d\n" &b b);printf( %x : %d\n , &b ,b);printf("%x : %x : %d\n", &c, c, *c);
}
CSE 251 Dr. Charles B. OwenProgramming in C27
![Page 212: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/212.jpg)
Third Section Address Memory Name
0xeffffa94
0xeffffa90
A
B
49
38
c = &b; /* c now points to b */printf("%x : %d\n", &a, a);printf("%x : %d\n", &b ,b);i f("% % %d\ " & * )
0xeffffa8c C0xeffffa90printf("%x : %x : %d\n", &c, c, *c);
CSE 251 Dr. Charles B. OwenProgramming in C28
![Page 213: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/213.jpg)
Third Section Address Memory Name
0xeffffa94
0xeffffa90
A
B
49
38
c = &b; /* c now points to b */printf("%x : %d\n", &a, a);printf("%x : %d\n", &b ,b);i f("% % %d\ " & * )
0xeffffa8c C0xeffffa90printf("%x : %x : %d\n", &c, c, *c);
O t tOutput:effffa94 49effffa90 38effffa8c effffa90 38effffa8c effffa90 38
CSE 251 Dr. Charles B. OwenProgramming in C29 2
![Page 214: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/214.jpg)
Reference parameters
A valuable use for pointers:Passing addresses to a function
CSE 251 Dr. Charles B. OwenProgramming in C30
![Page 215: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/215.jpg)
Argument & Returned Value
Consider a function call y=f(x). – The value x is passed to the function f – A value is returned and assigned to y.
d h h l f– By passed we mean that the value of argument x is copied to the parameter in the function. Some calculation is performed and the result is returned and passigned to y.
CSE 251 Dr. Charles B. OwenProgramming in C31
![Page 216: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/216.jpg)
Example
int x, y;x = 5;y = Square(x);
Address Memory Namey = Square(x);
int Square(int t) {
0xeffffa94 … x
y0xeffffa98{ return t*t
}…
… y0xeffffa98
}…
…
CSE 251 Dr. Charles B. OwenProgramming in C32
![Page 217: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/217.jpg)
Example
int x, y;x = 5;y = Square(x);
Address Memory Namey = Square(x);
int Square(int t) {
0xeffffa94 5 x
y0xeffffa98{ return t*t
}…
… y0xeffffa98
}…
…
CSE 251 Dr. Charles B. OwenProgramming in C33
![Page 218: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/218.jpg)
ExampleThe call Square(x) :creates a variable tcopies the value of x to t
int x, y;x = 5;y = Square(x);
Address Memory Name
copies the value of x to t
y = Square(x);
int Square(int t) 0xeffffa94 5 x
y0xeffffa98{ return t*t
}…
… y0xeffffa98
}…
50xeffffc8c t0xeffffc8c
CSE 251 Dr. Charles B. OwenProgramming in C34
![Page 219: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/219.jpg)
ExampleThe call Square(x) :creates a variable tcopies the value of x to t
int x, y;x = 5;y = Square(x); Address Memory Name
pcalculates t * treturns t
y = Square(x);
int Square(int t)
y
0xeffffa94 5 x
y0xeffffa98{ return t*t
}…
… y0xeffffa98
}…
50xeffffc8c t0xeffffc8c
0xeffffc90 25 temp
CSE 251 Dr. Charles B. OwenProgramming in C35
![Page 220: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/220.jpg)
y=f(x)
Only one valued returned What if we want to return more than one value?
– Solution is to use pointers to variables in the calling function
CSE 251 Dr. Charles B. OwenProgramming in C36
![Page 221: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/221.jpg)
How to do this in C
The approach is to pass the address (using the & operator) of the value to be modified.
We call such a parameter a reference parameter.
Use the * operator to change the reference parameter value
CSE 251 Dr. Charles B. OwenProgramming in C37
![Page 222: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/222.jpg)
Function Reference Params
int val = 10;MyFun(&val);
Name Address Value
val 0xeffffa90 10MyFun(&val);printf(“%d”,val);
void MyFun(int *param){
*param = 27;}
CSE 251 Dr. Charles B. OwenProgramming in C38
![Page 223: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/223.jpg)
Function Reference Params
int val = 10;MyFun(&val);
Name Address Value
val 0xeffffa90 10MyFun(&val);printf(“%d”,val);
void MyFun(int *param){
Name Address Value
param 0xefffea88 0xefffa90 *param = 27;}
param 0xefffea88 0xefffa90
CSE 251 Dr. Charles B. OwenProgramming in C39
![Page 224: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/224.jpg)
Function Reference Params
int val = 10;MyFun(&val);
Name Address Value
val 0xeffffa90 27MyFun(&val);printf(“%d”,val);
void MyFun(int *param){
Name Address Value
param 0xefffea88 0xefffa90 *param = 27;}
param 0xefffea88 0xefffa90
CSE 251 Dr. Charles B. OwenProgramming in C40
![Page 225: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/225.jpg)
Function Reference Params
int val = 10;MyFun(&val);
Name Address Value
val 0xeffffa90 27MyFun(&val);printf(“%d”,val);
void MyFun(int *param){
Prints: 27
The memory used by *param = 27;
}the function is destroyed when it returnsreturns.
CSE 251 Dr. Charles B. OwenProgramming in C41
![Page 226: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/226.jpg)
What will this do different?
int val = 10;MyFun2(val);
Name Address Value
val 0xeffffa90 10MyFun2(val);printf(“%d”,val);
void MyFun2(int param){
param = 27;}
CSE 251 Dr. Charles B. OwenProgramming in C42
![Page 227: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/227.jpg)
Cards program/* C t d d d it *//* Create a random card and suit *//* This will compute a random number from 0 to 3 */suit1 = rand() % 4; This program repeats code. We don’t
like to do that. But, we could not put h d d i f i b/* This will compute a random number from 1 to 13 */
card1 = rand() % 13 + 1;
do
the card draw into a function because a function can only return one value, or so we thought!
do{
/* Create a random card and suit *//* This will compute a random number from 0 to 3 */suit2 = rand() % 4;
/* This will compute a random number from 1 to 13 */card2 = rand() % 13 + 1;card2 = rand() % 13 + 1;
} while(card1 == card2 && suit1 == suit2);
CSE 251 Dr. Charles B. OwenProgramming in C43
![Page 228: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/228.jpg)
Solution, pass by reference using pointers/* Create a random card and suit */DrawCard(&card1, &suit1);
do{
DrawCard(&card2, &suit2);} while(card1 == card2 && suit1 == suit2);
void DrawCard(int *card, int *suit){
/* This will compute a random number from 0 to 3 */
Don’t forget:
*suit← to set the value random number from 0 to 3 /*suit = rand() % 4;
/* This will compute a random number from 1 to 13 */
suit ← to set the value&card1 ← to get the address
Pass with & number from 1 to 13 /*card = rand() % 13 + 1;
}Set with *
CSE 251 Dr. Charles B. OwenProgramming in C44 3
![Page 229: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/229.jpg)
Intro to Arrays
Storing List of Data
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 230: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/230.jpg)
Why ArraysSuppose we want to store theSuppose we want to store the grade for each student in a class
/* Need a variable for each? *// Need a variable for each? /int bob, mary, tom, …;
W bWow, cumbersome…
Easier to have a variable that stores the grades for all students
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 231: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/231.jpg)
An array is a “Chunk of memory”f hAn array is a contiguous piece of memory that can
contain multiple valuesTh l ithi th ti h k bThe values within the contiguous chunk can be addressed individually
Add i
grades 74 59 95 85 71 45 99 82 76
0xeffffa00 0xeffffa04 0xeffffa08 0xeffffa0c 0xeffffa10 0xeffffa14 0xeffffa18 0xeffffa1c 0xeffffa20Address in memory
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 232: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/232.jpg)
Array: “Chunk of memory”
grades 74 59 95 85 71 45 99 82 76
0xeffffa00 0xeffffa04 0xeffffa08 0xeffffa0c 0xeffffa10 0xeffffa14 0xeffffa18 0xeffffa1c 0xeffffa20
Physical address
index 0 1 2 3 4 5 6 7 8
Use an index to access individual elements of the array:grades[0] is 74, grades[1] is 59, grades[2] is 95, and so on
CSE 251 Dr. Charles B. OwenProgramming in C4
![Page 233: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/233.jpg)
Array Declaration
Syntax for declaring array variable: type array_name[capacity];
– type can be any type (int, float, char, …)– array_name is an identifier– capacity is the number of values it can store (indexing starts at 0)starts at 0)
CSE 251 Dr. Charles B. OwenProgramming in C5
![Page 234: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/234.jpg)
ExampleNotice: The first location is location 0 (zero)!
int x[3]; // an array of 3 integers double y[7]; // an array of 7 doubles
Storage, e.g. 4‐bytes per int
X
0 1 2
First Location
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 235: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/235.jpg)
Operations with Arrays
• Assignment: – x[0] = 6; /* Assign 6 to element x[0] */
[2] 3 1 /* A i 3 1 l [2] */– y[2] = 3.1; /* Assign 3.1 to element y[2] */
• AccessAccess– m = x[2];– p = y[0];
• Input/Output: the elements are handled as their types e g– the elements are handled as their types, e.g.
scanf(“%d %lf”, &x[2], &y[3]); printf(“%d %lf\n”,x[0], y[2]); /* output 6 and 3.1 */
CSE 251 Dr. Charles B. OwenProgramming in C7
![Page 236: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/236.jpg)
Arithmetic Operations()int main()
{double x[5];
Variable Declarationfor the arraydouble x[5];
x[0] = 1;
for the array
[ ] ;x[1] = 2;x[2] = x[0] + x[1]; /* X[2] = 3 */x[3] = x[2] / 3; /* X[3] = 1 */x[4] = x[3] * x[2]; /* X[4] = 3 */
}}
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 237: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/237.jpg)
for loops
“for” loops are ideal for processing elements in the array.
int main() {
int i;double values[4] = {3 14 1 0 2 61 5 3};double values[4] = {3.14, 1.0, 2.61, 5.3};double sumValues = 0.0;
for (i=0; i<4; i++) {
sumValues = sumValues + values[i];}printf(“Sum = %lf\n” sumValues);printf( Sum %lf\n , sumValues);
}
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 238: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/238.jpg)
for loops
“for” loops are ideal for processing elements in the array.int main() {
int i;double values[4] = {3 14 1 0 2 61 5 3};double values[4] = {3.14, 1.0, 2.61, 5.3};double sumValues = 0.0;
for (i=0; i<=4; i++)
ERROR! Out of bound
{sumValues = sumValues + values[i];
}printf(“Sum = %lf\n” sumValues);printf( Sum %lf\n , sumValues);
}
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 239: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/239.jpg)
Initialization
Syntax: int X[4] = {2, 4, 7, 9};Behavior: initialize elements starting with leftmost, ehavior: initiali e elements starting with leftmost,i.e. element 0. Remaining elements are initialized to zero. 2 4 7 9X 2 4 7 9X
0 1 2 3
Initialize all to 0: int X[4]={0};
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 240: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/240.jpg)
Exampleint main(){double grades[5] = {90, 87, 65, 92, 100};g [ ] { , , , , };double sum;int i;
printf("The first grade is: % 1f\n" grades[0]);printf("The first grade is: %.1f\n", grades[0]);
sum = 0;for(i=0; i<5; i++){sum += grades[i];
}printf("The average grade is: % 1f\n" sum / 5);printf( The average grade is: %.1f\n , sum / 5);
grades[2] = 70; /* Replaces 65 */grades[3] = grades[4]; /* Replaces 92 with 100 */
}
CSE 251 Dr. Charles B. OwenProgramming in C12 1
![Page 241: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/241.jpg)
Constants for capacityGood programming practice: use #define for constants in your program
For example: #define MaxLimit 25#define MaxLimit 25
int grades[MaxLimit]; f (i t i i M Li it i ){ }for(int i; i<MaxLimit; i++){ };
If size needs to be changed only the capacityIf size needs to be changed, only the capacity “MaxLimit” needs to be changed.
CSE 251 Dr. Charles B. OwenProgramming in C13
![Page 242: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/242.jpg)
Arrays as parameters of functionsi t i ()int main() {
double values[4] = {3.14, 1.0, 2.61, 5.3};[ ] { , , , };
printf(“Sum = %lf\n”, SumValues( values, 4));}}
Suppose we want a function that sums up values of the array
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 243: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/243.jpg)
Arrays as parameters of functionsdouble SumValues(double x[], int numElements){
int i;double result = 0;for (i=0; i < numElements; i++)for (i=0; i < numElements; i++)
result = result + x[i];return result;
“[]” flags the parameter as an array.– ALWAYS passed by reference
return result;}
ALWAYS passed by referenceArray size is passed separately (as numElements)
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 244: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/244.jpg)
Example
Program Behavior1. Create an array of random numbers2. Print unsorted array3. Sort the array
d4. Print sorted array
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 245: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/245.jpg)
Sample output
Array before sortingElement 0 : 58.7000Element 1 : 8.0100Element 2 : 72.3700 p p
The array elements are randomly
Element 3 : 4.6500Element 4 : 58.3000Element 5 : 92.1700Element 6 : 95.3100
generatedElement 7 : 4.3100Element 8 : 68.0200Element 9 : 72.5400
Array after sortingElement 0 : 4.3100Element 1 : 4.6500Element 2 : 8.0100Element 3 : 58.3000Element 4 : 58.7000Element 5 : 68.0200Element 6 : 72.3700Element 7 : 72.5400Element 8 : 92.1700Element 9 : 95.3100
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 246: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/246.jpg)
#include <stdio.h>#include <stdlib.h> Functions are your friends!
void PrintArray( double [], int );void SortArray( double [] int );
Functions are your friends! Make them work and then use them to do work!
void SortArray( double [], int );void Swap (double *, double *);
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 247: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/247.jpg)
#define NumElements 10
int main() {{
int i;double values[NumElements]; /* The array of real numbers */
srand(time(NULL));( ( ));
for (i=0; i < NumElements; i++){
values[i] = (double)(rand() % 10000) / 100.0;[ ] ( )( () ) / ;}
printf("\nArray before sorting\n");PrintArray( values, NumElements );y( , );
SortArray( values, NumElements );
printf("\nArray after sorting\n");p ( y g );PrintArray( values, NumElements );
return 0;}
CSE 251 Dr. Charles B. OwenProgramming in C19
}
![Page 248: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/248.jpg)
#define NumElements 10
int main() {
Array declarationDeclare an array of 10 doubles{
int i;double values[NumElements]; /* The array of real numbers */
srand(time(NULL));
Declare an array of 10 doublesThe indices range from 0 to 9,
i.e. Value[0] to Value[9]( ( ));
for (i=0; i < NumElements; i++){
values[i] = (double)(rand() % 10000) / 100.0;[ ] ( )( () ) / ;}
printf("\nArray before sorting\n");PrintArray( values, NumElements );y( , );
SortArray( values, NumElements );
printf("\nArray after sorting\n");p ( y g );PrintArray( values, NumElements );
return 0;}
CSE 251 Dr. Charles B. OwenProgramming in C20
}
![Page 249: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/249.jpg)
#define NumElements 10
int main() {{
int i;double values[NumElements]; /* The array of real numbers */
srand(time(NULL));( ( ));
for (i=0; i < NumElements; i++){
values[i] = (double)(rand() % 10000) / 100.0;[ ] ( )( () ) / ;}
printf("\nArray before sorting\n");PrintArray( values, NumElements );
Initialize the array with random valuesrand() returns a pseudo random number between 0 andy( , );
SortArray( values, NumElements );
printf("\nArray after sorting\n");
rand() returns a pseudo random number between 0 and RAND_MAXrand()%10000 yields a four-digit integer remainder/100 0 moves the decimal point left 2 placesp ( y g );
PrintArray( values, NumElements );
return 0;}
/100.0 moves the decimal point left 2 placesSo, Values is an array of randomly generated 2-decimal digit numbers between 0.00 and 99.99
CSE 251 Dr. Charles B. OwenProgramming in C21
}
![Page 250: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/250.jpg)
printf("\nArray before sorting\n");PrintArray( values, NumElements );
PrintArray prints the elements of the array in the order they are given to it
SortArray( values, NumElements ); SortArray sorts the elements into ascending order
printf("\nArray after sorting\n");PrintArray( values, NumElements );
order
CSE 251 Dr. Charles B. OwenProgramming in C22
![Page 251: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/251.jpg)
Parameter Passing
void PrintArray( double array[], int size ) {} array is a C array of doubles
array is passed by reference, i.e. any changes to parameter array in the function would change the argument valueschange the argument valuesThe array size is passed as “size”size
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 252: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/252.jpg)
void PrintArray( double array[], int size ) {
i t iint i;
for (i=0; i<size; i++)printf(" Element %5d : %8 4lf\n" i array[i]);
array[i] is a double so the output needs to be “%f”
printf( Element %5d : %8.4lf\n ,i, array[i]);}
array[i] is a double so the output needs to be %f
The range of the “for” statement walks through theThe range of the for statement walks through the whole array from element 0 to element N‐1.
CSE 251 Dr. Charles B. OwenProgramming in C24
![Page 253: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/253.jpg)
Sorting Arrayvoid SortArray( double array[], int size){}}
array is an array of doubles.
i d b f i harray is passed by reference, i.e. changes to parameter array change the argument valuesThere is no size restriction on array so the size is passed as “size”.
CSE 251 Dr. Charles B. OwenProgramming in C25
![Page 254: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/254.jpg)
Selection Sort8 2 6 4array
0 1 2 3
CSE 251 Dr. Charles B. OwenProgramming in C26
![Page 255: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/255.jpg)
Selection Sort8 2 6 4array
0 1 2 3
Search from array[0] to array[3] to find the smallest number
CSE 251 Dr. Charles B. OwenProgramming in C27
![Page 256: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/256.jpg)
Selection SortSearch from array[0] to array[3]
8 2 6 4array
0 1 2 3
y[ ] y[ ]to find the smallest number andswap it with array[0]
2 8 6 4
0 1 2 30 1 2 3
CSE 251 Dr. Charles B. OwenProgramming in C28
![Page 257: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/257.jpg)
Selection Sort8 2 6 4array
0 1 2 3
2 8 6 4
0 1 2 3
Search from array[1] to array[3] to find the smallest number
0 1 2 3
CSE 251 Dr. Charles B. OwenProgramming in C29
![Page 258: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/258.jpg)
Selection Sort8 2 6 4array
0 1 2 3
2 8 6 4
0 1 2 3
Search from array[1] to array[3] to find the smallest number andswap it with array[1]0 1 2 3 swap it with array[1]
2 4 6 8
0 1 2 3
CSE 251 Dr. Charles B. OwenProgramming in C30
![Page 259: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/259.jpg)
Selection Sort8 2 6 4array
0 1 2 3
2 8 6 4
0 1 2 30 1 2 3
Search from array[2] to array[3] to find the smallest number and2 4 6 8swap it with array[2]
0 1 2 3
CSE 251 Dr. Charles B. OwenProgramming in C31
![Page 260: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/260.jpg)
Selection Sort8 2 6 4array
0 1 2 3
2 8 6 4
0 1 2 30 1 2 3
Search from array[2] to array[3] to find the smallest number and 2 4 6 8swap it with array[2]
0 1 2 3
2 4 6 8 A d d !2 4 6 8
0 1 2 3
And we are done!
CSE 251 Dr. Charles B. OwenProgramming in C32
![Page 261: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/261.jpg)
Selection Sort How many iterations are there?Answer: 3 ( from i = 0 to i = 2)
8 2 6 4array
0 1 2 3
Answer: 3 ( from i 0 to i 2)
More generally, if number of elements in the array is size
2 8 6 4
0 1 2 3
elements in the array is size,you need to iterate fromi = 0 to i = size ‐ 2
0 1 2 3
2 4 6 8
0 1 2 3
2 4 6 82 4 6 8
0 1 2 3
CSE 251 Dr. Charles B. OwenProgramming in C33
![Page 262: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/262.jpg)
Selection Sort At every iteration i, you need to search f [i] t [ i 1] tfrom array[i] to array[size – 1] to find the smallest element
How to do this?
2 8 6 4
0 1 2 3How to do this?
CSE 251 Dr. Charles B. OwenProgramming in C34
![Page 263: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/263.jpg)
Selection Sort At every iteration i, you need to search from array[i] to array[size – 1] to
2 8 6 4
0 1 2 3
find the smallest element
How to do this?
Use a variable called min to locate the index of the smallest elementmin 3
CSE 251 Dr. Charles B. OwenProgramming in C35
![Page 264: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/264.jpg)
Selection SortAssume current iteration i = 1
2 8 6 4
0 1 2 3
Initialize min = i
min 1
CSE 251 Dr. Charles B. OwenProgramming in C36
![Page 265: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/265.jpg)
Selection Sort Assume current iteration i = 1
Initialize min = I
ji
2 8 6 4
0 1 2 3
Initialize min = I Set j = i + 1Compare array(min) to array(j)
min 1
CSE 251 Dr. Charles B. OwenProgramming in C37
![Page 266: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/266.jpg)
Selection Sort
j Assume current iteration i = 1Initialize min = iSet j = i + 1
i
2 8 6 4
0 1 2 3
Set j = i + 1Compare array(min) to array(j)If array(j) < array(min)
set min to j
min 2 Because 6 < 8,min is now set to 2min is now set to 2
CSE 251 Dr. Charles B. OwenProgramming in C38
![Page 267: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/267.jpg)
Selection Sort
jIncrement j
i
2 8 6 4
0 1 2 3
Compare array(min) to array(j)
min 2
CSE 251 Dr. Charles B. OwenProgramming in C39
![Page 268: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/268.jpg)
Selection Sort
j Increment jCompare array(min) to array(j)If array(j) < array(min)
i
2 8 6 4
0 1 2 3
If array(j) < array(min)set min to j
min 3
Because 4 < 6,min is now set to 3
CSE 251 Dr. Charles B. OwenProgramming in C40
![Page 269: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/269.jpg)
Selection Sort
j
S (i) ith ( i )
i
2 8 6 4
0 1 2 3
Swap array(i) with array(min)
min 3
CSE 251 Dr. Charles B. OwenProgramming in C41
![Page 270: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/270.jpg)
SortArrayvoid SortArray( double array[], int size){
i t i j iint i, j, min;
for (i=0; i < size‐1; i++) {{
min = i;for (j=i+1; j<size; j++) {{
if (array[j] < array[min]){
min = j;j}
}
Swap(&array[i], &array[min]); }
}
CSE 251 Dr. Charles B. OwenProgramming in C42
![Page 271: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/271.jpg)
Swap void Swap (double *a, double *b) {{double temp = *a;*a = *b;*b = temp;
}
CSE 251 Dr. Charles B. OwenProgramming in C43
![Page 272: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/272.jpg)
Swap void Swap (double *a, double *b) {{double temp = *a;*a = *b;*b = temp;
}Note: We’re passing two elements of the array; not passing the entire array
So, we CANNOT declare it as
void Swap(double a, double b)
void Swap(double a[], double b[])
CSE 251 Dr. Charles B. OwenProgramming in C44 2
![Page 273: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/273.jpg)
Strings and File I/O
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 274: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/274.jpg)
Character Type: char
In C, characters are indicated by single quotes:
The type is char for charmyChar;myChar = 'a';
f(“ h \ ” h )
ypone (1) character
printf(“myChar is %c\n”, myChar);
%c is the formal specifier for a char
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 275: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/275.jpg)
String
A string is an array of characters, it is indicated by double quotes:
"this is a string"
But you can’t use an assignment operator to assign a string to a character arraychar myChar[80]; /* array of chars */myChar[4] = ‘a’; /* OK */
Ch “thi i t i ” /* NOT OK */myChar = “this is a string”; /* NOT OK */
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 276: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/276.jpg)
String
A null (‘\0’) character is placed to mark the end of each string
t sisih a s \0gnirt
String functions use ‘\0’ to locate end of string (so you don’t have to pass string length as argument to the functions)
CSE 251 Dr. Charles B. OwenProgramming in C4
![Page 277: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/277.jpg)
Initializing a Stringh [ ] {‘ ’ ’b’ ’ ’ ’d’ } myStrchar myStr[5] = {‘a’, ’b’, ’c’, ’d’, 0};printf(“myStr is %s\n”, myStr);
myStr
\0dcba
– Array size has exactly 5 elements– A terminating ‘\0’ character at the endA terminating \0 character at the end (in ASCII, char ‘\0’ is equivalent to int 0)
– Will print: “myStr is abcd”
CSE 251 Dr. Charles B. OwenProgramming in C5
![Page 278: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/278.jpg)
Another waymyStr
char myStr[10]=“birdbath”;printf(“myStr is %s\n”, myStr);
b i r \0htabd
– Ok to use assignment only to initialize string– myStr is an array of 10 characters (but only the first 8 y y ( yelements used to store the word)
– a ‘\0’ is added to the end automatically (so 9 elements in th i d)the array are occupied)
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 279: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/279.jpg)
Better waymyStr
char myStr[]=“birdbath”;printf(“myStr is %s\n”, myStr);
b i r \0htabd
– ‘\0’ is added automatically to the end of myStrS i ll t d t ti ll t h ld tl h t– Space is allocated automatically to hold exactly what we need (9 locations, including ‘\0’)
CSE 251 Dr. Charles B. OwenProgramming in C7
![Page 280: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/280.jpg)
printf for Stringschar myStr[] = “abc123”;
Output:Output: – Use %s to print the entire string:
printf(“%s\n”,myStr); /* outputs abc123 *//* ‘\0’ is not printed */
– Use %c to print a character:printf(“%c\n”myStr[1]); /* outputs: b */printf( %c\n ,myStr[1]); /* outputs: b */
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 281: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/281.jpg)
String input
There are several functions available
Part of the stdio.h library.
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 282: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/282.jpg)
scanf
scanf reads up to the first white space, ignores the stuff typed in after that. Be careful when using it.
char myStr[10];i f(“E i “)printf(“Enter a string: “);
scanf(“%s”, myStr);printf(“You entered %s\n\n” myStr)printf( You entered %s\n\n , myStr)
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 283: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/283.jpg)
scanf ‐ safer
Use %[width]s to copy only up to a maximum number of character. But, does not append the ‘\0’
char myStr[10];i f(“E i “)printf(“Enter a string: “);
scanf(“%9s”, myStr);myStr[9] = ‘\0’; /* Do this yourself just in case */myStr[9] = \0 ; / Do this yourself just in case / printf(“You entered %s\n\n”, myStr)
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 284: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/284.jpg)
getchar
getchar will fetch one (1) character from the input stream
char myChar;printf(“Enter a character: “);
Ch h ()myChar = getchar();printf(“You entered %c\n\n”, myChar);
CSE 251 Dr. Charles B. OwenProgramming in C12
![Page 285: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/285.jpg)
fgets
char * fgets(charArray, lengthLimit, filePtr)
• fetches a whole line, up to the size limit or when it sees a new line
• It will add a ‘\0’ at the end of string• Example• Example:
char myStr[80];fgets(myStr, 80, stdin); // fetch from console
• Returns a NULL if something went wrong, otherwise a pointer to the array
The functions that start with “f” work with any source of input. stdin is the C “Standard Input”.
CSE 251 Dr. Charles B. OwenProgramming in C13
p
![Page 286: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/286.jpg)
#include<stdio.h>#include<string.h>
int main () {int inputLength=20int cnt=0;int cnt 0;char str1[20], str2[20];
printf("\nEnter a string: ");fgets(str1, inputLength, stdin);
Make sure you’re clear the difference between fgetsand scanfg ( , p g , );
printf("You entered %s\n",str1);
printf(“Enter another string: ");scanf("%s",str2);
and scanf
printf("You entered %s\n",str2);}
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 287: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/287.jpg)
Note the extra new line when using fgets
str1 (read using fgets)
t sisih a s \ngnirt \0
str1 (read using fgets)
str2 (read using scanf)
t \0sih
CSE 251 Dr. Charles B. OwenProgramming in C15 1
![Page 288: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/288.jpg)
String manipulation functions #include <string.h>
strcpy – Copies a stringstrcat – Concatenates two stringsstrlen – Returns the length of a stringstrcmp – Compares two strings
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 289: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/289.jpg)
string copy (strcpy) strcpy(destString, srcString);
char [] strcpy (char dest[], const char src[]);
• copy string contents from src (2nd arg) to dest (1starg) including ‘\0’arg) including \0
• dest is changed, src unmodified (but can do some weird things)
• returns a pointer to the modified dest array
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 290: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/290.jpg)
string copy (strcpy)
char [] strcpy (char dest[], const char src[]);
• There is no error checking!– If dest array is shorter than src array, no errors. Weird things could happen but no compile errors and often no runtimecould happen, but no compile errors and often no runtime errors
– Tracking these “bugs” down is very hard!g g y
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 291: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/291.jpg)
Safer version of string copy strncpy(destString, srcString, 80);
char [] strncpy (char dest[], const char src[], int N);
• copies at most N characters from src to dest (or up to ‘\0’
• If length of src is greater than N, copies only the first N characters
• If length of src is less than N, pad the remaining elements in dest with ‘\0’
Does not copy the ‘\0’ if the string length is >= N
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 292: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/292.jpg)
concatenation (strcat)
char [] strcat(char dest[], const char src[])
• contents of src are added to the end of dest. • dest is changed, src is not• ‘\0’ added to the end of dest• return a pointer to dest• no bounds check (again, this is C)
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 293: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/293.jpg)
comparison (strcmp)
int strcmp (const char s1[],const char s2[]);
• Compares 2 strings– if s1 precedes s2, return value is less than 0– if s2 precedes s1, return value is greater than 0– if s1 equal to s2, return value is 0
C i i b d l i hi d (ASCII• Comparison is based on lexicographic order (ASCII order) – e.g., “a” < “b”
CSE 251 Dr. Charles B. OwenProgramming in C21
![Page 294: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/294.jpg)
#include <stdio.h>#include <string.h>
int main() {printf("strcmp(\"a\",\"b\"): %d\n", strcmp("a","b"));printf("strcmp(\"b\" \"a\"): %d\n" strcmp("b" "a"));printf( strcmp(\ b\ ,\ a\ ): %d\n , strcmp( b , a ));printf(“strcmp(\"a\",\"a\"): %d\n", strcmp("a","a"));printf("strcmp(\"2\",\"3\"): %d\n", strcmp("2","3"));printf("strcmp(\"2\",\"10\"): %d\n", strcmp("2","10"));
}
Lexicographic ordering is not the same as ordering numbers
CSE 251 Dr. Charles B. OwenProgramming in C22
![Page 295: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/295.jpg)
Reversing a string
Input: Math is funOutput: nuf si htaM
How would you do this?
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 296: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/296.jpg)
front
backvoid Reverse(char str[] ){int front = 0; int back = strlen(str) ‐ 1;int back = strlen(str) ‐ 1; char t; /* A temporary place to put a character */
while (front < back){t = str[front];str[front] = str[back];str[back] = t;str[back] t;front++;back‐‐;
}}
CSE 251 Dr. Charles B. OwenProgramming in C24
}
2
![Page 297: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/297.jpg)
Built‐in functions for characters#include <ctype.h>
Built in functions for characters
• These all return boolean (1/0). – isalnum(c): is c alphanumeric?– isalpha(c): is c alphabetic?– isdigit(c): is c a digit?– iscntrl(c): is c a control character?islower(c): is c lower case?– islower(c): is c lower case?
– isupper(c): is c upper case?– ispunct(c): is c a punctuation character, that is a printableispunct(c): is c a punctuation character, that is a printable character that is neither a space nor an alphanumeric character
CSE 251 Dr. Charles B. OwenProgramming in C25
![Page 298: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/298.jpg)
converters
• char tolower(c)– return the character as lower case
• char toupper(c)– return the character as upper case
CSE 251 Dr. Charles B. OwenProgramming in C26
![Page 299: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/299.jpg)
File IO
How to write programs to read from or write to filesor write to filesSo far, we’ve only looked at how to read/write to the consoleread/write to the console
CSE 251 Dr. Charles B. OwenProgramming in C27
![Page 300: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/300.jpg)
Open files
• Files are opened with fopen– the fopen function is part of stdio.h
– It takes two args: a string (the name of a file) and a mode string (how the file is opened).string (how the file is opened).
– It returns a file pointer• fptr = fopen(“myfile.txt”,”r”);
CSE 251 Dr. Charles B. OwenProgramming in C28
![Page 301: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/301.jpg)
Declare and assign file pointer
• fopen returns a NULL pointer if it cannot perform the operation
FILE *infile;inFile fopen(“file t t” ”r”)inFile = fopen(“file.txt”,”r”);if (inFile == NULL)// bad file opening
CSE 251 Dr. Charles B. OwenProgramming in C29
![Page 302: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/302.jpg)
file modes
• “r”, read from the beginning of an existing file• “w”, make an empty file (wipe out old contents), start writing.
• “a”, find an existing file, start writing at the end of that file
CSE 251 Dr. Charles B. OwenProgramming in C30
![Page 303: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/303.jpg)
Close files
• Files are closed with fclose– the fclose function is part of stdio.h
– It takes one argument: pointer to the file to be closedpointer to the file to be closed
fclose(fptr);
CSE 251 Dr. Charles B. OwenProgramming in C31
![Page 304: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/304.jpg)
The “f” functions
• most of the I/O functions we know have an equivalent “f” version to work with a file.
• The first argument is the file pointer value of an opened file– fprintf(filePtr, “format string”, values)– fscanf(filePtr, “format string, addresses)f f(fil Pt ) d f fil t t– feof(filePtr) end of file test
CSE 251 Dr. Charles B. OwenProgramming in C32 3
![Page 305: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/305.jpg)
States and State Machines
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 306: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/306.jpg)
What is this for?
State machines are commonly used in…
Embedded Systems
Factory/Process Controls
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 307: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/307.jpg)
State
State – An abstraction of the current status of a system. States are assigned names.
Waiting for a KeypressWaiting for Elvis
Paper JammedBattery is Below LimitWaiting for Elvis
Raising Firearm to FireCellphone is DialingD O i
Battery is Below LimitPower is OnDoor Open
Door Opening Prius Accelerator Stuck
Verbs with “ing” Statement of condition
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 308: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/308.jpg)
States in a Garage Door Are there any more states?
DoorClosed
DoorOpen
CSE 251 Dr. Charles B. OwenProgramming in C4 A
![Page 309: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/309.jpg)
More States
DoorOpening
DoorClosing
CSE 251 Dr. Charles B. OwenProgramming in C5
![Page 310: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/310.jpg)
How we will express this in a program
/* Our possible garage door states */#define DoorClosed 1#define DoorOpening 2
int main(){i D Cl d#define DoorOpening 2
#define DoorOpen 3#define DoorClosing 4
int state = DoorClosed;…
In themain functionAbove main in our program
In the main function
Why do we care? We do different things y gdepending on the current state. What does the button do in each state?
CSE 251 Dr. Charles B. OwenProgramming in C6 B
![Page 311: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/311.jpg)
Naming Conventions ‐ States
We will usually name states with camel‐case and a capital first letter. We’ll use #defines in our programs for state names.
WaitingForKeypressWaitingForElvis
PaperJammedl i iWaitingForElvis
RaisingFirearmCellphoneDialing
BatteryBelowLimitPowerOnDoorOpen
DoorOpeningp
PriusAccelStuck
Verbs with “ing” Statement of conditionVerbs with ing Statement of condition
CSE 251 Dr. Charles B. OwenProgramming in C7
![Page 312: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/312.jpg)
EventsA i i i I iAn event is an occurrence in time. It is considered atomic and instantaneous.
Left mouse button pressedKey pressed
Paper is jammedMessage has timed outy p
Elvis has left the buildingFlight 529 has landedPower turned on
Message has timed out10 seconds has elapsedBattery is below limit
P j t 2 i dPower turned on Project 2 is due
Past tense verbs Onset of condition
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 313: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/313.jpg)
Events vs. State
clickedOnScreen screenSlideDone clickedOnScreen screenSlideDone
IdleClosed IdleOpenSlidingOpen SlidingClosed IdleClosed
An event is what causes us to change from state to state.
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 314: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/314.jpg)
State Diagrams State diagrams describe what we will implement in code as a state machine.
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 315: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/315.jpg)
State Diagrams
Initial State
State
Transition
Event
Transition
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 316: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/316.jpg)
Starting out State Machine
int main(){i D Cl dint state = DoorClosed;…
CSE 251 Dr. Charles B. OwenProgramming in C12 C
![Page 317: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/317.jpg)
A Control Loopint main(){int state = DoorClosed;int state = DoorClosed;
printf("Garage Startup\n");GarageStartup();
A continuous loop in a controls application that controls the
t Ri ht l iwhile(IsGarageRunning()){
system. Right now our loop is doing nothing. We’ll want to add code to make our garage door
}
printf("Garage Shutdown\n");G Sh d ()
work.
GarageShutdown();return 0;
}
CSE 251 Dr. Charles B. OwenProgramming in C13
![Page 318: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/318.jpg)
Important Idea
We do something different depending on the state we are in. It makes sense to create a function for each state.
void StateDoorClosed(int *state){ Note the pointer. We
th t t b} pass the state by reference. It is an in/out parameter
What should happen when we are in the DoorClosed state?
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 319: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/319.jpg)
DoorClosed state…
If the button is pressed:Start the motorGo to the DoorOpening statep g
otherwise:Do nothing…
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 320: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/320.jpg)
DoorClosed state…id St t D Cl d(i t * t t )
If the button is pressed:Start the motorGo to the DoorOpening state
void StateDoorClosed(int *state){if(WasButtonPressed()){p g
otherwise:Do nothing…
SetMotorPower(1);*state = DoorOpening;
}}}
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 321: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/321.jpg)
The Control Loop – Handling Stateswhile(IsGarageRunning()){switch(state){
We will put a switch statement in our control
{case DoorClosed:StateDoorClosed(&state);break;
loop to handle the states.
}
}
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 322: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/322.jpg)
We now have this…
Trigger / Activity
Trigger is what causes the transition Activitythe transition. Activity is something that happens when the transition occurs.
This is a simple 2‐state statement.
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 323: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/323.jpg)
What happenswhile(IsGarageRunning()){switch(state){ void StateDoorClosed(int *state){case DoorClosed:StateDoorClosed(&state);break;
void StateDoorClosed(int state){if(WasButtonPressed()){
}
}
SetMotorPower(1);*state = DoorOpening;
}}
Control LoopState Function}
The control loop runs continuously (1000 times per second in this program). Each time it calls a function for the current state. That state function decides if we need to change the state and does anything else we need to do while in that state.
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 324: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/324.jpg)
A Garage Door Opener
CSE 251 Dr. Charles B. OwenProgramming in C20 1
![Page 325: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/325.jpg)
Pointers, Arrays, Multidimensional Arrays
• Pointers versus arrays– Lots of similarities
• How to deal with 2D, 3D, multidimensional arrays (for storing matrices and other 2D or 3D data!)(for storing matrices and other 2D or 3D data!)
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 326: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/326.jpg)
Review: PointersAddress Memory Name
Pointers are variables that store memory addresses
Address Memory
0xeffffa94
Name
a15
int a = 15;
0xeffffa98 b0xeffffa94
int a 15;int *b = &a;
printf(“%x %x %d\n”, b, &b, *b);// prints effffa94 effffa98 15// prints effffa94 effffa98 15
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 327: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/327.jpg)
int number; int *ptr = &number;
Using pointers in scanf function
Read & as “at”
printf(“Enter an integer: ”);scanf(“%d” &number);
scanf functionas at
scanf( %d , &number);printf(“Enter another integer: “);scanf(“%d”, ptr);
Don’t have to put & before ptr. It’s already an “at”
printf(“Number = %d, *ptr = %d\n”, number, *ptr);
already an at .
Example output:
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 328: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/328.jpg)
int multiply( int *, int);
int main()
Passing pointers (addresses) toint main()
{int number = 3;int *ptr &n mber;
(addresses) to functions
int *ptr = &number;printf(“1: %d\n”, multiply( &number, 2 ) );printf(“2: %d\n”, multiply( ptr, 3 ) );
}}
int multiply (int *a, int factor) {{
return (*a) * factor;}
CSE 251 Dr. Charles B. OwenProgramming in C4
![Page 329: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/329.jpg)
Review: Arrays
An array is a contiguous chunk of memory to store multiple values
int grades[]={74,59,95,85,71,45,99,82,76};
0xeffffa00 0xeffffa04 0xeffffa08 0xeffffa0c 0xeffffa10 0xeffffa14 0xeffffa18 0xeffffa1c 0xeffffa20
grades 74 59 95 85 71 45 99 82 76
index 0 1 2 3 4 5 6 7 8
CSE 251 Dr. Charles B. OwenProgramming in C5 A
![Page 330: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/330.jpg)
int sumArray( int [], int);
int main() Passing arrays to functions{
int list[] = {1, 2, 3, 4};printf(“Sum = %d\n”, sumArray( list , 4 ));
functions
}
int sumArray (int list[], int arraySize) {{
int sumvalue = 0;for (int i=0; i<arraySize; i++)
sumvalue += list[i];sumvalue += list[i];return sumvalue;
}
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 331: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/331.jpg)
Array Nameffe2de0c ffe2de10 ffe2de14 ffe2de18The array name is a
pointer to the first l t f th
1 2 3 4
[1] [2] [3][0]
listffe2de0c ffe2de10 ffe2de14 ffe2de18
element of the array [1] [2] [3][0]
int list[]={1,2,3,4};
Output: ffe2de0c ffe2de0c 1
int list[] {1,2,3,4};printf(“%x, %x, %d”, list, &list[0], *list);
Output: ffe2de0c ffe2de0c 1
CSE 251 Dr. Charles B. OwenProgramming in C7
![Page 332: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/332.jpg)
Pointers and Arrays p
int *p, int list[] {1 2 3 4};
1 2 3 4
[1] [2] [3][0]
list
int list[]={1,2,3,4}; p = list; /* equivalent to p = &list[0] */printf(“%d\n”, *p); /* prints the value “1” */
[ ] [ ] [ ][ ]
YYou can use apointer to access
the array
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 333: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/333.jpg)
Pointer and [] P
Any pointer to a block of memory can use the [] syntax, even if it is
not declared as an array! 1 2 3 4Listnot declared as an array!
[1] [2] [3][0]
int *p, pint list[]={1,2,3,4}; p = list;i tf(“%d\ ” [2]) // i t 3
int *v; and int v[]; /* Mean the same thing */
printf(“%d\n”, p[2]); // prints 3
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 334: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/334.jpg)
Array indexing [] *list – Contents pointed to by list*(list + 2) – Contents at list[2]
Indexing an array is just a way
list
ff 2d 0 ff 2d 10 ff 2d 14 ff 2d 18
list + 2
of finding a particular address in that block1 2 3 4
[1] [2] [3][0]
ffe2de0c ffe2de10 ffe2de14 ffe2de18
[1] [2] [3][0]
int list[] = {1 2 3 4} // array of 4 intsint list[] = {1,2,3,4} // array of 4 intsprintf(“%d”, list[2]);
This is equivalent toprintf(“%d”,*(list+2));printf( %d , (list+2));
CSE 251 Dr. Charles B. OwenProgramming in C10 B
![Page 335: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/335.jpg)
Pointer Arithmetic
When we add to a pointer, such as (p + 1), we don’t literally add 1 to the pointer address
Instead we add one “address” to the pointer
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 336: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/336.jpg)
Pointer Arithmeticint list[] = {1, 2, 3, 4};int *p = list; /* same as p = &list[0] */printf(“%x”,p); /* prints ffe2de0c */
p
printf( %x ,p); / prints ffe2de0c /
ffe2de0c ffe2de10 ffe2de14 ffe2de18
1 2 3 4
CSE 251 Dr. Charles B. OwenProgramming in C12
![Page 337: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/337.jpg)
Pointer Arithmeticint list[] = {1, 2, 3, 4};int *p = list; /* same as p = &list[0] */printf(“%x”,p); /* prints ffe2de0c */printf( %x ,p); / prints ffe2de0c /p = p + 1; /* p increases by 4 */printf(“%x”,p); /* prints ffe2de10 */
pThink of pointer arithmetic as add
1 2 3 4
ffe2de0c ffe2de10 ffe2de14 ffe2de181 “location” instead of one byte or addressbyte or address.
CSE 251 Dr. Charles B. OwenProgramming in C13
![Page 338: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/338.jpg)
Pointer Arithmeticd bl li t2[] {1 0 2 0 3 0}double list2[] = {1.0, 2.0, 3.0};double *p = list2; /* same as p = &list2[0] */printf(“%x”, p); /* prints ffe2de0c */
p
p ( p) p
1.0
ffe2de0c ffe2de10 ffe2de14 ffe2de18
2.0 3.0
ffe2de1c ffe2de20
1.0 2.0 3.0
CSE 251 Dr. Charles B. OwenProgramming in C14 C
![Page 339: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/339.jpg)
Pointer Arithmeticd bl li t2[] {1 0 2 0 3 0}double list2[] = {1.0, 2.0, 3.0};double *p = list2; /* same as p = &list2[0] */printf(“%x”,p); /* prints ffe2de0c */p ( p) pp = p + 1; /* P increases by 8 bytes */printf(“%x”,p); /* prints ffe2de14 */
P
1.0
ffe2de0c ffe2de10 ffe2de14 ffe2de18
2.0 3.0
ffe2de1c ffe2de20
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 340: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/340.jpg)
Pointer Arithmetic on Arrays*(l ) f h l h• *(list+1) references the next element in the array (equivalent to list[1])
• Be careful: *(++list) works too but now we have lost our pointer to the beginning of the array!!!our pointer to the beginning of the array!!!– Equivalent to: list = list + 1; *list;
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 341: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/341.jpg)
sizeof() operatori t i
Returns the number of bytes needed toint i;
int *ptr4i = &i;int IntArray[] = {1, 2, 3, 4, 5};double j;
of bytes needed to store a variable or a data typedouble j;
double *ptr4j = &j;double doubleArray[] = {1.0, 2.0, 3.0, 4.0,5.0};
i tf("Si f i t i %d b t \ " i f(i t))
data type
printf("Sizeof integer is %d bytes\n", sizeof(int));printf("Sizeof double is %d bytes\n", sizeof(double));
printf("Sizeof i is %d bytes\n", sizeof(i));printf("Sizeof pointer for i is %d bytes\n", sizeof(ptr4i));
printf("Sizeof j is %d bytes\n", sizeof(j));printf("Sizeof pointer for j is %d bytes\n", sizeof(ptr4j));
printf("Sizeof intArray is %d bytes\n", sizeof(intArray));printf("Sizeof doubleArray is %d bytes\n", sizeof(doubleArray));
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 342: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/342.jpg)
sizeof() operator
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 343: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/343.jpg)
When we pass an arrayWh i thWhen we pass an array, we are passing the array address
int sumArray( int [ ] int);int sumArray( int [ ], int);
int main() {{int list[] = {1, 2,3, 4); …
A ( li 4 )sumArray( list , 4 );
…
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 344: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/344.jpg)
When we pass an array
This will work too (because array name is a pointer to the beginning of the array)
int sumArray( int *, int);int main() {{int list[] = {1, 2,3, 4); …sumArray( list , 4 );
…
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 345: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/345.jpg)
When we pass an array
• But this DOES NOT work!
int sumArray( int *, int);y( , );int main() {int *list {1 2 3 4);int *list = {1, 2, 3, 4); …sumArray( list , 4 );
…
CSE 251 Dr. Charles B. OwenProgramming in C21
![Page 346: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/346.jpg)
Pointers *list – Contents pointed to by list*(list + 2) – Contents at list[2]
Indexing an array is just a
list
ff 2d 0 ff 2d 10 ff 2d 14 ff 2d 18
list + 2
way of finding a particular address in that block1 2 3 4
[1] [2] [3][0]
ffe2de0c ffe2de10 ffe2de14 ffe2de18
[1] [2] [3][0]
int list[] = {1 2 3 4} // array of 4 intsint list[] = {1,2,3,4} // array of 4 intsprintf(“%d”, list[2]);
This is equivalent toprintf(“%d”,*(list+2));printf( %d , (list+2));
CSE 251 Dr. Charles B. OwenProgramming in C22 1
![Page 347: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/347.jpg)
2‐D Arrays
int cave[ArraySize][ArraySize];
Column
1 2 3 40
0 1 2 3
Column
1 2 3 45 6 7 89 10 11 12
0
1
2Row
9 10 11 1213 14 15 16
2
3
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 348: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/348.jpg)
2D Arraysint myMatrix[3][4] = { {1 2 3 4} {5 6 7 8} {9 10 11 12} };int myMatrix[3][4] = { {1,2,3,4},{5,6,7,8},{9,10,11,12} };
0 1 2 3
Column
1 2 3 45 6 7 8
myMatrix[0][1] → 2
0 1 2 3
0
1Row 5 6 7 89 10 11 12
M t i [2][3] 12
2
Row
myMatrix[2][3] → 12myMatrix[row][col]
CSE 251 Dr. Charles B. OwenProgramming in C24
![Page 349: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/349.jpg)
Physically, in one block of memoryint myMatrix[2][4] = { {1,2,3,4},{5,6,7,8} };
ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28
1 2 3 4 5 6 7 8ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28
Array elements are stored in row major order
row 1 row 2
Array elements are stored in row major orderRow 1 first, followed by row2, row3, and so on
CSE 251 Dr. Charles B. OwenProgramming in C25
![Page 350: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/350.jpg)
2D Array Name and Addresses[ ][ ] { { } { } }
ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28
int myMatrix[2][4] = { {1,2,3,4},{5,6,7,8} };
1 2 3 4 5 6 7 8ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de28
myMatrix: pointer to the first element of the 2D arraymyMatrix[0]: pointer to the first row of the 2D arraymyMatrix[1]: pointer to the second row of the 2D array*myMatrix[1] is the address of element myMatrix[1][0]
CSE 251 Dr. Charles B. OwenProgramming in C26
![Page 351: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/351.jpg)
Accessing 2D Array Elements[ ][ ] { { } { } }int myMatrix[2][4] = { {1,2,3,4} , {5,6,7,8} };
1 2 3 4 5 6 7 81 2 3 4 5 6 7 8
Indexing: myMatrix[i][j] is same asg y [ ][j]*(myMatrix[i] + j)(*(myMatrix + i))[j]*((*(myMatrix + i)) + j)*((*(myMatrix + i)) + j)*(&myMatrix[0][0] + 4*i + j)
CSE 251 Dr. Charles B. OwenProgramming in C27
![Page 352: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/352.jpg)
Declaration#define ROWS 3#define COLS 5
int table[ROWS][COLS];
void display (table);
CSE 251 Dr. Charles B. OwenProgramming in C28
![Page 353: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/353.jpg)
void display( int x[ROWS][COLS] ) {
2D Arrays often require nested loops – two
for (int i=0; i < ROWS; i++) {
for (int j=0; j < COLS; j++ )
pvariables
( j ; j ; j ){
printf(" x[%d][%d]: %d", i, j, x[i][j]);}}printf("\n");
}printf("\n");
}
CSE 251 Dr. Charles B. OwenProgramming in C29
![Page 354: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/354.jpg)
Table A = { {13, 22, 9, 23},{17, 5, 24, 31, 55},{4 19 29 41 61} };
13 22 9 23 ?17 5 24 31 55{4, 19, 29, 41, 61} };4 19 29 41 61
Table B = {1, 2, 3, 4,5, 6, 7, 8, 9, 10 11 12 13 14 };
1 2 3 4 56 7 8 9 1011 12 13 14 ?10, 11, 12, 13, 14 }; 11 12 13 14 ?
CSE 251 Dr. Charles B. OwenProgramming in C30
![Page 355: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/355.jpg)
passing 2d arrays
In passing a multi‐dimensional array, the first array size does not have to be specified. The second (and any subsequent) dimensions must be given!
int myFun(int list[][10]);
CSE 251 Dr. Charles B. OwenProgramming in C31
![Page 356: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/356.jpg)
#define ROWS 3#define COLS 5
int addMatrix( int [ ][COLS] );int addMatrix( int [ ][COLS] );
int main() {int a[][COLS] = { {13 22 9 23 12} {17 5 24 31 55} {4 19 29 41 61} };int a[][COLS] = { {13, 22, 9, 23, 12}, {17, 5, 24, 31, 55}, {4, 19, 29, 41, 61} };printf(“Sum = %d\n”, addMatrix( a ) );
}
int addMatrix( int t[ ][COLS] )int addMatrix( int t[ ][COLS] ) {int i, j, sum = 0;for (i=0; i<ROWS; i++)for (i=0; i<ROWS; i++) for (j=0; j<COLS; j++) sum += t[i][j];
return sum;;}
CSE 251 Dr. Charles B. OwenProgramming in C32 1
![Page 357: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/357.jpg)
Compilation and Makefiles
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 358: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/358.jpg)
Lecture Outline• What is gcc?
– What are the different switches available?
• What is a Makefile?
• Exercise:– Take an existing file, split it into multiple separateTake an existing file, split it into multiple separate programs, and write a Makefile to simplify compilation of the files
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 359: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/359.jpg)
gcc is not a single program
gcc is a conglomeration of programs that work together to
make an executable filemake an executable file
We need to know what it does and how we can better control it.and how we can better control it.
In particular, we would like to be able to make multiple, separate p , p
programs which can be combined into one executable
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 360: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/360.jpg)
What does gcc do?#i l d tdi hd #include <stdio.h>#include <math.h>
#define NumIter 5
code.c
int main() {int i;
C sourcefile
int i;for (i=1; i<=NumIter; i++)
printf(“PI^%d is %f\n”, i, pow(M_PI, i));}
CSE 251 Dr. Charles B. OwenProgramming in C4
![Page 361: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/361.jpg)
What does gcc do? ExpandedC code
C ilpreprocessor(# commands)
Compiler
C sourceMachine Code( o file)C source
file(.o file)
Linker
Executable
LibraryFilesFiles
CSE 251 Dr. Charles B. OwenProgramming in C5
![Page 362: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/362.jpg)
Some gcc optionsP i ( d d i)• Preprocessing (gcc –E code.c > code.i)– Removes preprocessor directives (commands that start with #)– Produces code.i Don’t use directlyProduces code.i Don t use directly
• Compiling (gcc –o code.o –c code.i)– Converts source code to machine language with unresolved directives– Produces the code.o binary
• Linking (gcc –lm –o code code.o)– Creates machine language exectutable– Produces the code binary by linking with the math library (‐lm)
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 363: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/363.jpg)
C Preprocessor, cppExpanded
Processes commands that are preceded with # symbols and
preprocessor(# commands)
ExpandedC code
p yexpands the code
#include(# commands)
#define#ifdef and #ifndef
C sourcefile
CSE 251 Dr. Charles B. OwenProgramming in C7
![Page 364: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/364.jpg)
#include
Include header files that contain declarations necessary for compiling code
– the declarations provide the proper types, but not the actual definitions (the actual code)
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 365: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/365.jpg)
data c
# ifndef _STDIO_H
# if !defined need FILE &&
stdio.h
#include <stdio.h>
#include “functions.h”
data.c __ _!defined __need___FILE
# define _STDIO_H 1
# include <features.h>
int main() {
double x = 1;
__BEGIN_DECLS
…
printf(“Sinc(x) = %f\n”, Sinc(x));
} double Sinc(double x);
functions.h
gcc –E data.c > data.idata i is like an “expanded” C code in which the #include commanddata.i is like an expanded C code in which the #include command is “substituted” with text from the files
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 366: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/366.jpg)
Example#include “display.h”display h
main.c
void DisplayMe(int n); int main(){
DisplayMe(12);
display.h
DisplayMe(12);}
CSE 251 Dr. Charles B. OwenProgramming in C10 A
![Page 367: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/367.jpg)
Header Files
We’ve been using .h files to define things from the C libraries:stdio.h, stdlib.h, stdbool.h, etc.
These are called Header Files.
We’re going to create our own .h files to share information between .c files.
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 368: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/368.jpg)
#defined f bl#defines a preprocessor variable
– every place the variable occurs, the definition will be substituted as codesubstituted as code
Syntax: #define var_name var_definitiony _ _– Examples:
#define DEBUG 1#d fi PI 3 1415926535#define PI 3.1415926535
CSE 251 Dr. Charles B. OwenProgramming in C12
![Page 369: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/369.jpg)
#include <stdio.h>#define PI 3 14157265
preproc.c
gcc –E preproc c > preproc i#define PI 3.14157265#define square(x) (x*x)
int main() {
gcc E preproc.c > preproc.i
printf("Value of PI is %f\n", PI);printf("Square of 3.5 is %f\n", square(3.5));
}
# 1 “preproc.c"# 1 "<built‐in>"# 1 "<command line>“
preproc.i
# 1 <command‐line>…typedef unsigned int size_t;…int main() {printf("Value of PI is %f\n", 3.14157265);printf("Square of 3.5 is %f\n", (3.5*3.5));
}
CSE 251 Dr. Charles B. OwenProgramming in C13
}
![Page 370: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/370.jpg)
#ifdef, #ifndef, #ifSurround code that might be included. Include for compilation when desired
#ifdef DEBUG….#endif#ifndef DEBUG#ifndef DEBUG…#endif#endif
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 371: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/371.jpg)
Common useif(num == 1){/* This is the only time we actually move a disk */DisplayTower(tower);DisplayTower(tower);
#if 0printf("Press return");
( ( ) )
This is a handy way to turn off a block of code without removing it It often worksfgets(cmd, sizeof(cmd), stdin);
#endif
MoveDisk(tower, fm, to);
removing it. It often works better than trying to comment out the block, MoveDisk(tower, fm, to);
return;}
which may have comments already in it.
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 372: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/372.jpg)
Header Files #include <stdio.h>#include <stdlib.h>hanoi h:
hanoi.c:
#define NumDisks 6#define NumPins 3
#include <stdbool.h>
#include “hanoi.h”
hanoi.h:
bool CheckDone(int tower[NumPins][NumDisks]);
#i l d di h
display.c:I have two .c files in the same program. B h d k #include <stdio.h>
#include <stdlib.h>#include <stdbool.h>
Both need to know NumDisks and NumPins. So, I put that
#include “hanoi.h”
void DisplayTower(int tower[NumPins][NumDisks]){
information in a header file: hanoi.h
{…}
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 373: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/373.jpg)
Example#include “hanoi.h”hanoi h:
hanoi.c:
#define NumDisks 6#define NumPins 3
bool CheckDone(int tower[NumPins][NumDisks]);
#if 0
hanoi.h:
#if 0bool DebugStuff(int x, int b[NumPins]);#endif
CSE 251 Dr. Charles B. OwenProgramming in C17 B
![Page 374: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/374.jpg)
What would happen? #include <stdio.h>#include <stdlib.h>hanoi h:
hanoi.c:
#define NumDisks 6#define NumPins 3
#include <stdbool.h>
#include “solve.h”#include “hanoi h”
hanoi.h:
#include hanoi.h
bool CheckDone(int tower[NumPins][NumDisks]);#include “hanoi.h”
solve.h:
void Autosolve(inttower[NumPins][NumDisks]);
CSE 251 Dr. Charles B. OwenProgramming in C18 C
![Page 375: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/375.jpg)
Include Guards #include <stdio.h>#include <stdlib.h>hanoi h:
hanoi.c:
#ifndef HANOI_H#define HANOI_H
#include <stdbool.h>
#include “solve.h”#include “hanoi h”
hanoi.h:
#define NumDisks 6#define NumPins 3
# dif
#include hanoi.h
bool CheckDone(int tower[NumPins][NumDisks]);
#endif
#ifndef SOLVE H
solve.h: Include Guards: Conditional compilation code that protects a #ifndef SOLVE_H
#define SOLVE_H
#include “hanoi.h”
section of code in a header from being compiled more than once.
void Autosolve(inttower[NumPins][NumDisks]);
CSE 251 Dr. Charles B. OwenProgramming in C19
#endif
![Page 376: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/376.jpg)
Compiling ExpandedC code
Object Code (.o file)
gcc –c code.c
preprocessor(# commands)
Compiler
C
Compiler translates the C source code into object code – what the machine actually
C sourcefile understands
Machine‐specific
Each line represents either a piece of data orEach line represents either a piece of data or a machine‐level instruction
To create the assembly code:gcc -c preproc.c
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 377: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/377.jpg)
Linking• Object file may not be directly executable
– Missing some partsStill has some names to be resolved– Still has some names to be resolved
• The linker (ld) takes multiple object files ( o) and putsThe linker (ld) takes multiple object files (.o) and puts them together into one executable file– Resolves references to calls from one file to another
• Linking is important as it allows multiple, separate fil t b b ht t thfiles to be brought together
CSE 251 Dr. Charles B. OwenProgramming in C21
![Page 378: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/378.jpg)
Linkingpreprocessor
ExpandedC code
Compilergcc ‐E
p
gcc ‐c
C source
Machine Code(.o file)
file
Linker
ExecutableExecutable
LibraryFiles
gcc –lm code.o –o code
CSE 251 Dr. Charles B. OwenProgramming in C22
![Page 379: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/379.jpg)
Separate compilation
• For large, complex programs, it is a good idea to break your files into separate .c and .h files
• Can debug each separately, then reuse
• Can distribute pieces to other so they can incorporate into their code without changing their code (just link it in)
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 380: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/380.jpg)
Example (Separate Compilation)shapes.h shapes.cmainprog.c
math.h
mainprog
gcc -c shapes.cg p
gcc –c mainprog.c
gcc –lm mainprog.o shapes.o –o mainprog
CSE 251 Dr. Charles B. OwenProgramming in C24
![Page 381: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/381.jpg)
Another way (Compile all at once)shapes.h shapes.cmainprog.c
math.h
mainprog
l h i igcc –lm shapes.c mainprog.c –o mainprog
CSE 251 Dr. Charles B. OwenProgramming in C25
![Page 382: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/382.jpg)
Controlling compilation/linking better
• We need a better way to control compilation– too much detail to type each time
• We can save time by only updating (compiling) the parts that need updating– if a .o file is OK (unchanged source), leave it. If a .c file is changed, the .o file needs to be regenerated then everything relinkedeverything relinked
CSE 251 Dr. Charles B. OwenProgramming in C26
![Page 383: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/383.jpg)
Makefiles
• Suppose you have a program, which is made up of these 5 source files:main.c (include data.h, io.h)data.c (include data.h)d hdata.hio.c (include io.h)io hio.h
CSE 251 Dr. Charles B. OwenProgramming in C27
![Page 384: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/384.jpg)
How to create the executable?
data .c data.h main.c io.cio.h
gcc -c data.c → data.ogcc c io c → io ogcc -c io.c → io.ogcc -c main.c → main.o
i i d t t blgcc main.o io.o data.o –o executable
CSE 251 Dr. Charles B. OwenProgramming in C28
![Page 385: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/385.jpg)
How to create the executable?
data .c data.h main.c io.cio.h
gcc -c data.cgcc c io c
What if you modify data.h?
D d tgcc -c io.cgcc -c main.c
i i d t t bl
Do you need to re‐run gcc ‐c on io.c and main.c?
gcc main.o io.o data.o –o executable
CSE 251 Dr. Charles B. OwenProgramming in C29
![Page 386: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/386.jpg)
Dependencies executable
data.o main.o io.o
data.c data .h main.c io.cio.h
CSE 251 Dr. Charles B. OwenProgramming in C30
![Page 387: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/387.jpg)
What is a Makefile?
• A Makefile is used with the make utility to determine which portions of a program to compile.
• It is basically a script that guides the make utility to choose the appropriate program files that are to be compiled and linked together
CSE 251 Dr. Charles B. OwenProgramming in C31
![Page 388: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/388.jpg)
If data.h is modified executable
d t i idata.o main.o io.o
data .c data .h main.c io.cio.h
No need to re‐create data.o and main.o
CSE 251 Dr. Charles B. OwenProgramming in C32
![Page 389: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/389.jpg)
If io.c is modified executable
d t i idata.o main.o io.o
data .c data .h main.c io.cio.h
No need to re‐create data.o and main.o
CSE 251 Dr. Charles B. OwenProgramming in C33
![Page 390: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/390.jpg)
#ifndef HANOI_H#define HANOI_H
#include <stdio.h>#include <stdlib.h>
hanoi.h: hanoi.c:
#define NumDisks 6#define NumPins 3
#include <stdbool.h>
#include “solve.h”#include “hanoi h”
#endif#include hanoi.h
bool CheckDone(int tower[NumPins][NumDisks]);solve.h:
#ifndef SOLVE_H#define SOLVE_H
#include “hanoi h”
#include <stdio.h>#include <stdlib.h>
display.c:
#include hanoi.h
void Autosolve(inttower[NumPins][NumDisks]);
#include <stdbool.h>
#include “hanoi.h”
#endifbool DisplayTower(int tower[NumPins][NumDisks]);
CSE 251 Dr. Charles B. OwenProgramming in C34 D
![Page 391: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/391.jpg)
What is in a Makefile?
name incolumn1 spaces
fil d d 1 d d 2
not commas
file: dependency1 dependency2command
TAB character
CSE 251 Dr. Charles B. OwenProgramming in C35
![Page 392: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/392.jpg)
What it means
• The first line indicates what a file depends on. That is, if any of the dependencies change, then that file must be updated– What updating means is defined in the command listed below the dependencybelow the dependency
• Don’t forget the TAB character to begin the second• Don t forget the TAB character to begin the second line
CSE 251 Dr. Charles B. OwenProgramming in C36
![Page 393: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/393.jpg)
Dependency graph Executable (prog)
data.o main.o io.o
data .c data .h main.c io.cio.h
CSE 251 Dr. Charles B. OwenProgramming in C37
![Page 394: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/394.jpg)
Creating a Makefile Makefile:
Executable (prog) prog:
data.o:
data.o main.o io.o
main.o:
io.o:
data .c data .h main.c io.cio.h
List the object (*.o) and executable files that make up the program
CSE 251 Dr. Charles B. OwenProgramming in C38
![Page 395: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/395.jpg)
Creating a Makefile Makefile:
d t i iExecutable (prog) prog: data.o main.o io.ogcc –o prog data.o main.o io.o
data.o: data.h data.c
data.o main.o io.ogcc –c data.c
main.o: data.h io.h main.cigcc –c main.c
io.o: io.h io.cgcc –c io.c
data .c data .h main.c io.cio.h
First line specifies the dependencies for
g
each object and executable files
CSE 251 Dr. Charles B. OwenProgramming in C39
![Page 396: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/396.jpg)
Creating a Makefiled t i i
Makefile:
Executable (prog)prog: data.o main.o io.o
gcc –o prog data.o main.o io.o
data.o: data.h data.c
data.o main.o io.ogcc –c data.c
main.o: data.h io.h main.cigcc –c main.c
io.o: io.h io.cgcc –c io.c
data .c data .h main.c io.cio.hg
Second line contains the command to execute if any of the dependence files y pare modified
CSE 251 Dr. Charles B. OwenProgramming in C40
![Page 397: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/397.jpg)
Additional makefile “targets”
clean: rm -rf *.o example22
Command “make clean” calls the clean commandIn this case clears the o files and the executableIn this case, clears the .o files and the executable
CSE 251 Dr. Charles B. OwenProgramming in C41
![Page 398: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/398.jpg)
Usage
• make– To create the executable
• make linkedList.o– do what has to be done to make that .o file, then stop
• make clean– run the clean command
CSE 251 Dr. Charles B. OwenProgramming in C42 1
![Page 399: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/399.jpg)
structs Box
Aggregating associated data into a single variable
widthlengthheightheight
Circleint main() {
radiusBox mybox; Circle c;
mybox width = 10;mybox.width = 10;mybox.length = 30;mybox.height = 10;c.radius = 10;
}
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 400: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/400.jpg)
The idea Boxwidthlengthheight
I want to describe a box. I need variables for the width, length, and height. height
I can use three variables, but wouldn’t it be better if I had a single variable to describe a better if I had a single variable to describe abox?
That variable can have three parts the widthThat variable can have three parts, the width, length, and height.
CSE 251 Dr. Charles B. OwenProgramming in C2
![Page 401: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/401.jpg)
Structs
A struct (short for structure) in C is a grouping of variables together into a single type
– Similar to structs in Matlab
struct nameOfStruct{
type member;type member;…
}; N t th i l t th d}; Note the semicolon at the end.To declare a variable:
struct nameOfStruct variable_name;
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 402: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/402.jpg)
Example #include <stdio.h>
struct Box
Boxidth
struct Box {
int width;int length;
Data structure
widthlengthheight
int length;int height;
};
l
definition
Circle
struct Circle {
double radius;Circle
radius};
int main() {
You can declare
i bl{struct Box b; struct Circle c;
}
variables
CSE 251 Dr. Charles B. OwenProgramming in C4
}
A
![Page 403: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/403.jpg)
Example
int main() {struct Box b; You can
assign values
#include <stdio.h>
struct Box {
b.width = 10;b.length = 30;b.height = 10;
gto each member
int width;int length;int height;
};
Box
b.height 10;
}
};
widthlengthheight
We use a period “.” to get to the elements of a struct. g
If x is a struct, x.width is an element in a struct
CSE 251 Dr. Charles B. OwenProgramming in C5
in a struct.
![Page 404: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/404.jpg)
Another Examplet t b kR dSt t
You can use mixed data types
struct bankRecordStruct{
char name[50]; within the struct (int, float, char [])
char name[50];float balance;
};};
struct bankRecordStruct billsAcc;
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 405: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/405.jpg)
Accessing valuest t b kR dSt tstruct bankRecordStruct{
char name[50];Access values in a struct using a period:
float balance;};
“.”
struct bankRecordStruct billsAcc;
i tf(“M b l i %f\ ” bill A b l )printf(“My balance is: %f\n”, billsAcc.balance);
float bal = billsAcc.balance;
CSE 251 Dr. Charles B. OwenProgramming in C7 B
![Page 406: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/406.jpg)
Assign Values using Scanf()t t k dstruct BankRecord
{char name[50];float balance;;
};
int main() (){
struct BankRecord newAcc; /* create new bank record */
i tf(“E t t “)printf(“Enter account name: “);scanf(“%50s”, newAcc.name);printf(“Enter account balance: “);scanf(“%d”, &newAcc.balance);scanf( %d , &newAcc.balance);
}
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 407: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/407.jpg)
Copy via =
You can set two struct type variables equal to each other and each element will be copied
struct Box { int width, length, height; };
int main() {
struct Box b, c;b.width = 5; b.length=1; b.height = 2;c = b; // copies all elements of b to cc = b; // copies all elements of b to cprintf(“%d %d %d\n”, c.width, c.length, c.height);
}
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 408: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/408.jpg)
Passing Struct to a function
• You can pass a struct to a function. All the elements are copied
• If an element is a pointer, the pointer is copied but not what it points to!
int myFunction(struct Person p){…}
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 409: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/409.jpg)
Using Structs in Functions
Write a program that – Prompts the user to enter the dimensions of a 3D box and a circle
– Prints the volume of the box and area of the circle
Sample run:
CSE 251 Dr. Charles B. OwenProgramming in C11
![Page 410: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/410.jpg)
#include <stdio.h>#include <math.h>
struct Box { int width height length; };struct Box { int width, height , length; };
int GetVolume(struct Box b) {
return b.width * b.height * b.length;}
int main()int main() {
struct Box b;
printf("Enter the box dimensions (width length height): ");scanf("%d %d %d", &b.width, &b.length, &b.height);
printf("Box volume = %d\n", GetVolume(b));printf( Box volume %d\n , GetVolume(b));}
CSE 251 Dr. Charles B. OwenProgramming in C12 C
![Page 411: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/411.jpg)
Note: == Comparison doesn’t workstruct Box { int width, length, height; };
int main()int main() {
struct Box b, c;b width 5; b length 1; b height 2;b.width = 5; b.length=1; b.height = 2;c = b;if (c == b) /* Error when you compile! */
printf(“c and b are identical\n”);else
printf(“c and b are different\n”);printf( c and b are different\n );} t
Error message: invalid operands to binary == (have 'Box' and 'Box')
CSE 251 Dr. Charles B. OwenProgramming in C13
Error message: invalid operands to binary == (have Box and Box )
![Page 412: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/412.jpg)
Create your own equality test#i l d < tdi h>#include <stdio.h>#include <math.h>
struct Box { int width, height , length; };{ , g , g ; };
int IsEqual(struct Box b, struct Box c) {
if (b width==c width &&if (b.width==c.width &&b.length==c.length &&b.height==c.height)return 1;
belsereturn 0;
}
struct Box b, c;b.width = 5; b.length=1; b.height = 2;c = b;
if (IsEqual(b,c))printf("c and b are identical\n");
elsei tf(" d b diff t\ ")
CSE 251 Dr. Charles B. OwenProgramming in C14
printf("c and b are different\n");
D
![Page 413: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/413.jpg)
typedef
typedef is a way in C to give a name to a custom type.
typedef type newname;
typedef int dollars;typedef int dollars;typedef unsigned char Byte;
I can declare variables like:
dollars d;Byte b c;Byte b, c;
It’s as if the type already existed.
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 414: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/414.jpg)
typedef for Arrays
There is a special syntax for arrays:Now, instead of:
typedef char Names[40];typedef double Vector[4];typedef double Mat4x4[4][4];
double mat[4][4];
typedef double Mat4x4[4][4];I can do:
Mat4x4 mat;Mat4x4 mat;
CSE 251 Dr. Charles B. OwenProgramming in C16
![Page 415: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/415.jpg)
Using Structs with Typedef
typedef struct [nameOfStruct] {
type member;type member; optionalyp…
} TypeName;
optional
} yp ;
To declare a variable: TypeName variable_name;
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 416: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/416.jpg)
Example#include <stdio.h>
typedef struct{Box
widthl th
{int width;int length;i t h i htlength
height
Ci l
int height;} Box;
typedef struct { double radius; } Circle;Circle
radius
yp { }
int main() {
Box b; /* instead of struct Box */Box b; /* instead of struct Box */Circle c; /* instead of struct Circle */b.width = 10;b l th 30b.length = 30;b.height = 10;c.radius = 10;
}
CSE 251 Dr. Charles B. OwenProgramming in C18
}
E
![Page 417: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/417.jpg)
Arrays of structs
You can declare an array of a structure and manipulate each one
typedef struct{
d bl didouble radius;int x;int y;h [10]char name[10];
} Circle;
Circle circles[5];
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 418: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/418.jpg)
Size of a Struct: sizeof
typedef struct{
double radius; /* 8 bytes */int x; /* 4 bytes */int y; /* 4 bytes */int y; /* 4 bytes */char name[10]; /* 10 bytes */
} Circle;} Circle;
printf(“Size of Circle struct is %d\n”, sizeof(Circle));sizeof(Circle));
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 419: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/419.jpg)
Size of a Struct8 + 4 + 4 + 10 = 26
– But sizeof() reports 28 bytes!!!
Most machines require alignment on 4‐byte boundary ( d)(a word)
– last word is not filled by the char (2 bytes used, 2 left over)
D D D D D D D D I I I I I I I I C C C C C C C C C C X X8 byte, 2 word double 4 byte,
1 word4 byte, 1 word
10 byte char array, 2 bytesof the last word unused
integer integerof the last word unused
CSE 251 Dr. Charles B. OwenProgramming in C21
![Page 420: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/420.jpg)
Pointers to structs
typedef struct{int width;
Box b; /* A variable of type Box */Box *c;/* A pointer to a Box */double w;int length;
int height;} Box;
double w;
b.width = 5; b.height = 7; b.length = 3;
c = &b; /* Same as before */
w = c‐>width;
To access the members of a struct, we use:
. for a variable of the struct’s type‐> for a pointer to a struct
CSE 251 Dr. Charles B. OwenProgramming in C22
> for a pointer to a struct
![Page 421: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/421.jpg)
struct Concepts struct Box b; /* No typedef */Circle c; /* typedef */
struct Box{
double wid, hit;}
struct Box *pBox; /* Pointer to Box */Circle *pCirc; /* Pointer to Circle */
};
typedef struct{
pBox = &b; /* Get pointer to a Box */b.wid = 3;pBox‐>wid = 7;{
double radius;int x;int y;char name[10];
pBox >wid 7;
pCirc = &c;(*pCirc).radius = 9;char name[10];
} Circle;
CSE 251 Dr. Charles B. OwenProgramming in C23 1
![Page 422: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/422.jpg)
Dynamic Memory Allocation
• Dynamic memory allocation– How to allocate memory for variables (esp. arrays/strings) during run timeduring run time
– malloc(), calloc(), realloc(), and free()
CSE 251 Dr. Charles B. OwenProgramming in C1
![Page 423: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/423.jpg)
Why dynamic memory allocation? Usually, so far, the arrays and strings we’re using have fixed length (i.e., length is known at compile time)
• Example:h [ ] // ll f hchar myStr[11]; // allocates memory for 10 charsprintf(“Enter a string: “);fgets(myStr, 11, stdin);fgets(myStr, 11, stdin);
What if the user wants to enter a string more than 10enter a string more than 10 chars long or if the length is known only at run time?
CSE 251 Dr. Charles B. OwenProgramming in C2
y
![Page 424: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/424.jpg)
malloc()
• malloc() is used to request additional memory from the operating system during program execution
Syntax: malloc(numBytes)
• Input is the number of consecutive bytes to be allocated• Return value is a pointer to the beginning of the block of
memory allocated or NULL if malloc fails
• To use malloc(), you must #include <stdlib.h>
CSE 251 Dr. Charles B. OwenProgramming in C3
![Page 425: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/425.jpg)
malloc()h * h P /* d l i h */char *charP; /* declare a pointer to char */
charP
charP = malloc(10); 10 bytes or charscharP malloc(10);
charP
10 bytes or chars
charP contains the address of the beginning of that block.
CSE 251 Dr. Charles B. OwenProgramming in C4
![Page 426: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/426.jpg)
free()
• The function free() returns memory to the memory pool. It “frees” up memory
Syntax: free(ptr)
where ptr “points to” memory previously allocated by– where ptr points to memory previously allocated by malloc() function
• To use free(), you must #include <stdlib.h>
CSE 251 Dr. Charles B. OwenProgramming in C5
![Page 427: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/427.jpg)
Example
This program allows the user to specify the length of a stringspecify the length of a string, allocates memory for the string, and then applies string operationspp g p
CSE 251 Dr. Charles B. OwenProgramming in C6
![Page 428: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/428.jpg)
#include <stdlib.h> /* you need this library for malloc(), free(), exit() */#include <stdio.h>#include <string.h> /* you need this library for strchr(), strlen() */
int main () {char *charP, *q;, q;int maxlen;
printf("Enter maximum string length: ");scanf("%d" &maxlen);scanf( %d , &maxlen);getchar(); /* reads the newline character */
printf("Enter the string: ");p ( g )fgets(charP, maxlen, stdin);
if ((q = strchr(charP, '\n')) != NULL) *q = '\0';
printf("You've entered a string %s of length %d\n", charP, strlen(charP));free(charP);}
CSE 251 Dr. Charles B. OwenProgramming in C7
}
A
![Page 429: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/429.jpg)
What it does:
if ((q = strchr(charP, '\n')) != NULL) *q = '\0';
The function fgets returns the entire line input by the user including the newline at the end (when the user hit return). The function strchr(charP, ‘\n’) will return a pointer to that character (newline) if it exists or NULL otherwise Ifwill return a pointer to that character (newline) if it exists or NULL otherwise. If the result in the variable q is not NULL, the if statement executes the line of code to replace the newline with a null termination for the string.
CSE 251 Dr. Charles B. OwenProgramming in C8
![Page 430: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/430.jpg)
strchr
if ((q = strchr(charP, '\n')) != NULL)*q = '\0';
This code finds the first occurance of the character ‘\n’ which is the newline character that fgets will obtain If found (value in q isthat fgets will obtain. If found (value in q is not NULL), it sets that character to the string null termination.
CSE 251 Dr. Charles B. OwenProgramming in C9
![Page 431: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/431.jpg)
Memory leak
If malloc’ed memory is not free’ed, then the OS will “leak memory”
– This means that memory is allocated to the program but not returned to the OS when it is finished using itThe program therefore grows larger over time– The program therefore grows larger over time.
CSE 251 Dr. Charles B. OwenProgramming in C10
![Page 432: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/432.jpg)
Exampleint main () {char *charP, r[80]; Memory leak exampleint length;
while (1) {{
printf("Enter the maximum string length: ");fgets(r, 80, stdin);sscanf(r, "%d", &length);
if ((charP = malloc(length)) == NULL) {printf("Out of memory. Quitting\n");exit(1);( );
}printf("Enter the string: ");fgets(charP, length, stdin);/* free(charP); */
}}
CSE 251 Dr. Charles B. OwenProgramming in C11 B
![Page 433: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/433.jpg)
Exampleint main () {char *charP, r[80];
Memory leak exampleEach iteration of the loop allocates memoryint length;
while (1) {
Each iteration of the loop allocates memory for a string. But, that memory is never freed. Hence, we have a memory leak.{
printf("Enter the maximum string length: ");fgets(r, 80, stdin);sscanf(r, "%d", &length);
if ((charP = malloc(length)) == NULL) {printf("Out of memory. Quitting\n");exit(1);( );
}printf("Enter the string: ");fgets(charP, length, stdin);/* free(charP); */
}}
CSE 251 Dr. Charles B. OwenProgramming in C12
![Page 434: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/434.jpg)
malloc without freeing while (1) {
charP = malloc(length+1);charP = malloc(length+1);…
}
charP
If you don’t free the allocated memory, previous block is still “ours” according to the OS, but we can no longer find it (no pointer to it). That block is an orphan!
It’s like you bought a house, but then lost the address You still own it and pay taxes on it butaddress. You still own it and pay taxes on it, but you can’t use it because you can’t find it.
CSE 251 Dr. Charles B. OwenProgramming in C13
![Page 435: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/435.jpg)
Always free what you malloc
• You are responsible for your memory, you must allocate it and free it.
• Unlike other languages, it is all up to you!
• If you don’t free it, your program grows larger and eventually runs out of memory!
CSE 251 Dr. Charles B. OwenProgramming in C14
![Page 436: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/436.jpg)
malloc allocates bytes
• If you want a character array that stores 10 characters (including ‘\0’):
char *p = malloc(10);
If t t ll t t f 10 i t ( d bl• If you want to allocate storage for 10 ints (or doubles or floats), you can’t do this:
int *p = malloc(10); /* WRONG! Why? */int p = malloc(10); / WRONG! Why? /
CSE 251 Dr. Charles B. OwenProgramming in C15
![Page 437: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/437.jpg)
allocate int and double array
int *intP;double *doubleP;
// Allocate space for 10 integersintP = malloc(10 * sizeof(int));intP = malloc(10 sizeof(int));
// Allocate space for 10 doublesdoubleP = malloc(10 * sizeof(double));
CSE 251 Dr. Charles B. OwenProgramming in C16 C
![Page 438: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/438.jpg)
allocate int and double array
int *intP;double *doubleP;
// Allocate space for 10 integersintP = malloc(10 * sizeof(int));
Allocates 40 bytessizeof(int) = 4
intP = malloc(10 sizeof(int));
// Allocate space for 10 doublesdoubleP = malloc(10 * sizeof(double));
Allocates 80 bytessizeof(double) = 8
CSE 251 Dr. Charles B. OwenProgramming in C17
![Page 439: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/439.jpg)
realloc
realloc takes a pointer to allocated memory and reallocates the memory to a larger size
– if it can make the old block bigger, great– if not, it will get another, larger block, copy the old contents to the new contents free the old contents andcontents to the new contents, free the old contents and return a pointer to the new
intP = malloc(sizeof(int));intP = malloc(sizeof(int));intP = realloc(intP, 2*sizeof(intP));
intP may be different after a realloc!
CSE 251 Dr. Charles B. OwenProgramming in C18
![Page 440: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/440.jpg)
int main () {double *dblPtr;int howMany randNum
Step 1: Prompt the user to enter the number of random numbers to generate
int howMany, randNum;
printf("How many random numbers to generate:");howMany=ProcessInput(stdin);
dblPtr = malloc(howMany * sizeof(double)); if (dblPtr == NULL){printf("memory allocation error exiting\n"); An example programprintf( memory allocation error, exiting\n );exit(1);}
p p g
for (int i=0;i<howMany;i++){randNum = random();dblPtr[i]=(randNum%10000)/1000 0;dblPtr[i]=(randNum%10000)/1000.0;}
PrintArray(dblPtr,howMany);
CSE 251 Dr. Charles B. OwenProgramming in C19
![Page 441: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/441.jpg)
Step 2: create a dynamic array to store the random numbers
int main () {double *dblPtr;int howMany randNumint howMany, randNum;
printf("How many random numbers to generate:");howMany=ProcessInput(stdin);
dblPtr = malloc(howMany * sizeof(double)); if (dblPtr == NULL){printf("memory allocation error exiting\n");
In this example we have tested to be sure malloc
printf( memory allocation error, exiting\n );exit(1);}
succeeded. If not, we are out of memory.
for (int i=0;i<howMany;i++){randNum = random();dblPtr[i]=(randNum%10000)/1000 0;dblPtr[i]=(randNum%10000)/1000.0;}
PrintArray(dblPtr,howMany);
CSE 251 Dr. Charles B. OwenProgramming in C20
![Page 442: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/442.jpg)
Step 3: generate the random numbers and print them
int main () {double *dblPtr;int howMany randNumint howMany, randNum;
printf("How many random numbers to generate:");howMany=ProcessInput(stdin);
dblPtr = malloc(howMany * sizeof(double)); if (dblPtr == NULL){printf("memory allocation error exiting\n");printf( memory allocation error, exiting\n );exit(1);}
for (int i=0;i<howMany;i++){randNum = random();dblPtr[i]=(randNum%10000)/1000 0;dblPtr[i]=(randNum%10000)/1000.0;}
PrintArray(dblPtr,howMany);
CSE 251 Dr. Charles B. OwenProgramming in C21
![Page 443: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/443.jpg)
dblPtr = realloc(dblPtr, 2*howMany); Step 4: double the size of the array using realloc
for (int i=howMany; i<howMany*2; i++){{
randNum = random();dblPtr[i]=(randNum%10000)/1000.0;
}
Step 5: generate more random numbers and print them
howMany *= 2;
PrintArray(dblPtr howMany);PrintArray(dblPtr, howMany);free(dblPtr);
}
CSE 251 Dr. Charles B. OwenProgramming in C22
![Page 444: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/444.jpg)
int ProcessInput(FILE *f)p ( ){int val; Safe data entry, just like last char in[100];fgets(in,100,f);
y, jweek
sscan(in, “%d”, &val);return val;
}
CSE 251 Dr. Charles B. OwenProgramming in C23
![Page 445: C-Michigan State University](https://reader033.fdocuments.in/reader033/viewer/2022042623/545db4b1b1af9f320a8b4ce2/html5/thumbnails/445.jpg)
Print Array
void PrintArray(double *ptr, int cnt){printf("Printing Array Values\n");for(double *p=ptr; p<ptr+cnt; p++)( p p ; p p ; p )printf("Val is:%lf\n",*p);
}}
CSE 251 Dr. Charles B. OwenProgramming in C24 1