COP 3223H: Honors Introduction to Programming with C (Spring 2014) Instructor: Muhammad Faisal Amjad HEC-250 Data Systems Lab, faisal@knights.ucf.edu Course Time: MoWeFr 8:30AM - 9:20AM, BHC 0126. Office Hours: MoWe 11:00 am – 12:30 pm Course Webpage: http://eecs.ucf.edu/~faisal/COP3223H-SP14/cop3223h.htm Prerequisites: None (Knowledge of basic math is assumed). Course Information • This is an introductory course in C programming language for students with no prior programming experience. • You will learn the syntax of C and its major constructs* such as : – – – – – – – – Data types and variables, conditional statements, loops, functions, arrays, structures, strings, pointers, file input / output. • *Not necessarily in this order • Just like learning any language, learning to program using the C language requires a lot of practice. • Students are encouraged to try writing programs in addition to those discussed in class. Grading • Following is an approximate breakdown of semester’s workload and weightage: Coursework Quantity Weightage Individual Programming Assignments Quizzes 10 25% 5 30% Final Exam 1 30% Midterm Exam 1 15% Textbook • A wealth of tutorials, examples and programming projects is available online. Everyone should be able to succeed in this course without buying any book. • An excellent online source for learning C programming is http://en.wikibooks.org/wiki/C_Programming, but students may choose any other source of their liking. Academic Misconduct • Please see http://goldenrule.sdes.ucf.edu/ and the golden rule handbook. Introduction Computer Basics • CPU: Commonly known as the processor, “runs” everything on the computer. • Memory: All programs and their data are contained in memory – Main, commonly known as RAM – External, USB, CDs, Hard drives etc. – We will not be dealing with other types of memory e.g. registers, cache, virtual/page etc. • OS: Interface between the user and the computer’s resources – Mac, Windows, Unix etc. • Compiler: Converts programs written in high level languages into machine instructions / executable programs C Program Development Cycle Edit Program Source Code Compile Object Code Library Files Link Object Code Executable Code DevC++ IDE • To accomplish all parts of C program development cycle, we will use the DevC++ IDE (Integrated Development Environment). • http://www.bloodshed.net/dev/devcpp.html • This is a free software under the GNU General Public License. • link to Sourceforge download site. • Use default install options. • It runs on Windows computers only. • A tutorial on DevC++ installation can be found at: http://www.brooklyn.cuny.edu/web/aca_naturalsciences_cis/STARTDev.pdf • Save programs using the “.c” extension and NOT “.cpp” • All submitted programming assignments should run on my installation of Dev C++ which is Dev-C++ 5.0 beta 9.2 (4.9.9.2). A brief history of C • Created by Dennis Ritchie at Bell Labs in 1972 • Originally created to design and support the Unix operating system. • C compilers are available for virtually every platform • In 1983 the American National Standards Institute (ANSI) standardized C to be called ANSI Standard C. • ANSI C programs that you write should work with any ANSI C compiler. Our First C program /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */ #include <stdio.h> int main() { printf("Hello World! \nThis is the first program of COP 3223H\n"); system("pause"); return 0; } Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */ #include <stdio.h> int main() { printf("Hello World! \nThis is the first program of COP 3223H\n"); system("pause"); return 0; } • • • • This is a comment The compiler ignores everything between /* and */ It helps reader to understand what is written in the “code”. An essential part of programming. Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */ #include <stdio.h> int main() { printf("Hello World! \nThis is the first program of COP 3223H\n"); system("pause"); return 0; } • This is called a pre-processor directive • Pre-processor directives start with a ‘#’ sign • Tells the compiler to “include” a library file called stdio.h for our HelloWorld.c program • After it is included, we can use all the features / functionalities provided by stdio.h in our program • Notice that there is no space between # and include Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */ #include <stdio.h> int main() { printf("Hello World! \nThis is the first program of COP 3223H\n"); system("pause"); return 0; } • This is the start of definition of function main, also called the header of function main • All C programs MUST have a function named “main” • Execution of a program starts from the function main • Functions return some value, in our program int is the return type of function main. Write “void” of they don’t return any value. • () contains a list of parameters passed to a function separated by commas. Parameter list of our program is empty. We can also write “void” in the parameter list but an empty parameter list is automatically considered void. Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */ #include <stdio.h> int main() { printf("Hello World! \nThis is the first program of COP 3223H\n"); system("pause"); return 0; } • The pair of curly braces identifies the start and the end of function main’s definition • Mandatory for any function definition • This pair of curly braces is also used for other code blocks that we will study later Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */ #include <stdio.h> int main() { printf("Hello World! \nThis is the first program of COP 3223H\n"); system("pause"); return 0; } • This is a call to function named printf which is defined in stdio.h • printf function prints a string enclosed within a pair of double quotes • The characters \n are not printed on screen. They are called escape sequences. \n tells the computer go to new line • More on escape sequences later Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */ #include <stdio.h> int main() { printf("Hello World! \nThis is the first program of COP 3223H\n"); system("pause"); return 0; } • The function “system” is also defined in stdio.h file • Passing the string “pause” causes the computer to pause execution at this line until a key is pressed on the keyboard. Lets dissect HelloWorld.c /* Written by Faisal Amjad for COP 3223H - Spring 2014 Our First C Program, called HelloWorld.c */ #include <stdio.h> int main() { printf("Hello World! \nThis is the first program of COP 3223H\n"); system("pause"); return 0; } • This statement tells the computer to exit function main and return 0 to the program from where it was called. • Returning 0 from main signals successful execution of function main. • The returned value of a function must be the same as its return type. • If you return a value other than an int in HelloWorld.c, it will cause a compilation error. • Finally: Every program specifies instructions for execution in the exact order without ambiguity. Running HelloWorld.c Variables • Almost all programs manipulate data • To process it, a program needs to store data • Different types of variables allow the storing different types of data, hence the name “Data Types” • E.g. if you had to store the numbers 10 and 10.0, C provides two different data types. How do Variables work • All variables have three components – A name – An address – A value that it can hold • When we declare a variable like – int temp; – The compiler gets space for an integer (4 bytes) allocated for this variable – This memory space has an address, which is also accessible to your program • When we initialize this variable like – temp = 125; – The compiler stores the integer number 125 in the memory space allocated for the variable temp – Here, “=“ is an assignment operator, which assigns values to variables After declaration int temp; Variable name Variable address temp 2000 After initialization Memory address Memory contents 2000 temp = 125; Variable name Variable address temp 2000 Memory address Memory contents 2000 125 Some Naming Conventions • Names with leading and trailing underscores are generally used for system purposes. • #define constants should be in all CAPS. • Enum constants are Capitalized or in all CAPS • Function, typedef, and variable names, as well as struct, union, and enum tag names should be in lower case. • Avoid names that differ only in case, like sum and Sum. • Avoid names that look like each other. ‘1’ and ‘l’ • Avoid names that might conflict with various standard library names. E.g. stdio Variable Names • Variable names can contain letters, digits and underscores • The first character must be a letter or an underscore – the underscore can be used as first character but avoid this!! • Case matters! int temp is not the same as int Temp or int TEmp • C keywords cannot be used as variable names. – – – – – mycarname, hello, y2k, r2d3, ... _2013_tax_return Hello#Cprogrammer double 2lazytocode /* OK */ /* OK but avoid*/ /* illegal */ /* will not work */ /* illegal */ /* Muhammad Faisal Amjad program to try out different types of variable names: see what works and what doesn't COP 3223H - Spring 2014 */ #include <stdio.h> int main() { int my_car_model = 2002; int numberofstudents; int _2013_tax = -1500; int 2lazytocode = 1; int double = 35000; int hello#CProgrammer = 0; printf("Success..... Now I know how to name variables\n"); system("pause"); return 0; } Variables – basic data types • We will study the C data types in detail later. Lets focus on the basics of variables. • There are only a few basic data types in C – char: a single byte, holds one character e.g. the letter ‘a’, although they are stored as integer values standardized as ASCII numbers – int: an integer of fixed length, usually 4 bytes / 32 bits. E.g. the number 10 can be stored in a variable of type int. – float: single-precision floating point. e.g. the number 10.67 – double: same as a float but with double precision Variable declaration • Generic Form – typename varname1, varname2, ...; • Examples: – int count; – float a, b, c; • Where declarations appear affects their scope – Declaration outside of any function are for global variables – e.g., just before the main function Variable declaration and Initialization • ALWAYS initialize a variable before using it – Failure to do so in C is asking for trouble, unexpected values • Examples: – int count; /* This is declaration, sets aside storage space for count */ – count = 100; /* This is initialization, stores 100 in the variable count */ • Declaration and initialization can be combined: – int count = 0, distance = 20; • “Out of range errors” – Short int value = 32768; //short int has a max value of 32767 – The C compiler does not detect this as an error – What do you suspect will happen if a variable is assigned an out of range value? Practice with variables • Write a program to practice declaring variables • Write a program to practice initializing variables • Write a program to see the contents and addresses of variables with and without initialization • Write a program to practice swapping contents of variables Simple output and input with printf and scanf Output with printf() • As we have seen earlier, printf() function has the following syntax: – – – – printf(format string, arg1, arg2, …); E.g. printf("Hello World! \nThis is the first program of COP 3223H\n"); The text including the pair of double quotes is the format string We can print the values of variables using conversion specifiers and their corresponding arguments in the arguments’ list • The format string contains: – Literal text: is printed as is – Escaped sequences: special characters preceded by \ e.g. \n – Conversion specifiers: % followed by a single character • Indicates (usually) that a variable is to be printed at this location in the output stream. • The variables to be printed must appear in the parameters to printf following the format string, in the order that they appear in the format string. Common C escape sequences Escape sequence Meaning \a \b \n \t \\ \' \" \0 alarm or a beep Backspace New line Horizontal tab Backslash Single quotation mark Double quotation mark ASCII 0x00 (null terminator) Common C conversion specifiers Specifier Meaning %c %d %x %f %e %s %u %% %ld, %lld Single character Signed decimal integer Hexadecimal number Decimal floating point number Floating point in “scientific notation” Character string (more on this later) Unsigned decimal integer Just print a % sign long, and long long Input with scanf() • The scanf() function is the input equivalent of printf defined in the <stdio.h> library file • Takes a format string and parameters, much like printf • The format string specifiers are the same as printf • Examples: – printf(“Enter the number of days"); – scanf(“%d", &days); • • • • • /* prompt user for input */ /* reads a decimal integer */ The ampersand (&) is used to get the “address” of the variable The printf() prints the string “Enter the number of days ” And then scanf() waits for the user to input an integer Stores the input value at the address of the variable days One scanf() function call can read more than one values /* Muhammad Faisal Amjad program to try out printf and scanf functions COP 3223H - Spring 2014 */ #include <stdio.h> int main() { int days = 0; float dist_to_work = 0; float weekly_travel = 0; printf("Enter the distance in miles from your home to work place: "); scanf("%f", &dist_to_work); printf("Enter the number of days you go to work: "); scanf("%d", &days); weekly_travel = days * dist_to_work; printf("You travel %.3f miles to and from work in a week\n\n", weekly_travel); system("pause"); return 0; } Practice with variables, printf and scanf • Write a program to calculate the amount of interest paid for house mortgage. • Ask user to input – Loan amount – Interest rate (assume simple interest) • Output: Interest paid, total amount paid to bank. Programming Style and structure • • • • • • A good time to have a look at how your code “looks” Programming style refers to the layout of your code A program will be read by someone It should be easy to read with appropriate white spaces Use indentation Arrange your code in appropriate code blocks contained within a matching pair of curly braces { and } • Be careful about variable within code blocks, the scope of variables matters • Variable should be given meaningful names – E.g. consider int n; and int num_of_students; • Use comments at appropriate places – – – – Beginning of your program called header comment Beginning of a major code block Start of a function Any other place you might consider appropriate #include <stdio.h> int main(void) {printf("Hello, World!\n");return 0;} #include <stdio.h> int main(void) { printf("Hello, World!\n"); return 0; } #include <stdio.h> int main(void) { printf("Hello, World!\n"); return 0; } /* Muhammad Faisal Amjad program to print “Hello World!” on standard output COP 3223H - Spring 2014 */ #include <stdio.h> int main(void) { printf("Hello, World!\n"); return 0; }