1 / 101

Crash Course in C Programming Basics

Get started with C programming by writing simple yet effective programs. Learn to express ideas, debug code, compile, and run your own programs. Explore pseudo code, flowcharts, and basic syntax to kick-start your programming journey.

derin
Download Presentation

Crash Course in C Programming Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 1 - Crash Course in C • Our Plan: • We are going to take a quick look at C through a sequence of short (but increasingly complex) programs. This way, you will get a flavor for what is possible and quickly be able to write and run your own programs • In the chapters that follow, we will take a more exhaustive look at the main features introduced in the first chapter

  2. First Program - Definition • As an engineer, you will need to communicate your ideas, data, conclusions in writing to others, so our first program will show you how to express ideas in writing. • Code objective: • write a program to tell the world: • “ENEE 148A is my favorite class!” and • “Prof. Lawson is a … teacher”

  3. Program realization steps • Write program “ex01” (source file) • Pseudo code or flowchart • Develop/enter code • Debug code in IDE (Integrated Development Environment) • compile program - produce ex01.o (object file) • Debug code • link the program to get a.out or ex01.exe (linking combines your executable with library executables) – many IDEs combine last two steps with a BUILD command • Debug code • Run the program • Debug code

  4. First Program - Specification • Pseudo code • “natural language” (i.e. English) description of the tasks that need to be accomplished • Top-down, stepwise refinement • begin with statement of goals • revise many times by taking each step and braking it down into more detailed steps • stop when each pseudo code line is easily converted to C

  5. First Program - Specification, ctd • Flowcharting • another alternative approach to pseudo code utilizing symbols... • our program: • start • write “ENEE 148A is my favorite class” • write “Prof. Lawson is a ... teacher” • stop

  6. Writing the code • The code can be entered: • In a standard text editor: vi (in unix). Leafpad (on a Raspberry Pi), or Notepad (in Windows) • In an IDE • (Integrated Development Environment) http://en.wikipedia.org/wiki/Integrated_development_environment

  7. Advantages of an IDE • Will often have a color scheme to differentiate comments, keywords, content enclosed in parentheses, etc. • They are usually self-contained. You can write, compile, build, debug, save, print, and upload (if written for an embedded device) without leaving the IDE • Sometimes have intelligent line completion • Some IDEs are free: http://c-madeeasy.blogspot.com/2012/05/best-4-ides-for-coding-programs-in-c.html • Some are not (like Microsoft Visual Studio)

  8. First Program - Coding (1st version) /* Program #1: Demonstrates simple print command*/ /* Written by W. Lawson*/ /* First written Aug 15, 1997; last modified Sept 2, 2014 */ #include <stdio.h> /* will explain this later */ int main(void) /* all programs must have a main */ { printf("ENEE 148A is my favorite class"); /* 1st line */ printf("Prof. Lawson is a ... teacher"); /* 2nd line */ return 0; /* end */ }

  9. Program analysis - line 1 /* Program #1: Demonstrates simple print command*/ /* Written by W. Lawson*/ /* First written Aug 15, 1997; last modified Sept 2, 2014 */ These are comment lines. Comments begin with /* and end with */. ANYTHING enclosed in between is simply ignored by C. They are used to document the program and make it easy to understand. Always start a program with a comment about the purpose of the code. Also state the author and revision history (dates and key changes).

  10. Comments • Comments can span several lines: /* Program #1: Demonstrates simple print command Written by W. Lawson First written Aug 15, 1997; last modified Sept 2, 2014 */ • They can not be imbedded: /* this will not /* work */ at all */ • Forgetting the end */ and reversing the order are two common errors - beware!

  11. Single line comments (C++) • A double slash // can be used for a single line comment. Everything from the // to the end of the line (carriage return) is ignored • O.k. to use, but always could cause portability issue if you find a C (not C++) compiler

  12. Program analysis - line 2 #include <stdio.h> /* will explain this later */ • Note that comments can go anywhere • The # sign indicates that this is a message for the C compiler and not a C “statement” • It is called a “pre-processor” directive • Because C handles input and output through standard “functions”, we must provide some info about what those functions look like. That info is stored in the “header file” stdio.h - standard input - output in a pre-defined directory. In LINUX the directory is often /usr/include

  13. Include directive • The header file is inserted into the code at the point indicated before the code is compiled. • If you write your own header file and store it in your local directory, you would use “” instead of <>: • #include “myheader.h”

  14. Program analysis - line 3 (sort of) int main(void) /* all programs must have a main */ { } • ALL C programs are made up of functions. Functions can have arguments, that are variables whose values are determined before the function is “executed” presumably by some other function. • The arguments are enclosed in parenthesis after the function name and are separated by commas. • If there are no arguments, place “void” in parenthesis to emphasize this fact.

  15. Functions • All functions can generate a (single) value which can be used elsewhere in the program. If the value of the function is an integer, we place an “int” in front of the function name to indicate this. • E.g. consider the function y = f(x) = x2. x is the argument, y is assigned the value of the function f. • Each program can have only one “main” function. The program begins execution at main, regardless of where main is located in the body of the code. • Note: C is case-sensitive; “Main” is not the same as “main.” • The code for each function is always enclosed in braces {…}.

  16. Program analysis - lines 4 & 5 printf("ENEE 148A is my favorite class"); /* 1st line */ printf("Prof. Lawson is a … teacher"); /* 2nd line */ • These two lines call the function “printf”, which is defined in <stdio.h>. • printf prints the text in parenthesis on the standard output, which in this case is the monitor. • Each line is an example of a C statement, which commands the computer to perform some task. • C statements always end with a semicolon (;) • Forgetting a quote or semicolon are typical errors - beware!

  17. Warning: • NOTE: pre-processor directives are not statements, so they don’t end in semicolons! • Neither does the definition line for main (or any function)!

  18. Program analysis – “final line” return 0; /* end */ } • indicates the end of the function. • The value indicated after “return” is the value of the function. • In main, this value is customarily set to zero if the program worked as expected and to some nonzero value if there was an error. • Note: program will work without a return, but we will always include it (good programming practice!).

  19. Notes on formatting • The C compiler pretty much ignores “white space”, which are blanks, tabs, and new lines, so these can be used to help make the code more readable. • Put blank lines in between sections of code that are not closely related. • Indent blocks of code to indicate functional structure of code (each indentation should be about 3 spaces ) • GOOD FORMATTING IS IMPORTANT FOR READABILITY!

  20. Integrated Testing • What would be the output from this code?

  21. First Program - Integrated testing • There are two types of “bugs” • syntax error • caught by compiler - can not run • logic error • program runs, but gives “wrong” answer • What type of error did our first code have?

  22. A few control sequences • new line - \n • tab - \t • double quote - \” • single quote - \’ • backslash - \\

  23. Comment on tabs \t • the space resulting from a tab can not be adjusted. • there are 10 tabs across an 80 character page, so that individual tabs generate up to 8 spaces. • We will learn advanced formatting techniques later in the course.

  24. Corrected first example… • Let’s fix the first example with control characters…

  25. 2nd Program - Definition • Programs can be written to perform difficult, repetitive computations in EE • Below is an example from the Electrophysics area (you will see it in ENEE 380) : • Write a program to calculate the “magnitude” of the electric field generated by a single electron a fixed distance away.

  26. 2nd Program - Specification • the program: • start • define constants • define variables • initialize radius • calculate electric field • print radius, electric field • stop

  27. Program # 2 - coding

  28. Program #2 - part 2 int main(void) { float e_field, radius=.0025; /*new feature */ e_field=CHARGE/(4.0*PI*EPSILON_0*radius*radius); printf("Electric field at a radius %f = %f\n",radius,e_field); /* this printf has more than one argument */ return 0; }

  29. Program analysis - new feature 1 #define CHARGE -1.602e-19 /* new feature */ #define EPSILON_0 8.854e-12 #define PI 3.141592654 • Pre-processor directive “define” generates symbolic constants. Constants are replaced in code by numeric values before compilation. • No equal sign and no semicolon • Convention for constants: use all uppercase letters • Good programming practice: use symbolic constants often!

  30. Program analysis - new feature 2 float e_field, radius=.0025; /*new feature */ • this is called a variable definition • variable is declared and space is allocated • all variables must appear in one, where you define the variable’s “data type” • char single text characters • int integers • float real numbers • more variations will be discussed later

  31. new feature 2 - continued • Convention for variables: use all lowercase letters • Separate variables with commas • initialize with equal sign • end with semicolon • variable names (identifiers) • are unique to 31 characters, • contain characters, numbers, and underscores, • must begin with a character • can not be a C “reserved” word (like return, float) • should be meaningful and follow a standard convention (we will discuss this further later)

  32. Reserved words (keywords) • there are over 30 reserved words, already we have seen: • char • int • float • void • return

  33. Program analysis - new feature 3 printf("Electric field at a radius %f = %f \n", radius, e_field); • Now there are 3 arguments of this function • the first argument is the format for the print • The percent sign is a special character, the following “f” indicates that a float (real number) is inserted there. The second argument identifies the number to be inserted at that point (the first %f). The third argument is inserted at the second %f.

  34. 2nd Program test • Let’s try out this program now...

  35. 2nd Program conclusion • This program seems to work! • It’s not very useful, though, because we can’t vary the distance from the charge...

  36. 3rd Program - Definition • The next example comes from circuit theory (you will see it in ENEE 205) • Write a program to calculate the net resistance of two (variable) resistors in parallel

  37. 3rd Program - Specification • the program: • start • define variables • prompt for input • read R1, R2 • check for valid input • if valid • calculate R3 • print parallel resistance • if not print error • stop

  38. Program # 3 - coding

  39. Program #3 - part 2 if (r1!=0) { /* check to insure resistance r1 isn't zero */ if (r2!=0) { /* check to insure resistance r2 isn't zero */ r3=1.0/(1.0/r1+1.0/r2); printf("total Resistance Rtot = %f ohms\n",r3); } else printf("r2 is a short circuit...\n"); } else printf("r1 is a short circuit...\n"); /* end of if-else test */ return 0; }

  40. Program analysis - new feature 1 • #include <stdlib.h> /* includes info on exit() */ This inputs the “Standard Library” header exit() is a function that halts execution of the program (similar effect as return ONLY in main) - exit(0) signifies a normal exit

  41. Program analysis - new features if (scanf("%f %f",&r1, &r2)!=2) { printf("Data entered incorrectly...Bye!!\n"); There are two new features here on one line; let’s take them one at a time:

  42. scanf 1) scanf("%f %f",&r1, &r2) just as printf prints to the standard output, scanf reads from the standard input; the default is the keyboard. a) "%f %f" the format indicates that two floating point numbers will be read. b) the second two arguments indicate the names of the variables. The & indicates the address (location in the computer memory) is to be given. This is necessary to transfer the data for reasons to be seen later. c) scanf returns an integer which equals the number of variables successfully read

  43. scanf vs. printf Beware: forgetting the & in scanf or including & in printf (where it doesn’t belong) are typical sources of errors!

  44. conditional test • The general form of the conditional test is if (expression) statement 1; else statement 2; statement 1 will be executed if the expression is true, otherwise statement 2 will be executed. Note: semicolon after statement only! indentation to show dependence

  45. conditional test • expressions are always “resolved” to a numeric value. If the value is “0”, the expression is considered “false”. Any other value is considered “true”. Often, but not always, the value of true is “1”.

  46. Relational operators > greater than >= greater than or equal to < less than <= less than or equal to = = equal to != not equal to Note: do not confuse assignment = with test = =

  47. On embedded functions... • We could have written: inti; /* include in declaration at the start */ ... i=scanf("%f %f",&r1, &r2); if (i!=2) {... • However, one line performs both functions without the need for an extra variable: if (scanf("%f %f",&r1, &r2)!=2) {... • Look out for this style - it will occur often

  48. Nested “if” statements if (r1!=0) { if (r2!=0) { r3=1.0/(1.0/r1+1.0/r2); /* note: different from definition*/ printf("total Resistance Rtot = %f ohms\n",r3); } else /* goes with 2nd “if” use indentation! */ printf("r2 is a short circuit...\n"); } else /* goes with 1st “if” */ printf("r1 is a short circuit...\n");

  49. Logical operators • We could have written our test for invalid resistances more compactly as: if ((r1==0)||(r2==0)) { printf(“One of the resistances is zero”); ... /* we lose a little information... */ && and || or ! not

  50. More on logical operators • would this code work correctly? if ((r1=0)&&(r2==0)) { printf(“One of the resistances is zero”); ... • what should follow this line? if ((r1!=0)&&(r2!=0)) {

More Related