CPS 125: Computer Science For Engineers A Comprehensive Overview
e-jja Ryerson University
Preface Greetings, this is going to be a written guide from the perspective of a student. From this document you will be able to learn the basics of the course. This was primarily done to improve my writing while trying to create something useful. I may never use these notes again, but they are really pretty. Please follow along with these notes, and mark any corrections as I am only human. I’ve had multiple people willing to pay for one on one tutoring, but I don’t take money from others. The only word I can describe CPS 125 is useless. As a course, it moves slowly and there are still major components of C not covered. As a programmer, it can barely be called an introduction to computer science as it does not include any study of algorithms. This course is similar to a free online 7 week courses. The assignments are outdated, the twitter account is annoying as they should simply push D2L notications, and the online web page feels like they are mocking students. Every assignment is confusing to read as they make you write code, then expect you to erase it and add on more, instead of saying what is required from the start. In other words, the course should be an online credit.
Disclaimer: I am not responsible for any plagiarism committed by the presence of this document, this only serves as a guide. Any plagiarism will not be tolerated by Ryerson University, nor is this guide intended to be an answer sheet. This guide will help only if you apply yourself by programming.
1
Contents 1 Denitions and Conversions
4
2 The C Language
9
3 Learning The Basics 3.1 Hard Rules for Identiers . . . . . . . . . . 3.2 Soft Rules for Identiers . . . . . . . . . . . 3.3 Placeholders for IO Statements . . . . . . . 3.4 Pointers . . . . . . . . . . . . . . . . . . . . 3.5 Arrays and Strings . . . . . . . . . . . . . . 3.5.1 Arrays . . . . . . . . . . . . . . . . . 3.5.2 Strings . . . . . . . . . . . . . . . . . 3.5.3 String Arrays . . . . . . . . . . . . . 3.5.4 Two Dimensional Arrays . . . . . . . 3.6 Arithmetic . . . . . . . . . . . . . . . . . . . 3.6.1 Evaluating Expressions . . . . . . . . 3.6.2 Casting . . . . . . . . . . . . . . . . 3.6.3 Shortcut Op erators . . . . . . . . . . 3.6.4 Increment and Decrement Oper perator . 3.6.5 Comparison Op erators . . . . . . . . 3.6.6 Logical Operators . . . . . . . . . . . 3.6.7 Order of Operation . . . . . . . . . .
. . . . . . . . . . . . . . . . .
11 12 12 13 14 15 15 15 16 16 17 17 18 18 19 19 19 20
4 Libraries 4.1 The Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 The Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3 The Standard Input Output Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
22 22 22 22
5 Modes of Op eration 5.1 Interactive Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2 Batch Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
24 24 25
6 The if Statement 6.1 Else if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.2 Nested if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
26 26 27
7 Switch Statement
28
8 Loops 8.1 While . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.2 Do While . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8.3 for Lo op . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
29 29 30 30
9 Dealing with Files using Loops 9.1 Reading a Whole File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9.2 Writing to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
32 32 33
2
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
10 Indep endent Functions 10.1 Create Your Own Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.2 Multiple Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.3 10.3 Usin Usingg Two Dime Dimens nsio iona nall Arra Arrays ys with with Inde Indepe pend nden entt Funct unctio ions ns . . . . . . . . . . . . . . . . .
35 35 35 36
11 Recursion
37
12 Dynamic Memory Allocation
39
13 Linked Lists
41
14 Labs 14.1 La L ab 14.2 La L ab 14.3 La L ab 14.4 La L ab 14.5 La L ab 14.6 La L ab 14.7 La L ab
44 44 45 46 48 49 51 53
1 2 3 4 5 6 8
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
15 Assignment 1
55
16 Assignment 2
57
17 Ending Comments
59
3
1 Den Denit itio ions ns and and Con Conv versi ersion onss Denition: An algorithm is a series of instructions on how to solve the problem. • The order of execution execution must must be correct. correct. Eg: To make a jam sandwich, you have to open the jar of jam before you spread the jam • The order order must be unambiguous. unambiguous. The compiler must know what to do, imagine you are simply speaking to a child. The compiler takes everything literally, so therefore in order to minimize error in translation from logic to program you must be clear. (eg. 3*2/5-3 should be 3*(2/(5-3)) ) • There There must must be a result. result. The sequence of steps must produce a nal result. In the rst point’s example, the result is the jam sandwich • They must stop at a nite amount if time. You want to make sure your program pushes out a result before the sun burns out. A computer is something we use in our everyday life, we recognize the keyboard, mouse, and display but we rarely think about the complexity required to make such devices work seamlessly together. In computer science, we try explain how computers work on the inside and why you should care. Just to get denitions out of the way:
Denition: A bit is a binary digit, so it can represent a 1 or 0 Denition: A byte is a sequence of 8 bits. Denition: A word is the width of a memory cell In decimal, you can represent any positive integer N by the formula,
∑
di 10i
(1)
i≥0
Where di = 0,1,...,9. Recall, that every number is a place holder for a power of ten. Eg. 70 can be represented by 7 in the tens and 0 in the ones column. 70 = 7 × 101 + 0 x 0 x 10 0
(2)
In binary, binary, the place holder idea still applies. Therefore Therefore digit starting starting from the right hand side increases by a factor of 2 as you move to the left. To introduce the math, any integer number N can be represented by
∑
di 2i
(3)
i≥0
Where di = 0, 1. To nd 70 in binary, you add the powers of two. 70 = 1 × 26 + 0 × 25 + 0 × 24 + 0 × 23 + 1 × 22 + 1 × 21 + 0 × 20 4
(4)
Representing an integer number N in binary 1. First largest largest power power of two smaller than or equal to N. N ≥ 2 i ‘. Keep track of the power i. 2. Take N and subtract it by the number found in the previous step. 3. Repeat step 1 with your new smaller smaller number until until you get to zero. 4. In an empty empty space, write down the powers powers of two two increasing increasing from right right to left. left. Starting at zero 5. Recall Recall all the the i’s found in step 1. Wherever that power of 2 exists, write a one above it. 6. For all other places places which did not nd a power. power. Write a zero above the power. As an example, let us represent the number 89, • Notice that 89 > 64 = 26 . i = 6. • 89 − 64 = 25 • Notice that 25 > 16 = 24 . i = 4 • 25 − 16 = 9 • Notice that 9 > 8 = 23 . i = 3 • 9 − 8 = 1 • Notice that 1 = 1 = 20 . i = 0 • 1 − 1 = 0 • We found i = {6, 4, 3, 0} 1 1 1 1 26 25 24 23 22 21 20 • Fill in the rest with 0s. 0 s. Which gives us, 1011001. If you wanted to verify this answer, 89 = 1 × 26 + 0 × 25 + 1 × 24 + 1 × 23 + 0 × 22 + 0 × 21 + 1 × 20
(5)
Exam tip: On the multi multiple ple choice choice,, you you do not have have much much time. time. Theref Therefore ore,, instea instead d of conve converti rting ng the number into binary slowly. Just check if the question asks for an odd number. If this is the case, the right most bit must exist. You can prove this yourself. Now we move on towards 32 bit number. To represent 89 in 32 bits, you use the same result. Except this time there are 26 zeros in front. 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0101 0101 1001 1001 5
Notice there is little spacing between every 4 bits. This is more visual, but it’s important for being organized. Since there are 32 bits, you expect there to be 8 chunks of 4 bits. Up till now now we have have only only been using using positiv positivee numbe numbers. rs. This This is bec b ecaus ausee negati negative ve numbers numbers add a small small layer of complexity. In order to make sure the computer can dierentiate between a negative and positive numbers, the left most bit is always reserved. Currently, there are two methods for dealing with negative numbers, 1. Sign and Magnitude Magnitude Method Method 2. Two’s Compliment Compliment
Sign Magnitude • If the number is negative, ip the left most bit to a 1. 9 = 00000000000000000000000000001001 −9 = 10000000000000000000000000001001
Caution: This method is simple, but it is almost never used. This is due to fact adding and subtracting are very dicult, and it leaves an ambiguous case for zero. You can literally have a −0 or +0. +0. +0 = 000 00000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 −0 = 10000000000000000000000000000000
Two’s Compliment • If the number is negative, ip the left most bit to a 1. • ip every every bit starting from the left to the right to a 1 until until the least signicant signicant bit. You do not ip the least signicant bit, nor do you ip the bits after 9 = 00000000000000000000000000001001 −9 = 11111111111111111111111111110111 This method is used as adding and subtracting are works normally, has a dened case for zero. The term least least signican signicantt is the right right most bit of your your number number if it was positiv positive. e. In the example example below, below, the least least signicant bit(LSB) is marked as L. 12 =0000 =0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1100 1100 Position of the LSB =000 =00000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0L00 =1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 0100 0100 −12 =1111 Binary and decimal are not the only two numbering systems. We also have hexadecimal system, remember hex means 16 so the maximum maximum number this system can represent represent is 15. But since we only have numbers numbers up to 9, we have to switch to alphabets. 0 1 2 3 4 5 6 7 8 9A B C D E F 6
This is technically a more ecient system for numbering as it uses less digits for larger numbers. Google uses a similar similar method for numbering numbering the amount of Youtube Youtube videos. As a referenc reference, e, I created created a table from everything I have talked about. Decimal 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Octal 0 1 2 3 4 5 6 7 8 9 A B C D E F
Hexadecimal 0 1 2 3 4 5 6 7 10 11 12 13 14 15 16 17
Binary 0 0 00 0 0 01 0 0 10 0 0 11 0 1 00 0 1 01 0 1 10 0 1 11 1 0 00 1 0 01 1 01 0 1 0 11 11 0 0 1 10 1 1 11 0 11 1 1
Binary to Hexadecimal When converting numbers from binary to decimal, simply take each block of 4 bits and convert them individually, =11111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 0100 0100 −12 =111 −12 = F F F F F F F 4
Binary to Octal When converting numbers from binary to octal, simply take each block of 4 bits re-bunch them starting from the left in groups of 3. Then convert each bunch of 3 directly into octal. =1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 0100 0100 −12 =1111 −12 =011111111111111111111111111110100 −12 = 3 7 7 7 7 7 7 7 7 6 4 Now we increase the diculty,
7
Floating Point Numbers in Binary (Watch the Two Videos) Floating point numbers are simply real numbers. Numbers such as 21.23. 23. The problem is, how do we get decimals into binary, we can’t really do 1001.1101. 1101. Luckily, the common standard we learn in class is IEEE 754. It contains an sign, exponent, and mantissa. Left Left most most bit is allocat allocated ed for sign, sign, follo followe wed d by 8 bits bits for the exponent exponent,, and 23 for the mantiss mantissa. a. That’s That’s right, we will be using 32 bits for this method. For more visual learners, the format follows as, [sign][exp(8)][mantissa(23)]
Steps for converting a real number R to IEEE 754 Single Precision Binary 1. Determine Determine the sign. sign. If the number number is positive, positive, the sign is 0, if it is negative negative the sign is 1. 2. Find the greatest greatest power power of 2 that’s less than R. 3. To determine determine exponent, exponent, take the greatest power power of 2 that’s that’s less than R(we shall call it i). Plugging i into the formula, exp = exp = 127 + i We get the exponent in decimal, represent this number in binary plug into allocated exp place. 4. Take the numbers numbers after after decimal, decimal, if any, any, and multiply multiply it by 2. 5. If the number number is now now greate greaterr than than or equal to one make make note note of it, subtrac subtractt one. one. Contin Continue ue to the next step if the number is now zero or you nd a pattern, else go back to step 4. 6. Take the ones which which you noted multiplying multiplying by 2, and write them them in a row. This is your binary value value for the mantissa. Rewrite the value as follows. Eg: (oor( oor(N ))2 .[Mantissa] 7. Move Move the decimal decimal i places to the left. 8. Copy Copy everything everything after the decimal into the space for your mantissa. mantissa. 9. Fill any any blank spots with with zero.
You can see how long this method is, on the exam you will need to do this fast I would love to say I am going to do an example, however words are never going to explain it better than these two videos: Decimal to Binary Binary to Decimal
Exam Tip: For the multiple choice, instead of validating the mantissa, check if the sign and exp match. 8
2 The C Language Using English, we are able to use multiple letters to form words, then use these words to form sentences, and sentences to form proper arguments. However, computers speak in binary, this is due to the fact that an electrical electrical signal can either either be on or o. People People didn’t want want to look at a screen lled with ones and zeros, zeros, so instead they created Assembly language. Assembly language utilized human readable hexadecimal values instead of ones and zeros, and mnemonic codes to perform tasks which made it simpler than machine language. Now, we get to the type of language which we know today. So called “high level languages” such as: C, Fortra Fortran, n, Java, Java, and Python. Python. This made programming programming availabl availablee to the masses as you could write a program and never care about the registers or memory allocation. C is one of the most widely known programming languages around. But why is this the case? C is portable, ecient, easy to learn, and modular. It teaches proper memory management, and forces the programmer to care about system resources and clean code. In this class we use C to program solutions to various problems,
Steps for Solving Problems 1. Dene the the Problem Problem 2. Analyse Analyse the Problem Problem 3. Design Design a solution solution 4. Implemen Implementt solution 5. Test the Program Program 6. Update and maintain maintain the program program
Steps for Implementations 1. Write the program program 2. Compile Compile the program program 3. Build the the program program 4. Run the the program program You will not be tested for remembering any of the steps above, but project cycles, maintenance, and design are important aspects of software engineering.
Denition: A preprocessor is a system program that modies the program prior to compilation Denition: A preprocessor directive is instructions for the preprocessor, beginning with # Denition: A library is a collection of functions, symbols, and values. In C there are two types of preprocessor directives #include
and #define
Each Each command is terminate terminated d with a semi-colon( semi-colon(;). ;). The compiler compiler has no sense of tabs or line numbers, numbers, but it is case sensitive. 9
Denition: A comment is a line or lines of code which is ignored by the complier. To declare a comment, we generally use “// Single Line Comment” or “/* Multi line Comment */” We have talked talked about functions functions in math. It can be b e thought of as some black box that takes some input and produces produces some output output.. In progra programmi mming, ng, it’s it’s the same as math, math, excep exceptt we call inputs inputs as functi function on arguments. f (x,y,z )
(6)
Where f is some function, x, y , z are some inputs. In the same you can see how programming programming is almost identical, f u n c t i o n _ n am am e ( a r g u me me n t _ 1 , a r g u me me n t _ 2 , a r g u m e n t _ 3 ) ;
Just like f is a function, now you have a function with the name “function_name”, and it takes in 3 arguments just like x,y ,z . This will provide an output based on the arguments.
10
3 Lear Learni ning ng The The Ba Basi sics cs The general skeleton of a program is, 1
#include
2 3 4 5 6 7
i nt m a i n ( void ) { / / T hi h i s i s y o ur u r m ai a i n f u n ct ct i on on return (0); }
By the time you nish this course, you should be able to blindly type this code. Let us dissect this template, #include
This statement statement informs the preprocessor preprocessor that some functions functions in our program may be b e dened dened in the stdio.h stdio.h librar library y. The stdio.h stdio.h librar library y is simply simply short for “Stand “Standard ard Input Output Output Library” Library” and contai contains ns a vast majority of the functions we will learn about. i nt m a i n ( void )
In C, when when the le is being being compil compiled. ed. The compil compiler er searches searches for a functi function on called called main. main. Since Since main is a function function it will take inputs, inputs, but as you can see the arguments arguments are “void” “void”.. In the very very beginning of this line you see “int” this is to inform the compiler, this function will return an integer value. return (0);
This line is simply following suit as we are supposed to be outputting an integer value from this function. Therefore, we simply return the integer 0. In C, there are 4 main variable types we care about 1. integer (int)
eg. 3
2. Single Precision Floating Point (oat)
eg. 3.14
3. Double Precision Floating Point (double)
eg. 3.1415
4. Character or String (char)
eg. ’c’ or “Hello”
In order to declare a variable you must write the type, followed by the name and data stored. /* < t yp yp e > < v a r ia i a b le l e n am am e > = < s t or o r e d v al a l ue ue > ; T he h e f ol o l l ow ow i ng ng b el e l ow o w a re r e a f ew ew e xa x a m pl pl e s o f d ef e f in i n i ng ng v a ri ri a bl bl e s */ i nt a = 2 7 ; i nt b = 2 0 ; char g r ad ad e = ' A ' double p i = 3 . 14 14 1 59 59 2 65 65
This might seem easy, but you need to know what classies as a identier name by the compiler.
11
3.1 Har Hard d Rule Ruless for for Iden Identi tiers ers 1. It can only contain underscor underscores, es, letters, letters, and numbers numbers ( _ , ABC , 123) 2. It cannot begin with a number (3var_na (3var_name) me) 3. It cannot be a keywor keyword d (if, else, while, not, etc) etc) Additionally, there are conventions in the Computer Science eld for variable names. It would be correct not to follow the rules below, but your co-workers would probably kill you
3.2 Soft Soft Rule Ruless for for Iden Identi tiers ers 1. Constant Constantss are all capital letters letters (eg. double PI = 3.14) 2. Identier Identierss are are all lower lower case (eg. int class_av class_average erage = 33) 3. It cannot be b e another identier identier unless your intenti intention on is to reassign a function function or variable ariable 1
#include
2 3 4 5 6 7 8
i nt m a i n ( void ) { / / T he he f ol o l l ow ow i ng ng a re r e n on on - v a li l i d i de d e nt n t if i f ie i e rs r s , t ry ry a nd nd f in i n d o ut u t w hy hy . i nt 4 a = 7 ; i nt T h e r e - a re re = 7; i nt n t i f = 7;
9
/ / T h e f ol o l l ow ow i ng ng a re r e v al al id id , b ut ut n ot ot g oo o o d e ti t i q ue ue t te te i nt p i = 3 .1 . 1 41 41 5 ; i nt p r in in tf tf = 7 ; /* p i w il i l l n ev e v er e r c ha ha ng n g e , t he h e r ef ef o re re y ou ou c o ns ns id i d e r i t a c on o n s ta ta n t i n t he he p ro r o gr g r am am . H ow o w e ve ve r , a m o re re c o mm m m o n a p p li l i c a ti ti o n a r e r e s ol ol u t io i o n v a r ia ia b l es e s : S C RE R E E N_ N _ W ID I D T H , S C R EE E E N _ SI SI Z E */ /* p ri r i nt n t f i s n o t a k ey e y wo w o rd r d i n C , b ut ut i t i s a f un u n ct c t io i o n f ro r o m t he he s td t d io io . h l ib i b ra r a ry ry . W e c an an u se se t he he w or o r d p ri r i nt n t f f or or d ef e f i ni ni n g v ar a r ia i a bl b l es e s , b ut ut s in i n ce c e t hi h i s i d en en t if if i er er h as a s a lr l r ea e a dy d y b ee e e n u s ed ed , i t s h o ul ul d n ot ot b e r e d ef e f in in e d */
10 11 12 13 14 15 16 17 18 19 20 21 22 23
}
12
3.3 Placeh Placehold olders ers for for IO Stat Stateme emen nts In this course, only the following placeholders will be used, 1. %f - Floating Point Point (oat) (oat) 2. %lf - Long Floating Point Point (double) 3. %d - Integers Integers (int) (int) 4. %c - Characters Characters (char) (char) 5. %s - String String (char (char x[n]) We now consider the spacing on the output, %N d
N is the number of assigned space for an integer, it begins to ll the space from right to left
%.N d
N is the number of assigned space for an integer, it begins to ll the space from left to right
This lls the place holders to the left with zeros % w.d lf
w is the total space allocated for this double d is the number of spaces reserved after the decimal point
Note: w is the space space includ including ing the integ integer er and decima decimall part part of a oatin oatingg point point numbe number. r. The intege integerr portion is always prioritized over the decimal. Therefore, if you have an l number of digits for the integer component, the spots left for the decimal is w − l . If w − l ≥ d then the result is exactly what you would expect, otherwise it would truncate(round) the decimal earlier. Caution: If you use a wrong placeholder, the number will print zero. These place holders are used IO functions like printf, scanf, and fscanf. p r i n t f (" ( " S tu t u ff f f t o p ri r i nt n t : % d ", ", i n t e ge ge r _ v ar ar i a b le le ) ;
Some people learn better by example, 1
#include
2 3 4 5 6 7
i nt m a i n ( void ) { i nt x = 1 43 43 ; float y = 1 4. 4. 4; 4; double z = 2 7 .9 .9 1 92 92 0 ;
8 9 10 11 12
/ / Y o u c an an p ri r i nt nt p r i n t f (" ( " V al al ue ue o f p r i n t f (" ( " V al al ue ue o f p r i n t f (" ( " V al al ue ue o f
m u lt lt ip i p l e v ar a r i ab ab l es es a s l o ng n g a s t h e re r e e xi x i st s t s p l ac ac e ho h o l de de r s f or or e ac a c h v al a l ue ue . x : % 4 d = % .4 .4 d \ n" n" , x , x ) ; / / T he he \ n p ri r i nt n t s a n ew e w li l i ne ne y : % f \ n ", ", y ) ; z : % l f = % 5. 5. 3 lf lf = % 2. 2. 9 lf lf = % 0 0l l f \ n ", ", z , z , z ) ;
13 14 15
return 0; }
Try and grab a piece of paper to determine the output. The answer is on the next page.
13
Note: The rst time x is printed, the output is shifted one to the right due to the unused space allocated.
3.4 3.4 Poin ointers ters Pointers are unbelievably useful, but it’s tricky to understand. Imagine you had an integer x with the value, i nt x = 5 ;
We know x is a variable, so therefore it must be stored somewhere in memory. To get the address(location) of where it is located, you can use the & operator. We should note that the address is not the value of the variable. Try this code, #include 2 i nt m a i n ( void ) 3 { 4 i nt x = 5 ; 5 p r i n t f (" ( " Th T h e v al al ue u e o f x i s % d \ n" n" , x ) ; 6 p r i n t f (" ( " Th T h e a dd d d re r e ss s s o f x i s % p \ n" n " , & x) x) ; 7 return (0); 8 } 1
You will notice, the second value that prints just seems like garbage number. This is in-fact the memory address where the integer is stored. Now you may ask why would you ever want to use pointers? To which I wo would uld reply reply with with anothe anotherr questi question. on. Imagin Imaginee you you had a house, house, and you you wa want nted ed to call call a plumbe plumberr over over to your house. house. How How do you you get a plumbe plumberr to come come over? over? I don’t don’t think any any logical logical person person would would bring bring the house to the plumber. Instead, you would call up the plumber and tell them your home address. The plumber can then come over do their job. Similarly, if programming and you nd a point where a function(plumber) needs to work on something complex like a matrix or multi-dimensional array(house). You send over the address. Moving huge chunks of data and recreating multi-dimensional arrays multiple times is cumbersome and simply bad code. We have a specic type of variable variable that contains contains the address of another another variable. variable. This is what we call a pointer. We can dene a pointer as, < t y pe pe o f p o in in t er er > * < p o i nt nt e r n am am e > = < a dd d d r es es s >
So now, if you wanted a variable to point to x. We can do it as follows, #include 2 i nt m a i n ( void ) 3 { 4 i nt x = 5 ; 5 i nt * p t r = & x ; 1
6 7
p r i n t f (" ( " Th T h e a dd dd re re ss s s o f x i s : % p = % p" p " , p t r , & x) x) ;
8
14
9
p tr tr = NU N U LL LL ;
10 11 12
return (0); }
Major Major thing thing to notice notice is on line 7. I made made sure sure my pointer pointer was no longer longer pointin pointingg to x, instea instead d it’s it’s now now equal to null
PROPERLY CLEAR YOUR POINTER AT THE END OF YOUR CODE The whole reason why C is such an amazing language to learn is the simplicity and how it forces good memory management. Now you might be wondering. If there is an address stored, shouldn’t we be able to work backwards and see what what the addres addresss contai contains? ns? You are correct. correct. This This is called called dereferencing a point pointer er.. We use the *pointer_name to dereference a pointer. In the example above, we can use x = *p;
and that would be the same as saying, x = x;
3.5 3.5 Arra Arrays ys and and Stri String ngss 3.5. 3.5.1 1 Arra Arrays ys You can think of an array array as an ordered set. You understand understand sets from linear algebra, Z+ = { 0, 1, 2,...}. Likewis Likewise, e, you can dene a set of variables variables by using an array array. The general general form of an array array is shown shown belo b elow, w, < t yp yp e > < n a me me o f a rr r r ay a y > [ N u mb mb e r o f e l e me me n t s ( N )] ) ] = { E _0 _0 , E _ 2 , . .. .. , E _ ( N - 1 ) }; };
Imagine you wanted to store 5 integers, you can use the following code, i nt b u nc n c h_ h _ of o f _i _ i nt n t s [5 [5 ] = { 1 , 2 , 3 , 4 , 5 }
In order to pick out an element from the list, you can use the following code b u n c h _ o f _ i nt nt s [ e l e m e n t n u m b e r ]
Notice: In the genera generall form form,, we star starte ted d from from E 0 and went to E (N −1) . This This means means the num numberin beringg of elements begins at 0 instead of 1. Therefore, if you wanted to read the last element in the array, i nt l a s t _ e le l e m e nt n t = b u n ch c h _ o f_ f _ i n ts ts [ 4 ]
/ / l as as t el e l em e m en e n t is is e le l e me m e nt nt # 4
3.5. 3.5.2 2 Stri String ngss How do arrays relate to strings? Well a string is an array of characters as shown below. char < s t r i n g _n _n a m e > [ m a x _ l e t t e r s _ i n _ s t r i n g ] = " s o me m e s t ri r i n g "; ";
Notice: You do not use single quotes, instead you use double quotes for strings. A string and an array in the simplest simplest form is a poin p ointer. ter. When declaring declaring a string string or an array, array, it is necessary necessary to inform the complier the amount of memory to be allocated towards it. After the memory is allocated, there is a pointer used to keep track and grab values from the assigned memory. This process is similar to those old multi-disk music players from the early 90’s.
15
3.5.3 3.5.3 String String Array Arrayss You may want to create an array of strings. The code for such an idea is shown below. i nt * a r ra r a y _o _ o f _s _ s t ri ri n gs g s [ 5 ] = { " H e l l o " , " M y " , " N a m e " , " i s " , " S t u d e n t " };
The main dierence between a regular array and an array that can store strings is shown in the code above. For an array which can store strings, you use an array pointer (which is why you use of the ∗). If ∗ was missing, missing, then it would would be a regular character character array array that can hold 5 charact characters. ers. With the ∗ , it means it can hold 5 strings.
3.5.4 3.5.4 Two Dimensiona Dimensionall Arra Arrays ys You might feel very very familiar with two dimensional dimensional arrays as act like matrices. matrices. You can visualize visualize a two two dimensional array using the gure below,
a11 a12 .. ...
a1 j
a21 a22 .. ...
a2 j
.. .
ai1
.. .
...
.. .
ai2 . . . aij
In order to create a two dimensional array, you would use the following code < t y pe pe > < a r r a y n a me me > [ i ] [ j ]
In this class, you are being asked to use the Row-major order. Theref Therefore ore,, in the code above, above, i is the column number and j is the row number. As an example, to create a 7 by 7 array of integers, you would use the following code. i nt m a t r i x [ 7 ] [ 7 ] ;
Caution: Once again remember the index of an array begins at 0. Therefore, a11 is column 0 and row 0.
16
3.6 3.6 Arit Arithm hmet etic ic 3.6.1 3.6.1 Evalua Evaluating ting Expressio Expressions ns For the most part arithmetic in code is evaluated the same way as math. 1. Expressions Expressions in parenthe parentheses ses () must must be evaluate evaluated d rst 2. Operators Operators are evaluate evaluated d in the order: order: *,/,+, -, % (More order of operations operations later) 3. All expressions expressions in are evaluate evaluated d from left to right right 4. If there is a oating oating point p oint type type value in an expressio expression, n, it will take precedenc precedencee over integer integerss 1
#include
2 3 4 5 6 7
i nt m a i n ( void ) { i nt x = 9 ; float y = 2 .5 .5 ; double z = 3 .1 .1 ;
8 9 10 11
float m = x / y ; i nt r = x * x + y * y + z * z ; double u = ( x * y ) * (1 (1 / x ) *( * ( z / ( x * y )) )) ;
12 13 14
return 0; }
The question is, what are the values of m, r, and u. Lets begin with m, float m = x / y
This is an integer divided by a oating point number, so the nal value is also going to be a oating point. m = 3.6000000 i nt r = x * x + y * y + z *z *z ;
For r, we have an integer, oat, and double all squared. i n t r = 9 ∗ 9 + ( 2.5 ∗ 2.5)+(3.1 ∗ 3.1). 1). Let us go through with the multiplication. i n t r = 81 + 6.25 + 9.61. 61. Since we are adding an integer to a oat and double, our nal result will be a oat. i n t r = 96.86. 86. But now now since since r can only store integers, we need to convert a double to an integer. This is where rule below comes into play, by this logic, r = 96. 96.
Note: If we change a oat/double to an integer, it will always round down to a whole number. Additionally, if we divide integers to get a decimal, it will be rounded down double u = ( x * y ) * (1 (1 / x ) *( * ( z / ( x * y )) )) ;
We can see u = 0, because we have 1/ x, which are two integers so it evaluates to zero.
17
3.6. 3.6.2 2 Cast Castin ing g Sometimes when doing arithmetic or dealing with functions of dierent types, it’s useful to temporarily chang changee the type of a variabl ariablee or the return return type of a funct function ion.. This This tempora temporary ry change change in type type is called called casting Take for example the code below: 1
# i n l cu cu d e < s t di di o . h >
2 3 4 5 6
i nt m a i n ( void ) { i nt a = 2 , b = 3 ; double c = a / b ;
7 8
p r i n t f (" ( " Th T h e v al al ue u e o f c i s: s : % lf l f ", ", c ) ;
9 10 11
return (0); }
If you were to compile and run the program above, you would nd c = 0.000 Since we know since c is an double, double, the code’s code’s initial initial intent intention ion was to make make c = 0.6666 0.666677 = 2/3. Because Because a and b are intege integers, rs, it rounds down 0.6667 to 0.000. If we want to avoid such easy mistake, it’s a good idea to use casting. The following code below shows how to cast. ( < n e w t e m p t y pe pe > ) v a r i a b l e
In order to x the example above we would cast a double on a or b. 1
# i n l cu cu d e < s t di di o . h >
2
i nt m a i n ( void ) 4 { 5 i nt a = 2, b = 3 ; 6 double c = ( double ) a / b ; 3
7 8
p r i n t f (" ( " Th T h e v al al ue u e o f c i s : % lf l f ", ", c ) ;
9
return (0); 11 } 10
3.6.3 3.6.3 Shortc Shortcut ut Operato Operators rs In programming, programming, you sometimes sometimes need to repeat an action. Therefore Therefore for those repeated expressions expressions,, we have shortcuts. x a i i
= = = =
x *5 *5 ; a /2 /2 ; i +2 +2 ; i -2 -2;
Are the same as x a i i
*= /= += -=
5; 2; 2; 2;
18
3.6.4 3.6.4 Incremen Incrementt and Decremen Decrementt Operator Operator Similarly, you also use counter variables which require to increase by one or decrease by one each time. Instead of writing every time, i = i + 1; // or i += 1;
we use i++;
Similarly, instead of using, i = i - 1; // or i -= 1;
we use i--;
There are however two types. i ++ /* / * a nd nd * / ++ i
i++ runs through the code before incrementing the value, whereas ++i increments increments before evaluating. We
can easily show this with an example. #include i nt m a i n ( void ) { i nt a = 1 ; i nt b = 1 ; i nt x = a + + ; i nt y = + + b; b; return (0); }
In the end a = b = 2. But x = 1 and b = 2, this is because ++b increments before evaluating the expression, whereas a++ increments after.
3.6.5 3.6.5 Compar Compariso ison n Opera Operator torss This is going to be a short sub-subsection, but the most important. a a a a a a
< > <= >= == !=
b b b b b b
// // // // // //
is a is a is a is a d o es es d o es es
l e ss ss t ha ha n b g re r e at a t er e r t ha ha n b l e ss ss t ha ha n o r e q ua ua l t o b g re r e at a t er e r th th an an o r e qu qu al al t o b a e qu qu al al t o b a n o t e qu qu al al t o b
3.6.6 3.6.6 Logica Logicall Operato Operators rs By introducing logical operators you now get access to more complex comparisons. We have 3 main logical operators which you will be using in this class. 1. The && or and operator which means both sides of and has to be true 19
2. The || or or operator which means either side of or has to be true 3. The ! or not operator ips the truth value of the argument Imagine we are given the values, i nt a = 1 ; i nt b = 2 ;
what can you say about the following statements, (a (a < b ) & & ( b = = 2 ) 2 (a (a > b ) | | ( a = = 1 ) 3 (a != 5) && ( b = = 2) 4 ( b/ b / 2 = = 1 ) & & ( a/ a/ a = = a ) 5 (a ( a /2 /2 = = 0 ) o r ( 5 / b = = 2 ) 6 ( a /9 /9 = = 1 ) a nd nd ( 6/ 6/ b = = 4 6) 6) 1
• Line Line 1. (a is less less than b)(TR b)(TRUE) UE) and and (b is equal equal to 2) (TRU (TRUE) E) – True • Line Line 2. (a is greate greaterr than b)(F b)(FALS ALSE) E) or (a is equal equal to 1)(TRU 1)(TRUE) E) – True • Line Line 3. (a does not not equal equal 5)(TR 5)(TRUE) UE) and and (b is equal equal to 2)(TR 2)(TRUE) UE) – True • Line Line 4. (b divide divided d by 2 is 1)(TRUE) 1)(TRUE) and and (a divided divided by by a is a)(TRUE) a)(TRUE) – True • Line Line 5. (a divide divided d by 2 is 0)(TRUE) 0)(TRUE) or (5 divide divided d by b is 2)(TRUE) 2)(TRUE) – True • Line 6. (a divided divided by 9 is 1)(F 1)(FALSE) ALSE) or or (6 divided divided by b is 46)(F 46)(FALSE) ALSE) – False
Note: For line 5 and 6 remember the rounding rule for integers we discussed. Exam Tip: For stupidly long statements, look for or or if statements • For and, if one side is wrong, the whole statement is wrong. • For or, if one side is true, the whole statement is true.
3.6.7 3.6.7 Order Order of Operat Operation ion Now we discuss how the complier simplies and completes our code. 1. Function unction Calls 2. Unary Operatio Operations ns (a) Incremen Incrementt (i++) (b) Decremen Decrementt (i–) (c) Address Address (&a) (&a) (d) Positiv Positivee (+x) (e) Negative Negative (-x) (-x) (f) Not (!(x>y) (!(x>y))) (g) Casting Casting (double)int (double)int 20
3. Multiplicat Multiplication, ion, Division, Division, and Modulus 4. Addition, Addition, Subtraction Subtraction 5. Comparison Comparison Operators Operators 6. and statements 7. = operator You are expected to know how arithmetic works and what operations take precedence in a complex line of code.
21
4 Libraries In this course, we only use 3 dierent dierent libraries libraries.. So therefore, therefore, I will introduce introduce you to them and anything testable.
4.1 4.1 The The Math Math Libr Librar ary y To use the math library we need to inform the preprocessor that some commands used are dened in that library. #include
In the math library all functions below will return return oating point values values no matter the input type. Some important functions in this library are : sqrt(x) floor(x) ciel(x) log(x) log10(x) fabs(x)
// // // // // //
R et e t ur u r ns ns R e tu t u r ns ns R et e t ur u r ns ns R et e t ur u r ns ns R et e t ur u r ns ns R et e t ur u r ns ns
t he he s q ua u a re r e r oo oo t o f t he he i np n p ut u t ( eg e g . s qr q r t ( 69 69 ) = 8 . s om om th t h i ng ng ) t he h e n u mb m b e r r o un u n d ed e d d o wn wn ( e g . f l oo o o r ( - 1 . 2) 2) = - 2. 2. 0 ) t he he n um u m be b e r r ou o u nd n d ed e d u p ( e g . c ie i e l ( - 1. 1 . 2) 2) = - 1. 1. 0) 0) l og og b as as e e o f x o r l n( n ( x) x ) ( eg e g . l og og ( e) e ) = 1 .0 .0 ) l og og b as as e 1 0 o f x ( eg e g . l og og 10 1 0 ( 10 1 0 0) 0) = 2 .0 .0 ) a b so so lu l u t e v al a l ue u e o f x ( e g. g . f ab a b s ( - 1. 1 . 2) 2) = 1 .2 .2 )
Additionally, we have trig functions which use radians as input sin(x) cos(x) tan(x)
/ / R et e t ur u r ns n s t he he s in in e o f x ( eg e g . s in in ( PI P I ) = 0 .0 .0 ) // R e et t ur u r ns ns t h he e c os o s in i n e o f x ( eg e g . c os os ( PI PI ) = - 1. 1. 0) 0) / / R et et u ur r ns n s t he he t an a n g en en t o f x ( e g. g . t an a n ( PI P I / 4) 4 ) = 1 .0 .0 )
Next we have a few simple but testable functions exp(x) pow(x,y) atan(x)
/ / R et e t ur u r ns n s e ^x ^ x ( eg e g . e xp xp ( 1) 1) = e ) // R e et t ur u r ns ns x ^ ^y y ( eg e g . p ow ow ( 2 ,3 ,3 ) = 8 ) / / R et et u ur r ns n s a rc rc t an a n g en en t i n r an a n d ia ia ns n s ( e g . a ta t a n ( 1) 1) = p i /4 /4 )
4.2 4.2 The The Sta Stand ndar ard d Lib Libra rary ry To use the standard library we need to inform the preprocessor that some commands used are dened in that library. #include
We have some testable functions, abs(x) rand(x)
/ / R et e t ur u r ns n s a bs b s ol o l ut u t e v al a l ue ue o f x ( eg e g . a bs bs ( -1 -1 ) = 1 ) // Re et t ur u r ns n s a n i nt n t e ge ge r b et e t we w e en e n 0 a nd n d R A ND ND _ MA MA X
Note: RAND_MAX is a variable which can be modied by the user abs(3. 3.1) 1) = 3) Caution: abs(x) will only return an integer value (eg. abs( Exam Note: Remember the dierence between abs and fabs. Note their libraries.
4.3 The The Standa Standard rd Inpu Inputt Outpu Outputt Librar Library y To use the standard input output library we need to inform the preprocessor that some commands used are dened in that library. #include
The main important functions from this library is 22
i nt v a ri ri a bl bl e = 2 p r i n t f (" ( " v a r i ab ab l e % d ", " , v a r ia ia b l e ) 3 scanf("%d", & v a r i ab ab l e ) 1 2
/ / W il i l l p ri r i nt n t " v a ri r i ab ab l e 2 " // Ge et t s a n i nt n t eg e g e r f ro ro m u s se e r a nd nd s to t o re re s i t
We will go more in depth on these functions later and you will see them being utilized everywhere throughout this course. For any programs you write, this will be the default include.
23
5 Modes odes of Opera perati tion on There are two modes by which a program can operate. 1. Interact Interactive ive Mode - The program will print print words on the screen screen and ask for input. 2. Batch Batch Mode - The program will read and write write to a le.
5.1 In Inte terac ractiv tive e Mode The computer will have to interact with the user by printing statements to the screen and waiting for input. We already know how to use printf. printf is used below without any additional arguments 1
#include
2 3 4 5 6 7
i nt m a i n ( void ) { p r i n t f (" ( " d a t a ") "); return (0); }
This program will print out: “data”. To print out a variable, you have seen the use of placeholders and variables as additional arguments 1
#include
2 3 4 5 6 7 8
i nt m a i n ( void ) { i nt l u c k_ k _ n u mb mb e r = 4 2 ; p r i n t f (" ( " m y l uc u c ky k y n um u m be b e r i s % d ", " , l u c ky k y _ n um um b e r ) ; return (0); }
This prints out: “my lucky number is 42”. Now Now we want want user input. input. This This requir requires es the use of a functi function on called called scanf. The scanf function’s st argument argument is a string which which only contains contains placeholders. placeholders. The second or additional additional argument argument is the address of variables to store each input. The placeholder has to match the type of variable at the address given. #include i nt m a i n ( void ) 3 { 4 i nt x = 0 ; 5 s c a n f ( " % d " , & x) x) ; 6 reutrn(0); 7 } 1 2
If the user was required to input more numbers, numbers, we add more placeholders placeholders and variable ariable address. For each each place holder, the program will stall and wait for user input. Therefore, for the program below, it will stall 3 times. During each stall, an integer values must be input and the user must hit the enter key. #include i nt m a i n ( void ) 3 { 4 i nt x , y , z ; 5 s c a n f ( " %d % d % d % d " , & x, x , & y , & z) z) ; 6 return (0); 7 } 1 2
Note: Do not use anything else but placeholders in the quotations for scanf. 24
5.2 5.2 Ba Batc tch h Mode ode Imagine you had a le with the name “data.txt” containing the number 42. In order to read from the le, we use the following code. 1
#include
2 3 4 5
i nt m a i n ( void ) { i nt d a t a _ f r o m _ f i l e ;
6 7
F IL IL E * d at a t a = f op o p en e n (" ( " d a t a . t x t ", ", "r");
8 9
f s c a n f ( d a t a , " % d " , & d a t a _ fr fr o m _f _f i l e ) ;
10 11 12 13
fclose(data); reutrn(0); }
Let us begin to analyze this code, F I LE LE * d a t a_ a_ f i le le
We rst create a le pointer called data. f o p e n (" (" d a t a . t x t " , " r " )
To load a le, we use the function fopen. fopen takes takes two argument arguments. s. The rst argument argument is a string of the le name, and the second is the status. We set the status to “r” which means read only. fscanf( data_file , " % d " , & d a t a _ fr fr o m _ fi fi l e ) ;
fscanf is exactly like scanf, except the rst argument is now the le pointer. Each value we read, the le
pointer moves to the next value inside the le. fclose(data)
This deallocates the le pointer. We elaborate more on les after we cover loops. Now imagine imagine you wanted wanted to write write the number number 42 to a named “data.txt” “data.txt”.. The code is almost exactly exactly the same as reading, except now we use fprintf. 1
#include
2 3 4 5
i nt m a i n ( void ) { i nt d a t a _t _t o _ st st o r e = 4 2 ;
6 7
FI F I LE LE * d at at a = f op op en e n (" ( " d a t a . t x t " , " w " ) ; // / / T hi hi s t im im e t he he m od o d e i s w . T hi hi s i s t o w ri ri te te .
8 9
f p r i n t f ( d a t a , " % d " , d a t a_ a _ f r om o m _ f il il e ) ;
10
fclose(data); 12 r e u t r n ( 0 ) ; 13 } 11
You can notice the similarity between printf and fprintf. It’s almost identical identical but the rst argument argument for fprintf is the le pointer
25
6 The if Sta Stateme temen nt If you want to implement conditional logic into your code, then you should consider the if statement. The general form of the if stateme statement nt is: if ( c o n d i t i o n ) { / / do d o s o m et et h i ng ng } else { / / do d o s o m et et h i ng ng }
Recall : the condition condition is statemen statements ts or statemen statements ts combined combined with logical logical operators. We saw how statements and logical operators work in section 3.6.6. If the condition is true, the code inside the parenthesis will run. In other words, the condition is checked before running running any code inside the parenthesi parenthesis. s. The code inside the else statement will only run if the condition is false 1
#include
2 3 4 5 6
i nt m a i n ( void ) { i nt x = 2 ; i nt y = 3 ;
7 8 9 10
if ( x > 2 | | y = = 3 ) { p r i n t f (" ( " H e l lo lo W o rl rl d ") ") ;
11 12
/ / No No ti t i ce c e t he he f ir i r st s t c o nd n d it i t i on on i s f al al se se , s e co c o nd n d is i s t ru ru e / / D u e t o t he h e " o r" r " s ta t a te t e me m e nt n t , t he h e c on o n d it it i on on i s t r ue ue / / S o t hi h i s c od od e w il il l r un un
}
13 14 15
return (0); }
6.1 Else if If you know there there are many outcomes, outcomes, but only one of them is true. true. You can use an else else if statement. An els else e if statement is used directly after an if statement or another els else e if statement statement.. It optimizes optimizes your code, because if the initial if statement or any other else else if statement is true, then any els else e if or else statements below are skipped. You will nd the structure of an els else e if statement identical to that of a regular if statement. An example of using els else e if is shown below, 1
#include
2 3 4 5
i nt m a i n ( void ) { i nt x = 0 ;
6 7
p r i n t f (" ( " P l ea ea se s e i np n p ut u t a n um u m be be r : " ) ;
26
8
s c a n f ( " % d " , & x) x) ;
9 10 11 12 13 14 15 16 17 18 19 20 21
if ( x = = 0 ) { p r i n t f (" ( " Z er e r o i s s uc u c h a b or o r in i n g n um u m be b e r ") ") ; } e l se se i f( f( x > 0 ) / / N ot o t ic i c e t he he p o si si ti t i o n ( b e tw tw ee e e n i f a nd n d e ls ls e ) { p r i n t f (" ( " O hh hh a p o si si ti ti v e i n nt t eg e g er e r ") ") ; / / No N o ti t i ce ce t h he e i d en e n t ic ic a l s tr tr u ct ct u re re t o if if } else { p r i n t f (" ( " O hh hh a n e ga ga ti t i v e i nt nt e eg g er e r ") ") ; }
22 23 24
return (0); }
6.2 Neste sted if For more complex scenarios, you may nd yourself trying to use an if statement inside another existing if statement. This “if inside another if” is called a nested if statement. Below is an example to show the structure of a nested if statement. 1
#include
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
i nt m a i n ( void ) { i nt a = 2 ; in t b = 3 ; in t x = 4 ; in t z = 9 ; if ( a < b ) / / T hi h i s i s t he he m ai ai n i f s t ta a t em em e nt nt { x--; if ( (z ( z - 5) 5) = = x ) / / T hi h i s i s n e st s t ed e d i f s ta t a t em em e nt nt . I t i s i n si s i de d e a no n o th t h er er i f { p r i n t f (" ( " H e l lo lo W o rl rl d ") ") ; } else { p r i n t f (" ( " I s le le ep e p 1 4 h ou o u rs rs a d ay ay ") ") ; } } }
The code above will print “I sleep 14 hours a day”. You should note that if the main if statement is false, then the nested if statement’s condition is never checked. Because the code inside your main if statement is skipped.
27
7 Swit Switcch Stat Statem emen entt A switch statement is like an if statement, and is used when you have one condition and you know the possible output values. The general form of a switch statement is, switch ( v a r i a b l e ) { case v a l u e 1 : \ \ c od o d e h er er e break ; case v a l u e 2 : \ \ c od o d e h e re re break ; case v a l u e 3 : \ \ c od o d e h e re re break ; .. . default : \ \ c od o d e h e re re break ; }
/ / N ot o t ic i c e n o p a re r e n et et h es e s i s a re re b e i ng ng u s ed ed . // t th h e " b re re ak a k " ke k e yw y w or o r d i s us u s ed e d to t o en en d e a ac c h c as as e
The break keyw keyword ord in C is used to forcef forcefull ully y end loops. In the genera generall form, form, we can only end each case with a break. As an additional additional note, you must avoid avoid ending while or for loops using break, break, as it is typicall typically y considered as “bad code”. The example below shows one such use for using 1
#include
2 3 4
i nt m a i n ( void ) {
5 6
char R A M S S _g _ g r a de de = ' F ' ;
/ / T he he g ra r a de d e h as as b ee ee n se se t to to F
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
switch ( R A M S S _ g r a d e ) { case ' A ' : p r i n t f (" ( " Y o u p a ss s s e d ") ") ; / / T hi h i s c o de de w il i l l b e s k ip i p pe pe d break ; case ' F ' : p r i n t f (" ( " F ai a i li l i ng n g i s a p ar ar t o f l if i f e" e" ) ; / / T hi h i s c o de d e r un un break ; default : p r i n t f (" ( " U n k no n o w n I n pu p u t V a lu l u e ") ") ; break ; } return (0); }
If we run the code above, it will output the following statement: “Failing is a part of life”. This is because the RAMSS_grade is an ’F’, and the code has instructions to run in that specic case. Note, when none of the cases match the variable, then the default case runs.
28
8 Loops A loop is just something that repeats itself. if you notice you are copying and pasting something multiple times, chances are you need a loop. In C there are 3 kinds of loops 1. while loop 2. do while loop 3. for loop Again for the following section, I encourage you to pull up and compile the code yourself.
8.1 While A while while loop will will liter literally ally do somet somethin hingg while while a condit condition ion is true. true. The general general form of a while while loop is as follows, while ( c o n d i t i o n ) { / / C od o d e h e re re }
The condition is only checked before any of the code inside the parenthesis is run. If the condition is true, 1. The code inside the the parenthesi parenthesiss is run 2. At the end of the parenthesi parenthesis, s, the condition is checke checked d again 3. If the condition condition is still true, return return to step 1. If the condition is false, the code inside parenthesis is skipped. A very simple application of the loop is shown below, 1
#include
2 3 4 5 6 7 8 9 10 11 12
i nt m a i n ( void ) { i nt a = 2 ; i nt b = 1 ; while ( b ! = a ) { b++; } return (0); }
29
8.2 Do While ile Do whil whilee is exac exactl tly y the the same same as a whil whilee loop. loop. How However ever,, init initia iall lly y the the code code insi inside de do is run run befor beforee the the condition is checked. It has a general form, do { / / S om o m e c od o d e h er er e } while ( c o n d i t i o n ) ;
This type of loop is generally used for input validation, as it can be very simple to apply. The code below is an example of input validation using this loop. 1
#include
2 3 4 5 6 7 8 9
i nt m a i n ( void ) { i nt n u mb mb er er = 0 ; do { p r i n t f (" ( " P l ea ea se s e i np n p ut u t a n i nt n t eg e g er e r n um u m be b e r b e tw tw ee e e n 0 a nd nd 2 5: 5: ") ; s c a n f ( " % d " , & n u m be be r ) ;
10 11
} while ( n um u m be b e r < = 0 | | n um u m be b e r > = 2 5) 5) ;
12 13
p r i n t f (" ( " \ n T h an an k y o u ") ") ;
14 15 16
return (0); }
Notice: There is a semi-colon after the while statement.
8.3 for Loop oop A for loop should only when you know the amount of loops to perform before hand. The general form of such a loop is as follows, f or ( i n i t ia i a l _ co c o d e ; c o n di d i t i on on ; u p d a te te _ i n st s t r u c ti ti o n ) { / / D o s o m et et h i ng ng }
The loop follows the following steps, 1. initial_code is run when the loop initializes 2. Check Checkss if the condition is true, if yes proceed to next step, if not exit the loop. 3. Run the code inside the parenthesi parenthesiss 4. The update_instruction is run 5. Return to step 2 The reason why this loop is so useful, is because of the inbuilt initial_code and update_instruction. These These two two pieces pieces of code are typic typicall ally y used used to setup and run a count counter er for the loop. The condition is used to end the loop. An example of a for statement in use is, 30
1
#include
2 3 4 5 6 7 8 9 10 11 12 13
i nt m a i n ( void ) { f or ( in t i = 0 ; i < 2 0 ; i ++ ++ ) { if ( i %2 %2 ! = 0 ) // T he he p er e r ce c e nt n t m ea ea ns n s r em e m ai a i nd n d er e r a ft ft er e r i i s d iv i v id i d ed ed b y 2 { i++; } p r i n t f (" ( " Th T h e v al al ue u e o f i i s: s : % d" d" , i ) ; } }
Try and nd out what the code above will print.
31
9 Deal Dealin ing g with with Fil Files es usi using ng Loop Loopss 9.1 9.1 Read Readin ing g a Whol Whole e File File Imagine Imagine we have a le called “data.dat” “data.dat”.. Inside this le, we have have the following following values tabulated. tabulated. 1 2 3 4 5
92 88 97 90 94
Since I am an Electrical Engineering student, for the second semester I only take 5 courses. The numbers indicate each of my course averages. Your job is to take these 5 courses and nd the TGPA. We require 5 fscanfs. Try to think of a way to do this. The answer is below. 1
#include
2 3 4 5
i nt m a i n ( void ) { F IL IL E * d at a t a = f op o p en e n (" ( " d a t a . d a t ", ", "r");
6 7 8
float t e m p ; float t g gp pa = 0;
9
/ / E x tr t r ac a c t a l l t h e c o u rs rs e d a t a a nd n d c ha h a ng n g e t o g pa pa f or ( in t i = 0 ; i < 5 ; i ++ ++ ) { f s c a n f ( d a t a , " % d " , & t em em p ) ;
10 11 12 13 14
if ( t em em p > = 9 0) 0) { t gp g p a + = 4 .3 . 3 3; 3; } e l se se i f( f ( 9 0 > t e m p & & t e m p >= 8 5 ) / / S am am e a s ju j u st s t a n o th t h er e r i f s t at a t em e m e nt nt { t gp g p a + = 4 .0 . 0 0; 0; } e l se se i f( f ( 8 5 > t e m p & & t e m p >= 8 0 ) { t gp g p a + = 3 .6 . 6 7; 7; } / / Y ou ou c an an f il i l l t h e r e st st b e lo lo w , b ut ut t hi hi s s h ou o u ld l d c ov ov er er a l ll l t he he a v ve e rg r g ae a e s i n t he he f il il e
15 16 17 18 19 20 21 22 23 24 25 26 27
} t gp gp a /= /= 5; 5;
28 29 30 31
p r i n t f (" ( " My M y T GP GP A = % .3 .3 f ", " , t gp gp a ) ;
32 33
fclose(data);
34 35
return (0);
36 37
}
32
9.2 9.2 Writi riting ng to File Filess Time to step it up a notch. Imagine you created a game. Every time your friend and you play, it always starts a ght because no one kept track of score. Requirements from your code: • You will write code to store data for one game • There are 5 rounds per game, you will ask who won each round • You should expect input of “1” or “2” as the winner of each round. round. Input Validat Validation! ion! • Every Every round round should should be stored stored on a new line line in the data data le • At the end of each game, you must must include the phrase “END–” on a newline followed followed by two two additional newlines. • You must declare declare who won at the end The answer is below. 1
#include
2 3 4 5 6 7
i nt m a i n ( void ) { i nt c u r r _ w i n ; i nt d e c i d e _ w i n ; F IL IL E * d at a t a = f op o p en e n (" ( " d a t a . d a t ", " , " a " ) ; / / " a " m od o d e a pp p p en e n d s e x is is t in in g f il il e
8
f or ( in t i = 0 ; i < 5 ; i ++ ++ ) { do { p r i n t f (" ( " P l ea ea se s e e nt n t er e r v al a l id i d r es e s ul u l t s f ro r o m r ou o u nd n d % d : " , i +1 +1 ) ; s c a n f ( " % d " , c u r r_ r_ w i n ) ;
9 10 11 12 13 14 15
} while ( c ur u r r_ r _ wi w i n ! = 1 & & c ur u r r_ r _ wi wi n ! = 2 ) ;
16 17
if ( c u rr r r _ wi wi n = = 1 ) { decide_win++; }
18 19 20 21 22 23 24 25
f p r i n t f ( d a t a , " % d \ n " , c u rr r r _ w in in ) ;
} f p r i n t f ( d a t a ," , " E N D - - \ n \ n ") ");
26 27 28 29 30 31 32
if ( d e c i de d e _ w in in > = 3 ) { p r i n t f (" ( " P l ay ay er e r 1 w in i n s ") ") ; } else {
33
33 34
p r i n t f (" ( " P l ay ay er e r 2 w in i n s ") ") ; }
35 36
fclose(data);
37 38 39
return (0); }
34
10 Independe Independent nt Functio unctions ns 10.1 Create Create Your Your Own Functions unctions Independen Independentt functions functions are functions functions other than main(void). We discussed this earlier when studying the basics, basics, but now we are going to be creating functions. functions. In order to declare declare a new function function we can follow the outline below. below. () { / / C od od e t o r un un }
Your function needs to be above main unless we use forward declaration. The following is an example of how to use a function. 1
#include
2 3 4 5 6
i nt p r i n t _ n u m b e r ( in t n u m b e r ) { p r i n t f (" ( " N um u m be b e r y ou ou w an an t t o p ri r i nt n t i s % d ", ", n u mb mb e r ) ; }
7 8 9 10 11 12
i nt m a i n ( void ) { print_number(42); return (0); }
We mentioned the use of forward declaration. It is done by leaving a snippet the undened function above the main. We can then properly dene the function after the main later. The undened snippet looks as follows < r e t u r n _t _t y p e > < f u n c t i o n_ n_ n a m e > ( < a r g u m e nt nt s > ) ;
As an example, we can rewrite the code above as, 1
#include
2 3
i nt p r i n t _ n u m b e r ( in t n u m b e r ) ;
4 5 6 7 8 9
i nt m a i n ( void ) { print_number(42); return (0); }
10 11 12 13 14
i nt p r i n t _ n u m b e r ( in t n u m b e r ) { p r i n t f (" ( " N um u m be b e r y ou ou w an an t t o p ri r i nt n t i s % d ", ", n u mb mb e r ) ; }
The code looks more cleaner for larger programs. The snippet informs the compiler not freak out when it sees this function as it’s dened later in the le. More examples are available in the section on recursion.
10.2 10.2 Multi Multiple ple Return Return Values alues Sometimes Sometimes you may want want a function function to return return more than one value. value. To deal with this, you are required required to use pointers pointers (or address). address). If you send a variable variable address as an argument argument to a function, then the function 35
can manipulate the stored value at that address. #include 2 # i n l cu cu d e < m a th th . h > 1
3 4
i nt s p l i t _ d e c i m a l ( double n u m , double * f r a ct c t i o na n a l _ p ar ar t ) ; double address
/ / E x pe pe ct c t s a do d o ub u b le l e a nd nd a
5 6 7 8 9
i nt m a i n ( void ) { double f r a c t i o n a l _ p a r t ; i nt i n t e g e r _ p a r t ;
10 11 12
/ / & i n t e ge g e r _ pa p a r t i s t h e a d dr d r e ss s s o f i n t e g er e r _ p ar ar t i n t eg e g e r _p _ p a r t = s p l i t_ t_ d e ci c i m a l ( 3. 3 . 1 4 , & i n t e g e r _p _p a r t ) ;
13 14 15
p r i n t f (" ( " T he he i nt n t eg e g e r p ar a r t i s : % d \ n ", " , i n t eg e g e r _p _p a r t ) ; p r i n t f (" ( " T he he f r ac ac t io io n al a l p ar a r t i s % l f" f " , f r a ct c t i o na n a l _ p ar ar t ) ;
16 17 18
return (0); }
19 20 21 22 23 24 25
i nt s p l i t _ d e c i m a l ( double n u m , double * f r a ct c t i o na n a l _ p ar ar t ) { * f r a c t io io n a l _p _p a r t = n u m - f l oo o o r ( n um um ) ; / / De De r ef e f e re r e n ci ci n g th th e ad a d dr d r es e s s a ll ll ow o w s me me y ou ou to to / / c h an a n g e t he h e v a r ia ia b l e d i re r e c t ly ly . return ( f l o o r ( n u m ) ) ; }
10.3 Using Tw Two Dimensional Dimensional Arrays Arrays with Independen Independentt Funct Functions ions In order to send two dimensional arrays into functions as arguments, the function argument needs to contain contain the maximum maximum row value expected. expected. As an example, example, a function function expecting a two two dimensional dimensional array of 200 row elements maximum would be ( [][200])
If the function’s name was “nd_border” with a return type double, expecting a two dimensional double array named “mama_mia” of size 200. Then follow the code below. double f i n d _ b o r d e r ( double m a m a _ m i a [ ] [ 2 0 0 ] )
36
11 Recur ecursi sion on Recursion Recursion is a bit nicky nicky but useful. useful. Especially Especially if you want to backtrack backtrack in programs. programs. Recursion Recursion in the simplest terms is a process which calls itself to solve a smaller problems of itself (weird). In this course we have simple applications such as nding a factorial or subtracting a number constantly. As an example, to nd a factorial of any number input you can use the following code. 1
#include
2 3 4 5 6 7 8 9 10 11 12 13
i nt f i n d _ f a c t o r i a l ( in t c ) { if ( c = = 0 ) { return 1; } else { c * = f i n d_ d _ f a c to to r i al al ( c - 1 ) ; } }
/ / w e k n ow ow w e c a n s o lv lv e 0 ! = 1
/ / S ol o l ve v e s a s m al a l le l e r v e rs r s i on on o f t h e p ro r o bl b l e m u si s i ng n g i t s el el f
14 15 16 17
i nt m a i n ( void ) { i nt c , r ;
18 19 20
p r i n t f (" ( " P l ea ea se s e e nt n t er e r a n um u m be be r : " ) ; s c a n f ( " % d " , & c) c) ;
21 22 23
r = fi fi n d _ fa fa c t o ri ri a l ( c ) ; p r i n t f (" ( " T he he f a ct ct o ri ri a l i s : % d " , r ) ;
24 25 26
return (0); }
The example below is another use of recursion. We nd the greatest common factor. 1
#include
2 3 4 5 6 7 8 9 10 11 12 13
i nt gcd( in t x , in t y ) { if ( y = = 0 ) { return x ; } else { g cd cd ( y , x % y ) ; } }
14 15 16 17
i nt m a i n ( void ) { i nt g , r , a ns ns ;
18 19 20
p r i n t f (" ( " P l ea ea se s e e nt n t er e r t wo w o n um u m be b e rs rs : ") scanf(" % d % d ", & g g, , & r) r) ;
37
21 22 23
a ns n s = g cd cd ( g ,r ,r ) ; p r i n t f (" ( " T he he g re r e a te te s t c om o m mo m o n d e mo mo n in i n a to to r i s : % d ", ", a ns ns ) ;
24 25 26
return (0); }
To make sure you do not get lost when deal with these recursive functions. Always develop a mathematical way of looking at your recursive function. For example, in the code above we have the following function for gcd. gcd( gcd(x, y ) =
�
if y = 0 gcd( gcd(x, remainder( remainder(x, y )) if y > 0 x
(7)
You can compute the output without rereading the code multiple times. For more complex examples, try solving the “N Queens Problem”.
38
12 Dyna Dynami micc Mem Memor ory y All Alloca ocati tion on For dynamic memory allocation we will be using functions from the standard library. #include
Dynamic memory allocation is used when we don’t know how much memory we are going to be using. Remem Remember ber when I said that an array array could could be though thoughtt of as a pointer pointer.. Now Now we are going to create create an array using a pointer. In order to create a dynamic one dimensional array of integers, 1 2
#include #include
3 4 5 6
i nt m a i n ( void ) { i nt a m o u n t ;
7 8 9
p r i n t f (" ( " P l ea ea se s e e nt n t er e r t he h e n um u m be b e r o f i n te te ge g e r s i n y ou o u r a rr r r ay a y ") ") s c a n f ( " % d " , & a m o un un t ) ;
10 11 12 13 14 15 16 17 18 19 20 21 22 23
i nt * a r r a y = ( in t * ) m a l l o c ( a m o u n t *sizeof * sizeof ( i nt ) ) ; if ( a rr r r ay a y ! = N UL UL L ) { fo r ( in t i = 0 ; i < a mo mo un un t; t ; i ++ ++ ) { p r i n t f (" ( " P l ea ea se s e e nt n t er e r i nt n t eg e g er e r % d : " , i + 1) 1) ; s c a n f ( " % d " , & a r r ay ay [ i ] ) ; } p r i n t f (" ( " A l l i n t eg eg e r s s t or o r e d ") ") ; } free(array); return (0); }
This may look confusing. But let me help digest this new code. i nt * a r r a y = ( in t * ) m a l l o c ( a m o u n t * sizeof ( i nt ) ) ;
This line is basically the only “new” code. malloc(size_in_bytes)
malloc allows us to allocate memory in bytes sizeof ( in t )
returns the size of an integer in bytes a m o u n t *sizeof * sizeof ( in t )
amount is the number to be stored in an array. So the total size the array will use is amount multiplied by
the size of an integer. ( in t * ) m a l l o c ( a m o u n t * sizeof ( in t ) ) ;
using (int (int *) is technically not needed but to be verbose we need to change the type to something a pointer can hold. i nt * a r r a y = ( in t * ) m a l l o c ( a m o u n t * sizeof ( i nt ) ) ;
39
So therefore, this piece of code assigns the total amount of memory which is going to be accessed through this pointer. Notice how the use of accessing data is still the same notation used for arrays array[element]
We need to make sure the memory allocated to the array is deallocated and free to use by the system again free(array);
In C we can use two commands to allocate space 1. malloc 2. calloc malloc only uses one argument which is the total space to allocate. m a l l o c ( a m o u n t *sizeof * sizeof ( i nt ) )
But calloc takes two arguments which number of them to allocate and the type respectively calloc( amount , sizeof ( i nt ) )
In the previous example, we can replace line 11 with the following i nt * a r r a y = ( in t *)calloc (amount , sizeof ( i nt ) ) ;
The main advantage of using calloc over malloc is that it allocates space, but also zeros the data spaces allocated. In doing so, malloc is eectively slower than calloc. In our previous example, we don’t care if the initialized array is all zeroed.
Note: Two dimensional dimensional dynamic arrays arrays are not important for this course. course. Howeve However, r, you should underunderstand how to use arrays and two dimensional array with functions. Exam Tip: You have to know how to create a dynamic array; as shown above; by hand.
40
13 Link inked Lists ists Do you remember remember those detective detective shows? shows? There is always always one chiché chiché scene in the detective detectivess house where a wall is lled with red string attached to tacks holding up paper clippings. Each tack contains data, but it also holds the string to the next tack.
Well, it’s almost like a linked linked list. In programming programming terms, each tack would would be b e called a node, and the string would wo uld be the links. links. Each Each node is located located at some address address,, and it is joined joined to other nodes nodes by links. links. Each Each node contains data and the location of the next node. Currently, we can’t represent a node by a variable, because because we can store two two data data types types in one. one. This This means means we have have to create create a composit compositee data data type. type. The general form for creating a new data type is as follows t y p e d e f s t r u c t NODE { struct N OD O D E * p tr tr ; i nt d a t a ; } n od od e ;
Let’s explain some of this code in easier context. typedef is used to rename data types. t y p ed ed e f i nt nt p e e w e e ; p ee ee we we e a = 2 ;
/ / w e j us u s t re re na n a m ed ed th t h e k ey e y wo w o r d i nt n t to to pe p e ew e w ee ee
struct struct > {} is used to create create a composi composite te data type. type. What’s What’s annoyin annoyingg is every every time time you create a new structure. You have to use struct struct to refer to it. struct i n t _ a n d _ f l o a t { i nt a ; float b ; } struct i n t _ a n d _f _f l o at at v a r ;
/ / N ew ew c om o m po p o s it it e da d a ta t a ty t y pe p e to to ho h o ld l d an an in i n t a nd nd fl f l oa oa t
/ / D e ca ca l ri ri n g n ew ew v a r ia i a bl b l e t o b e t yp yp e i n t _a _a n d_ d _ f lo lo a t
So we can rename struct struct int_and_float int_and_float to something easier to use typedef struct int_and_float / / t yp y p e de de f i s r em e m ai a i n g t he h e w ho h o le l e s tr t r u ct ct u re re { i nt a ; float b ; } i af af ; / / N ot o t ic i c e t he h e s em em i - c ol o l on o n . T hi hi s i s t h he e l in i n e e nd nd f or or t yp y p e de de f i af a f v ar ar ;
/ / D e ca ca lr l r i ng n g n ew e w v ar a r i ab ab le l e t o b e t yp y p e i n t_ t_ a nd n d _ fl f l o at at
41
Therefore, going back to our initial code, t y p e d e f s t r u c t NODE { struct N OD O D E * p tr tr ; i nt d a t a ; } n od od e ;
We have a composite data type called struct struct NODE NODE which contains a pointer to other struc struct t NODE variables and data. struct struct NODE NODE is also renamed to be node for ease of use. How do you access the data and pointer of a composite data type? You use the dot operator! < c o m po p o s i te te d a ta ta t y pe pe v a ri ri a bl bl e > . < v al a l u e t o a c ce ce ss ss >
An example of using the dot operator is shown below. typedef struct int_and_float { i nt i n t e g e r ; float f l o a t i n g _ p o i n t ; } i af af ; i af a f v ar ar ;
/ / v ar ar n ow ow i s a c om o m po p o si s i te t e d at at a t yp yp e
v ar a r . i n te te ge ge r = 3 ; v a r . f l oa o a t i ng n g _ p oi o i n t = 3 . 1 41 41 5 ;
/ / A c ce ce s si si n g t he h e v al a l ue u e s s to t o re r e d i n v ar ar
We can only use the dot operator when you are accessing the data using the variable. When accessing the data using a pointer, you use the arrow operator i a f * t = & va va r ;
In the code above, note that t -> data data is the same as var.data. The dierence is because you are using a pointer to access the data, whereas simply using the variable. This is very useful as shown below. The rst node in a linked list is called a head. The address address of the head head should should be caref carefull ully y used used or you risk losing the list. The last value in the list should always have it’s pointer set to null. 1
#include
2
t ty y p e d e f s t r u c t NODE { 5 struct N OD O D E * p tr tr ; 6 i nt d a t a ; 7 } n od od e ; 3 4
8 9 10 11 12 13
i nt m a i n ( void ) { n o de de h e ad ad ; n o de de no no d e_ e_ a ; n o de de no no d e_ e_ b ;
14 15 16 17
h e ad ad . p t r = & n od o d e _a _a ; n o de d e _ a . p tr tr = & n o d e_ e_ b ; n o de d e _ b . p tr tr = NU NU L L ;
18 19 20
h ea e a d . da d a ta ta = 1 1; ; n od o d e_ e _ a . d at at a = 2 2; ;
42
21
n od o d e_ e _ b . d at at a = 3; 3;
22 23 24 25 26
f or ( no n o d e * t = & he h e ad ad ; t ! = N UL UL L; L ; t - > p tr tr ) { p r i n t f (" ( " % d " , t - > d a ta ta ); ); }
/ / T r an an s ve ve r se se t he h e l is i s t u si s i ng n g a p oi o i n te te r
27 28 29
return (0); }
This This code should should output output:: “1 2 3 ”. ”. Using Using linked linked lists lists can be very trick tricky y. This This is a topic topic where where a lack lack of practice leads to a lack of understanding. I encourage you to make a linked list on your own. Maybe even try doubly linked lists (you keep track of the previous element and the next element using their addresses). Additionally, please play around and see if you can create functions to add links, delete links, and nd specic values in the linked list.
Exam Tip: Study the example above And we are nally done the main portion of this guide. I wrote this in 3 days so please excuse any mistakes.
43
14 Labs 14.1 Lab 1 1
#include
2 3 4 5
6 7 8
i nt main() { / / Y ou ou s ho h o ul u l d u se se t he h e f un u n ct c t i on on p ri r i nt n t f ( "" " " ) . A ny n y t hi hi ng n g i ns n s id i d e t he h e q uo u o t at a t io i o n s w il il l b e printed. p r i n t f (" ( " T h i s \ n I s \ n M y \ S e c o n d \ n C \ n P r o g r a m \ n ") ") / / t h e " \ n " m a k es es t he h e p ri r i nt n t f f un u n c ti ti o n p r i nt nt a n ew e w li l i ne n e o n t h e s c r ee ee n . p r i n t f (" (" X O X \ n O O X \ n O X O " );
9
return 0; 11 } 10
44
14.2 Lab 2 For this lab, you have have to understand understand syntax syntax and arithmetic arithmetic.. Additiona Additionally lly,, you should also try to compute compute each the value of c. 1
#include
2 3 4 5 6
i nt m ai a i n ( void ) { i nt a = 3 , b = 4 , e ; double f = 4 , c , d ;
7 8 9 10 11 12
d = a + b; c = a/ a / f - b; b; p ri r i nt n t f ( " Th T h e v al al ue u e o f d i s % l f \n \ n ", ", d ) ; return (0); }
45
14.3 Lab 3 1 2
#include #include
3 4 5 6 7
i nt m a i n ( void ) { i nt num1 ,num2, num3, num4, sumTotal ,sumDifference ,sumSq uares; double s u m S q r t ;
8 9 10
p r i n t f (" ( " P l ea ea se s e i np n p ut u t v al a l ue u e s f or or n um um 1 - 4: 4: \ n ") ") ; scanf(" % d % d % d % d " , & n nu u m1 m1 , & n um um 2 , & n um um 3 , & n um um 4 ) ;
11 12 13
s u m To To t a l = n u m1 m1 + n u m 2 + n um um 3 + n u m4 m4 ; s u m Di D i f f er e r e n ce c e = ( n u m 1 + n u m2 m2 ) - ( n u m3 m3 + n u m 4 ) ;
14 15 16 17
/ / I n st st ea e a d o f u si s i ng n g t he h e m at a t h f un u n c ti ti o n t o s qu q u ar a r e v ar a r ia i a bl b l es es , / / i t w o u ld l d b e e a s ie ie r t o m ul u l t ip ip ly l y t he h e m b y t he h e m se s e lv lv e s . s um u m S qu qu a re r e s = n um u m 1 * nu n u m1 m 1 + n um u m 2 * nu n u m2 m 2 + n um u m 3 * nu n u m3 m 3 + n um u m 4 * nu n u m4 m4 ;
18 19 20 21 22
/ / s u m Sq S q rt r t s ho h o ul u l d b e a d ou o u bl b l e v al al ue ue , t h er er e fo fo r e y ou ou s ho h o ul u l d c as a s t a ny ny i nt n t s i nt n t o d ou o u b le le s . / / T h i s i s n ot ot n ee e e de d e d b e ca ca us u s e i nt n t eg e g e r a n d f lo l o at a t s a lw l w ay a y s c on o n v er er t t o f l lo o at at s / / B u t y o u s h o ul ul d t r y a nd nd s ta t a y c o ns ns i st st e nt nt s u m Sq Sq r t = s qr q r t ( s u m S qu qu a r es e s ) / (double ( double ) ( s u m T o t a l ) ;
23 24 25 26
27 28
/ / P r i nt n t i ng ng p r i n t f (" ( " T he he p r i n t f (" ( " T he he ; p r i n t f (" ( " Th Th e p r i n t f (" ( " T he he sumSqrt);
v al a l ue u e s u si s i ng n g p l ac ac e ho h o l de de r s s uc uc h a s % d a n d % l f s um um t ot o t al a l i s : % d \ n ", ", s u m To To t a l ) ; d i ff ff e re re n ce c e b e tw tw ee e e n t he he f ir i r st s t t wo w o a nd nd l a as s t t wo w o i n te te g er er s % d \n \ n ", ", s u m D if if f e re re n c e ) s um um o f t he he s qu q u ar a r es e s i s: s : % d\ d \ n ", ", s u m Sq Sq u a re re s ) ; s qu q u ar ar e r o oo o t o f t he he s u um m o f s qu q u a re re s d iv i v id i d ed e d b y t h e s um um t ot o t oa o a l i s : % . 2 lf l f \ n ", ",
29 30 31
return 0; }
46
For the code below, you will notice the use of loops and arrays. This is a faster and more simpler method, but not expected expected for you to do. Instead Instead of using a loop, you would have have to input each each value. value. In the section covering loops, we noted that whenever you have to repeat an action numerous times it’s simpler to use a loop. 1
#include
2 3 4 5 6 7 8
i nt main() { / / C r ea e a t i ng ng r e q u i re r e d v a r i a bl bl e s . double c o n v e rt rt e d Y a r ds ds , c o n v e r te te d M i l e s , t o C o n v e r t ; / / U si s i ng ng a n a r ra ra t t o s to t o re re v al a l ue u e s o f t he he d at at a i nt v a l u es e s [ 4 ] = { 1 00 00 , 2 0 0 , 4 00 0 0 , 8 0 0} 0} ;
9 10 11 12
p r i n t f (" ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n ") ") ; p r i n t f (" ("| Meters | Yards | Miles |\ n ") ; p r i n t f (" ( " - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ n ") ") ;
13 14 15 16 17 18 19 20 21 22
/ / L o op o p t o p r in i n t e ac a c h v a l ue ue c o nv nv e rt rt ed e d t o y a rd r d s a n d m il i l es es f or ( in t i = 0 ; i < 4 ; i ++ ++ ) { / / C on o n ve v e rt r t a n d s av a v e t he he v a l ue ue s t o t em em p v a ri r i ab a b l es es c o n ve v e r t ed e d Y a r ds ds = ( double ) v a l ue u e s [ i ] * 1 . 09 09 4 ; c o n ve v e r t ed e d M i l es es = ( double ) v a l ue u e s [ i ] * 0 . 0 00 00 6 2 15 15 ; / / P r in i n t t e mp mp v a r ia i a b l es es p r i n t f (" ( " | % 6 d | % 9 lf l f | % 9 lf l f | \ n" n " , v a l u e s [ i ] , c o n v e r te te d Y a r ds ds , c o n v e r t e d M i l es es ) ; }
23 24 25
/ / a sk sk f o r i n pu p u t f r om om t he he u s e r p r i n t f (" ( " P l ea ea se s e e nt n t er e r a v al a l ue u e i n m et e t er e r s t o c o nv nv er er t : " ) ;
26 27 28 29
/ / R e me m e m be be r & v a r m e an a n s t h e a d d re r e ss s s o f v ar ar / / f o r s c a nf n f s t at at e me me n ts t s y ou ou h av a v e t o s to t o re r e i np n p ut u t a t t h e a dd d d r es es s s c a n f ( " % l f " , & t o C o nv nv e r t ) ;
30 31 32 33
/ / C o nv n v er e r t i np n p ut u t i nt n t o y a r ds ds a nd nd m il i l es es c o nv nv e rt r t e dY d Y a rd rd s = t o Co Co n ve ve r t * 1 1. . 09 0 9 4; 4; c o nv nv e rt r t e dM d M i le le s = t o Co C o n ve ve r t * 0. 0 . 0 00 0 0 62 6 2 1 5; 5;
34 35 36
/ / f i n al a l ly l y p ri r i nt n t t he h e c on o n v er er t ed ed y ar a r ds d s a nd n d m il i l es es p r i n t f (" ( " Y a r ds ds : % 9 lf l f \ n M i le l e s : % 9 l f ", ", c o n v e r te te d Y a r d s , c o n v e r t e d M i l e s ) ;
37 38 39
return 0; }
47
14.4 Lab 4 1
#include
2 3 4 5 6 7
i nt main() { i nt a 1 , a2 a2 , t 1 , t 2 , s u m ; double avg; char g r a d e ;
8 9 10
p r i n t f (" ( " I np n p ut u t 2 a s si si g nm n m en e n t m ar a r ks ks : ") ;
11 12 13 14 15 16 17 18
/ / T h is i s i s y e t a no n o t he he r m et e t ho h o d o f i n p ut ut v al a l i da da t io io n while ( s c a n f (" ( " % d % d " , & a1 a1 , &a & a 2 ) = = E O F | | a 1 > 1 0 0 | | a 2 > 1 0 0) 0) { p r i n t f (" ( " \ n P l ea ea s e e n te te r v a li l i d i n te t e g e r v a lu l u e s \ n ") ") ; p r i n t f (" ( " I np n p ut u t 2 a s si s i gn g n m en e n t m ar a r ks ks : ") ; } p r i n t f (" ( " I np np ut u t 2 t es es t m ar a r ks ks : " ) ;
19 20 21 22 23 24 25
/ / A n o th th er e r u se se o f i n pu p u t v a li li d at at i on on while ( s c a n f (" ( " % d % d " , & t1 t1 , &t & t 2 ) = = E O F | | t 1 > 1 0 0 | | t 2 > 1 0 0) 0) { p r i n t f (" ( " P l e as a s e e n te te r v a li l i d i n te t e g e r v a lu l u e s \ n ") ") ; p r i n t f (" ( " I np np ut u t 2 t es es t m ar a r ks ks : " ) ; }
26 27
s u m = ( a1 a1 + a 2 + t 1 + t 2 ); );
28 29
a v g = ( double ) s um u m / 4; 4;
30 31
p r i n t f (" ( " T he he a ve v e ra r a g e o f t he he m ar a r ks k s i np n p ut u t : % .2 . 2 l f ", ", a vg vg ) ;
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/ / Tr T r y a n d u s e " e l se se i f " o r s w i tc tc h s t at at e me m e nt nt s if ( a v g > = 8 0 ) g ra r a de de = ' A ' ; else if ( a vg vg > = 7 0) 0) g ra r a de de = ' B ' ; else if ( a vg vg > = 6 0) 0) g ra r a de d e = 'C ' ; else if ( a vg vg > = 5 0) 0) g ra r a de d e = 'D ' ; else g ra r a de d e = 'F ' ;
47 48
p r i n t f (" ( " \ n Ba B a se s e d o f t he h e m ar a r k a ve v e ra r a g e a bo bo ve ve , y ou ou c u rr rr en e n t ly ly h av a v e a m ar a r k : % c ", " , g r ad ad e ) ;
49 50 51
return 0; }
48
14.5 Lab 5 1
#include
2 3 4 5 6 7 8
i nt main() { / / S et e t u p v a r ia ia b le le s a n d f i l e p o in i n te te r i nt n u m _ s am am p l e s , b e a c h_ h_ n u m , n u m _ o r gs gs _ p e r _ 1 00 00 , t o t a l ; F IL IL E * d at a t a = f op o p en e n (" ( " d a t a . t x t ", ", "r"); double s a m pl p l e _a _ a vg vg = 0 ;
9
/ / M ak a k e s u re r e t he he f il i l e e x is i s ts ts if ( d a t a ) {
10 11 12 13 14
p r i n t f (" ( " Be B e a c h | Sa S a m p l e Nu Num |
S a m p le le s
| Sa S a m p l e s Av A v e r ag ag e | Sa S a f e or o r No N o t Sa S a f e \n \ n ") ") ;
15 16 17
18 19 20
/ / S ta t a te t e me m e nt n t u se se d to t o r e ad a d t o t he h e e n d of o f f i le le while ( ! f e o f ( d a t a ) ) { / / Re Re ad ad t he he d at a t a fr f r om o m t he he f il i l e an a n d st s t or or e in i n v ar ar s f s c a n f ( d a t a ," , " %d % d % d" d " , & b e a c h _ nu nu m , & n u m _ s a m p l e s ) ;
21
22
p r i n t f (" (" %3 d
| %7 d
| " , b e a c h_ h_ n u m , n u m _ s a m p l es es ) ;
23
t ot o t al al = 0 ;
24 25
fo r ( in t i = 0 ; i < n um u m _s _ s am a m pl p l es e s ; i ++ ++ ) {
26 27 28
/ / R ea ea d d at a t a f ro ro m t he he fi f i le le an an d s to t o re re in in va va rs rs f s c a n f ( d a t a , " % d " , & n u m _ o rg r g s _ pe p e r _ 1 00 00 ) ; t o ta t a l + = n u m _o _ o r g s_ s _ p e r _1 _1 0 0 ; p r i n t f (" ( " % d " , n u m _o _ o r g s _p _p e r _ 10 10 0 ) ;
29
30 31
32 33 34 35
36
/ / F in i n d o ut ut wh wh en e n t o p ri r i nt n t a c om o m ma m a ( m or o r e a st s t h et et ic ic ) if ( i +1 + 1 < n u m_ m _ s am am p le le s ) p r i n t f (" (" , "); } / / F i nd nd a v er er a g e s a m pl pl e _ av a v g = t o ta ta l / n u m _ sa s a m p le le s ;
37 38 39 40
41
p r i n t f (" ( " | % .1 .1 l f ", " , s a m pl pl e _ av av g ) ;
42
if ( s a m pl p l e _ av a v g < 3 5 00 00 ) p r i n t f (" ( " | S af a f e \ n" n" ) ; else p r i n t f (" ( " | N ot o t S af a f e \ n" n" ) ;
/ / F in i n d t he he n um um be b e r wh wh ic i c h te te r mi m i na n a t es es t he he lo l o op op if ( b e a c h_ h_ n u m = = - 17 17 ) break ;
43
44
45 46 47 48 49 50 51 52 53 54 55
} / / F re r e e t he he fi f i le l e po p o i nt nt er er fclose(data); } / / I f th t h e fi f i le le w as a s u na n a bl b l e to t o o pe pe n
49
56
57 58
else p r i n t f (" ( " U n ab ab le l e t o o pe p e n f il i l e ") ") ;
}
Note: The code feof() returns true if the le pointer is at the end of the le. Therefore, the code below will simply run until it reaches the end of the le. while ( ! f e o f ( f i l e _ n a m e ) ) { //code }
50
14.6 Lab 6 1
#include
2
// // F o rw rw ar a r d D e cl cl a ra r a t io io n 4 i nt m a x _ o f _ 3 ( in t , in t , 5 i nt m i n _ o f _ 3 ( in t , in t , 6 i nt m i d _ o f _ 3 ( in t , in t , 3
o f 3 f un u n c ti ti o ns ns e x pe pe c ti ti n g 3 i nt n t eg e g e r a r gu gu m en en t s i nt ) ; i nt ) ; i nt ) ;
7 8 9 10
i nt main() {
11 12 13 14
/ / O u r v a r ia i a b le le s a re r e d e cl cl a re re d h er er e i nt a , b , c ; i nt m ax ax , m in in , m id id ;
15 16 17 18
/ / A sk sk t h e u s er er f o r i n pu pu t p r i n t f (" ( " P l ea ea se s e e nt n t er e r a v al a l ue u e f or or a , b ,c ,c : " ) ; s c a n f ( " %d %d % d % d " , & a , & b , & c ) ;
19 20 21 22 23
/ / F u n ct c t i on on s a re re u se s e d t o d e rt rt e rm rm i ne ne t he h e m ax ax , m in in , a nd nd m id i d v al a l ue ue s m a x = m a x_ x _ o f _3 _3 ( a , b , c ) ; m i n = m i n_ n _ o f _3 _3 ( a , b , c ) ; m i d = m i d_ d _ o f _3 _3 ( a , b , c ) ;
24 25
p r i n t f (" ( " Th T h e v al al ue u e f ro ro m l ea e a st st t o g re r e at a t es e s t a re re : % d % d % d" d " , m in in , m i d , m a x ) ;
26 27 28
return 0; }
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
i nt m a x _ o f _ 3 ( in t a , i nt b , in t { / / C he h e ck ck i f a i s b ig i g ge g e r t h an an if ( a > b & & a > c ) { return a ; / / R et e t ur ur n a a s } / / C he h e ck ck i f b i s b ig i g ge g e r t h an an e l se se i f ( b > a & & b > c ) { return b ; } / / T he h e re r e fo f o re r e , i f a a nd n d b a re re else { return c ; } }
c) t he he r es es t
i t i s b i gg g g er e r t ha ha n t he h e r es es t t he he r es es t
n ot ot t he he b ig i g g es es t . T he he b ig i g ge g e s t w il i l l t he h e r ef ef o re re b e c
49 50 51 52 53 54 55
i nt m i n _ o f _ 3 ( in t a , i nt b , in t c ) { if ( a < b & & a < c ) // Fi in n d t he h e s m al al le l e s t u si s i ng n g c o mp m p ar a r i to to r s return a ; e l se se i f ( b < a & & b < c ) return b ;
51
56 57 58
else return c ; }
59 60 61 62 63 64 65
i nt m i d _ o f _ 3 ( in t a , i nt b , in t c ) { i nt m ax ax , m in in ; / / C he h e ck c k w ha h a t n um u m be b e r h as as n ot ot b ee e e n u se se d f ro ro m t he he m a x = m a x_ x _ o f _3 _3 ( a , b , c ) ; m i n = m i n_ n _ o f _3 _3 ( a , b , c ) ;
66 67 68
69 70 71 72 73
}
if ( a ! = m a x & & a ! = m i n ) return a ; e l se se i f ( b ! = m a ax x && b != min ) return b ; else return c ;
Note: The second part of Lab 6 is an exercise left to the reader.
52
3
14.7 Lab 8 This was a more dynamic approach to the problem. The way you would be expected to setup your array and pass it through functions is covered in section 3.5.4 and 10.3 . Other than the set up of the array, everyt everything hing is the same. If you have have time, try and understand understand the setup of the dynamic two two dimensional dimensional array below. #include 2 #include 1
3 4
void p r i n t _ m a t r i x ( in t * * a , in t m a t r i x _ s i z e ) ;
5 6 7
i nt main() {
8 9 10 11
F I LE LE * da da t a _f _f i l e ; / / F i le le p o i nt nt e r char * d at at a[ a [ ] = { " d a t 1 . d a t " }; / / A bi b i l it it y t o u se se m ul u l t ip ip l e f il i l es es i nt n u m _ of of _ d a t a _ f i l e s = sizeof ( d a t a ) / sizeof ( d a t a [ 0 ] ) ; // / / F in i n d h ow ow m an a n y f il i l es e s a re re t h he e re re
12
/ / Fo F o r e ve v e ry r y f i le le f or ( in t i = 0 ; i < n um u m _o _ o f_ f _ da d a ta t a _f _ f il i l es e s ; i + +) +) { d a t a_ a_ f i le le = f o pe pe n ( d a ta ta [ i ] , " r " ) ;
13 14 15 16
/ / O pe p e n e ac a c h d at a t a f il il e
17
in t m a tr t r i x _s _s i z e = 0 ; fscanf( data_file , " % d " , & m a t r ix i x _ s iz iz e ) ;
18 19
/ / G et et s t he he s iz iz e o f t he he m at a t ri ri x
20
in t * * a = m al a l lo l o c ( m at a t r ix i x _ si si z e *sizeof * sizeof ( i nt ) ) ; fo r ( in t j = 0 ; j < m at a t ri r i x_ x _ si s i ze z e ; j ++ ++ ) { a [ j ] = m a ll l l o c ( m a t ri ri x _ si s i z e *sizeof * sizeof ( in t ) ) ; }
21 22 23 24 25
/ / D yn y n a mi mi c a rr r r ay a y b as a s ed e d o n t he h e s iz iz e
26
fo r ( in t x = 0 ; x < m at a t ri r i x_ x _ si s i ze z e ; x ++ ++ ) { fo r ( in t y = 0 ; y < m at a t ri r i x_ x _ si s i ze z e ; y + +) +) { fscanf( data_file , " % d " , & a [ x ][ ][ y ] ) ; } }
27 28 29 30 31 32 33
/ / S to t o re r e f il i l e d at a t a i ns n s id i d e m at a t ri ri x
34 35 36
print_matrix(a,matrix_size); / / P ri r i nt n t t he he s to t o re r e d m at a t ri ri x p r i n t f (" ( " N o w p r i nt nt i n g d i ag a g o n al al a nd n d c r os os s d i ag a g o n al al \ n ") ") ;
37 38 39 40 41 42 43
fo r ( in t t = 0 ; t < m at a t ri r i x_ x _ si s i ze z e ; t ++ ++ ) { p r i n t f (" ( " % d \ t " , a [ t ][ ][ t ] ) ; } p r i n t f (" ( " \ n ") ");
/ / P ri r i nt n t t he he d ia i a g on on al al
44 45 46 47 48 49
fo r ( in t k = 0 ; k < m at a t ri r i x_ x _ si s i ze z e ; k ++ ++ ) / / P r in in t t he h e c ro ro ss s s - d i g a no no n a l { p r i n t f (" ( " % d \ t " , a [ k ] [ ( m a t r i x _ si si z e - 1 ) - k ] ) ; } / / D e a ll l l o ca ca t in i n g a n d f r e ei e i ng n g i s n ot o t r e qu qu ir i r e d f o r a r eg e g ul u l a r t w o d i m en e n s io io n al al a rr r r ay ay
50
53
fo r ( in t d = 0 ; d < m at a t ri r i x_ x _ si s i ze z e ; d ++ ++ ) { a [d [ d ] = N UL UL L ; } free(a);
51 52 53 54
55
/ / E m pt pt y d y ma m a n ic i c a r ra ra y
/ / D e a ll l l o c at a t e m e mo mo r y
56
57
59
fclose(data_file); }
58
}
60
// // F u nc nc t io io n t ha h a t p ri r i nt n t s t he he m at a t ri ri x 62 void p r i n t _ m a t r i x ( in t * * a , in t m a t r i x _ s i z e ) 63 { 64 f or ( in t x = 0 ; x < m at a t ri r i x_ x _ si s i ze z e ; x ++ ++ ) 65 { 66 fo r ( in t y = 0 ; y < m at a t ri r i x_ x _ si s i ze z e ; y ++ ++ ) 67 { 68 p r i n t f (" ( " % d \ t " , a [ x ][ ][ y ] ) ; 69 } 70 p r i n t f (" ( " \ n ") "); 71 } 72 } 61
54
15 Assig ssignm nmen entt 1 1 2
#include #include
3 4 5 6 7
i nt main() { / / C ou o u nt n t e rs rs t o d ev e v e lo lo p t he he f i bo bo na n a c ci ci s e qu qu en en c e i nt a = 0 , a _ 1 = 1 , a _ 2 = 0 ;
8
i nt a m o un u n t Sq Sq r t = 0 ;
9 10
/ / K e ep e p a c ou o u nt n t e r t o h ow o w m an a n y n um u m be b e r s w e re r e c al a l c ul u l at at e d i nt a m o un u n t Nu Nu m s = 1 ;
11 12 13
/ / 31 31 s t e le l e me me n t i nt n um u m 31 31 = 0 ;
14 15 16 17
double g o l de d e n R at at i o = 0 ;
18 19 20
while ( a < = s e q u e n ce ce M a x ) {
21 22
p r i n t f (" ("%d
", a);
23 24 25 26 27 28 29 30
if ( a_ a_ 1 ! = 0 ) { g o ld ld e nR nR a ti t i o = ( float ) a / a _ 1 ; p r i n t f (" ( " % . 3 l f \ n " , g o l de de n R at at i o ) ; } else p r i n t f (" ( " S k i p \ n ") ");
31
/ / Th T h e s e co co nd n d l a st s t e l e me m e nt n t i s e q ua u a l t o t he he l a st s t e l e me me n t a _2 _2 = a _1 _1 ; / / T he he l a st s t e l e me m e nt n t i s e q ua u a l t o t he he c u r re r e nt n t e le l e me m e nt nt a_1 = a ; / / T he he n e w c u rr r r e nt nt e l em em en e n t i s a s u m o f t he he t w o p r e vi vi ou o u s e l e me m e n ts ts a = a_1 + a_2 ;
32 33 34 35 36 37 38
/ / c he h e ck c k i f t h e i n te t e ge g e r h a s a p e rf r f e ct ct i n te te ge g e r s q u ar a r er e r o ot ot if ( s q r t ( ( float ) a ) = = f l oo o o r ( s q rt rt ( ( float ) a ) ) ) { amountSqrt++; p r i n t f (" ( " \ t p e rf r f e c t s q ua u a r e ") ") }
39 40 41 42 43 44 45 46 47 48 49 50 51
amountNums++; / / S av av e t he h e 3 1 e le l e me m e nt n t i n t he h e s eq e q ue u e nc n c e a n d w i ll ll p ri ri nt n t i t o ut ut l at a t er er if ( a m o un un t N um um s = = 3 1 ) { num31 = a ; }
52 53 54
} p r i n t f (" ( " \ n\ n \ n Th T h e a mo m o un u n t o f n um u m be b e rs r s d i sp sp l ay ay e d i s % d ", ", a m o u nt nt N u m s - 1 ) ;
55
55 56
p r i n t f (" ( " \ n\ n \ n Th T h e n um u m be b e r o f p er e r f ec ec t ly ly s qr q r t r oo o o t i nt n t e ge ge rs r s a re r e : % d ", ", a m o un un t S qr qr t ) ;
57 58 59 60 61
if ( n u m 3 1 ) p ri r i nt n t f ( " \ n Th Th e 3 1 st st n um u m be b e r i n t he he s e qu qu en e n c e i s % d ", " , n u m3 m3 1 ) ; else p r i n t f (" ( " \ n Th T h er e r e w as as n o ot t 31 el le e m en en ts t s i n t he he f i ib b o na na c ci ci s e qu qu en e n c e u p t o % d ", " , s e q ue u e n c eM eM a x ) ;
62 63 64
return 0; }
56
16 Assig ssignm nmen entt 2 The code below is left as snippets for the reader. Using this guide, go through each function and understand how they work. You should redo assignment 2 a few times before going to the exam. 1
#include
2 3
double a v e r a g e ( double a [ ] [ 2 0 0 ] , in t r o w , i nt col) { 6 double a vg vg = 0 ; 4 5
7 8 9 10 11 12 13 14 15 16 17
f or ( in t i = 0 ; i < r o w ; i ++ ++ ) { fo r ( in t k = 0 ; k < c o l ; k + +) +) { avg = avg + a [i [ i ][ ][ k] k]; } } a v g = a vg vg / ( r o w * co co l ) ; return avg; }
18
double c o r n e r ( double a [ ] [ 2 0 0 ] , in t r o w , i nt col) { 21 double c o r n e r _s _s u m = a [ 0 ] [0 [0 ] + a [ 0 ][ ] [ c ol o l - 1 ] + a [ r ow ow - 1 ][ ] [ 0 ] + a [ ro r o w - 1 ][ ][ c ol o l - 1 ]; ]; 22 return c o r n e r _ s u m ; 23 } 19 20
24
double r o w _ a v g ( double a [ ] [ 2 0 0 ] , in t r o w , i nt c o l , in t r_c) { 27 double r o w_ w _ av av g = 0 ; 28 f or ( in t i = 0 ; i< i < c o l; l ; i ++ ++ ) 29 { 30 row_avg += a[r_c -1][i]; 25 26
31
} r o w_ w_ av a v g / = co co l ;
32 33 34
}
35
double c a l c _ b o r d e r ( double a [ ] [ 2 0 0 ] , in t r o w , in t col) 37 { 38 double a vg vg = 0 ; 36
39
f or ( in t k = 0 ; k < c ol ol ; k + +) +) { avg = avg + a [0 [0 ][ ][ k ] + a[ a [ ro ro w - 1] 1] [k [ k ]; ]; } f or ( in t r = 0 ; r < r ow ow ; r + +) +) { avg = avg + a[ a [ r ][ ][ 0] 0] + a[ a [ r] r ] [ co c o l - 1] 1] ; } a vg v g - = c or o r ne n e r (a ( a , r ow ow , c ol ol ) ;
40 41 42 43 44 45 46 47 48 49 50
}
51 52
double d i a g ( double a [ ] [ 2 0 0 ] , in t row)
57
53 54
{ double a vg vg = 0 ;
55 56 57 58 59 60 61 62
f or ( in t i = 0 ; i < r o w ; i ++ ++ ) { avg + = a [i [ i ][ ] [ i ]; ]; } a vg vg / = ro ro w; w; return avg; }
63 64 65 66 67 68 69
i nt m a i n ( void ) { F IL IL E * d at a t a = f op o p en e n (" ( " d a t a . d a t ", ", "r"); i nt r ow ow , c ol ol ; i nt r _c _c , c _c _c ;
70 71
f s c a n f ( d a t a , " % d % d " , & ro r o w , & c ol ol ) ;
72 73
double a [ r o w ] [ c o l ] ;
74
f or ( in t i = 0 ; i < r o w ; i + + ) { fo r ( in t j = 0 ; j < c o l ; j + + ) { f s c a n f ( d a t a ," ," % l f " , & a [ i ] [ j ] ) ; } }
75 76 77 78 79 80 81 82
f or ( in t k = 0 ; k < r o w ; k + + ) { fo r ( in t c = 0 ; c < c o l ; c + +) +) { p r i n t f (" ( " % l f \ t " , a [ k ] [ c ]) ]) ; } p r i n t f (" ( " \ n ") "); }
83 84 85 86 87 88 89 90 91 92
f s c a n f ( d a t a ," , " % d % d " , & r_ r _ c , & c _c _c ) ;
93 94 95
p r i n t f (" ( " A V E RA R A G E : % l f ", " , a v er er ag a g e ( a, a , r ow ow , c ol ol ) ) ; p r i n t f (" ( " R OW OW : % l f" f " , r ow o w _ av av g ( a, a , r ow ow , c ol ol , r _c _c ) ) ;
96 97
fclose(data);
98 99
}
58
17 Endi Ending ng Comm Commen ents ts If you understand the material discussed in this overview, have ample practice by programming daily, and can easily solve solve the lab problem, problem, then there is no reason reason to ever ever show up to class. class. I will tell you straight to your face: if you do not practice, then you will fail.
59