420 likes | 544 Views
Introduction to C Programming. Microprocessors. Electronic brain which can perform computations It’s a brain without a mind (intelligence), you have provide it its intelligence in the form of instructions Those instructions are called programs/code
E N D
Microprocessors • Electronic brain which can perform computations • It’s a brain without a mind (intelligence), you have provide it its intelligence in the form of instructions • Those instructions are called programs/code • Most basic form of coding utilizes Machine language or assembly code
High-level view of programming • The file with instructions that comprise a program is called you source code • What this file looks like depends on the choice of programming language. • As long as you follow syntax rules for chosen language, your source code file is valid. • For this project, we will start with a powerful and well known language called C.
High-level view of programming • Compile the source code. • Compilation is the process of converting the source code into machine language – the very minimalist language that is spoken directly by the machine in use. • Note: It is possible to program directly in machine language, but it is tedious, ugly, and error-prone. • Run or execute the machine-language file. • The compiler converts source code into a machine language file which is stored on the microprocessor and executed.
1 /* Fig. 2.1: fig02_01.c 2 A first program in C */ 3 #include<LABX-2.h> 4 5 voidmain() 6 { 7 fprintf(RS232, "Welcome to C!\n" ); 8 9 } A Simple C Program • Comments • Text surrounded by /* and */ is ignored by computer • Used to describe program • #include <LABX-2.h> • Preprocessor directive • Tells computer to load contents of a certain file (header files) • <LABX-2.h> allows standard input/output operations Welcome to C!
A Simple C Program, Cont. • void main() • C programs contain one or more functions, exactly one of which must be main • Parenthesis used to indicate a function • Braces ({ and }) indicate a block • The bodies of all functions must be contained in braces • All statements must end with a semicolon ( ; )
What do program instructions look like? • A simple program has at least these three main parts • variable declaration • variable initialization • main body
Constants • Constants are declared once and do NOT change • Syntax #define PI = 3.1416 • Do NOT use a semicolon for #define) • Declare constants before the main() function
Variables in Programming • Represent storage units in a program • Used to store/retrieve data over life of program • Type of variable determines what can be placed in the storage unit • Assignment – process of placing a particular value in a variable • Variables must be declared before they are assigned • The value of a variable can change; A constant always has the same value
Naming variables • When a variable is declared it is given a name • Good programming practices • Choose a name that reflects the role of the variable in a program, e.g. • Good: name, ssn; • Bad : n, no; • Restrictions • Name must begin with a letter; otherwise, can contain digits or any other characters. C is CASE SENSITIVE! • Ab is not the same as ab
Basic C variable types • There are three basic data types in C: • char • A single byte capable of holding one character in the local character set. [Ex: a A b B + & …] • int • An integer of unspecified size [Ex: 17, -99] • float • Single-precision floating point [Ex: 7.4, -35.63, 2.001] • The range of these data types is limited but it can be extended by adding 8, 16 or 32 at the end like float32 or int16 etc.
Variable Declaration • All variables must be declared in a C program before the first executable statement involving the variables! Examples: main() { int a, b; float c; /* Do something here */ a=5; b=19; c=(a+b)/10; }
Declaring variables • All variables must always be declared before the first executable instruction • Variable declarations are always: • var_typevar_name; • int age; • float cost_of_soda; • char your_name, my_name; /* multiple variables are ok */ • In most cases, variables have no meaningful value at this stage. Memory is set aside for them, but they are not meaningful until assigned.
Variable assignment • After variables are declared, they should be given values. This is called assignment and it is done with the ‘=‘ operator. Examples: float a, b; float c; b = 212; c = 200; a=b+c; (a is now equal to 412)
Assigning values to Variables • Either when they are declared, or at any subsequent time, variables are assigned values using the “=“ operator. • Examples int age = 52; //joint declaration/assignment double salary; salary = 150000.23; age = 53; //value may change at any time
Assignment, cont. • Be careful to assign proper type – contract between declaration and assignments must be honored • int x=2.13 (not allowed since 2.13 is NOT and int) • double x = 3; (ok because 3 = 3.0) • char c = 300; (NOT ok because 300 is not a char)
Arrays • Arrays are multiple variables of the same type grouped together • int x[10] (10 integers grouped together called “x”) • char name[20] (20 characters called “name”) • Declare variables the same way as before, just add [ ] at the end with the number of variables you want in the array • Example • char c, my_name[6] = “Daniel”; • c = my_name[3]; (c = ‘i’, count up from 0) Example # 2; int i = 4; c = my_name[i]; (c = ‘e’ since i=4)
The printf Executable Statement • The only executable statements we’ve seen to this point are • Assignments • The printf and gets functions • Assignment expressions with simple operators (+, -) • Very hard to write any program without being able to print output. Must look at printf in more detail to start writing useful code.
printf(), cont. • Sends output to standard out, which for now we can think of as the terminal screen. • General form printf(format descriptor, var1, var2, …); • format descriptor is composed of • Ordinary characters • copied directly to output • Conversion specification • Causes conversion and printing of next argument to printf • Each conversion specification begins with %
printf() examples • Easiest to start with some examples • printf( “hello world”); • Output: hello world • as a string • printf(“j=%d, k=%d”, j, k); • If j=10 and k=99 • Output: j=10, k=99 • the value of the variable j as an integer followed by the value of the variable k. • printf(“The sum (j + k) =\n%d”, j+k); • Output: The sum (j + k) = 109 • \n for new line.
More on format statements • The format specifier in its simplest form is one of: • %s • sequence of characters known as a String • Not a fundamental datatype in C (really an array of char) • %d • Decimal integer (i.e. base ten) • %f • Floating point • Note that there are many other options. These are the most common, though, and are more than enough to get started.
Invisible characters • Some special characters are not visible directly in the output stream. These all begin with an escape character (i.e. \); • \n newline • \r carriage return (back to the start of line) • \t horizontal tab • \a alert bell • \v vertical tab
Getchar/putchar example /* uses getchar with while to echo user input */ #include<stdio.h> int main(){ int c; /* holds the input character value */ c = getchar(); /* reads first character from input stream with keyboard, this is signaled by Enter key*/ while (1){ /* loop forever */ putchar(c); /* write char to keyboard */ c = getchar(); /*get next char in stream */ } }
Gets/puts example • Works like getc/putc but for entire strings [arrays] of characters • Gets will capture a sting of characters until it detects a “null” character, also known as the “enter” key • Puts will output a string of text that is terminated with a “null” character
Second C Program User variables, reading user input
1 /* Profram2.c 2 #include <stdio.h> 3 #include <labx2.h> /*Circuit board specific header file 4 5 int main() 6 { 7 char name[20]; /* declaration */ 8 9 printf( “Hello\n" ); /* prompt */ 10 printf( “What is your name?\n" ); /* prompt */ scanf( "%d", &integer1 ); /* read an integer */ 11 gets(name); 12 printf( “\n %s, Welcome to the world of microprocessors“, name); /* prompt */ /* read an integer */ 13return 0; /* indicate that program ended successfully */ 14} Hello What is your name? Sam Sam, Welcome to the world of microprocessors
Arithmetic Operations • Five simple binary arithmetic operators • + “plus” c = a + b • - “minus” c = a - b • * “times” c = a * b • / “divided by” c = a/b • % “modulus” c = a % b • What are the values of c in each case above if • int a = 10, b = 2; • float a = 10, b = 2; • int a = 10; float b = 2; ??
Relational Operators • Four basic operators for comparison of values in C. These are typically called relational operators: • > “greater than” • < “less than” • >= “greater than or equal to” • <= “less than or equal to” • For the declaration int a=1,b=2,c; what is the value of the following expressions? a > b; a<b; a>=b;a<=b
Relational Operators, cont. • Typically used with conditional expressions, e.g. • if (a < 1) then … • However, also completely valid expressions which evaluate to a result – either 1 (true) or 0 (false). int c, a=2, b=1; c = (a > b) What is the value of c? • Note: We’ll talk about order of precedence for multipart expressions a little later. For now, we force an order using parentheses.
Equality Operators • C distinguished between relational and equality operators. • This is mainly to clarify rules of order of precedence. • Two equality operators • == “is equal to” • != “is not equal to” • These follow all of the same rules for relational operators described on the previous slide.
Logical Operators • Logical Operators are used to create compound expressions • There are two logical operators in C • || “logical or” • A compound expression formed with || evaluates to 1 (true) if any one of its components is true • && “logical and” • A compound expression formed with && evaluates to true if all of its components are true
Logical Operators, cont. • Logical operators, like relational operators, are typically used in conditional expressions • if ( (a == 1) && (b < 3) || (c == 1) ) etc. • Also works with characters char x=‘A’, y = ‘G’, C = ‘A’ If(x == C) y=‘C’; Printf(%c,y); //what is printed ?
Converting String to integer • An important function when using argv/argc is atoi. • atoi converts a String argument to an integer in the following way: int input, output; input = atoi(argv[1]); output = input + 1; printf("%d\n", output); > a.out 333 334
Reading single characters • Another important pair of functions for keyboard input/output is getchar/putchar • getchar reads a single character from the input stream; putchar write a single character to the standard out for example: int c; c = getchar(); /* blocks until data is entered if more than one char is entered only first is read */ putchar(c); /* prints value of c to screen */
While loops • A simple technique for repeating a statement or group of statements until some specified condition is met • General form: while (expr){ statement1; statement2; . . } • If expr evaluates to true (ie not 0), then perform statement1, etc. Otherwise, skip to end of while block. • Repeat until expr evaluates to false (ie 0).
FOR Loops • Syntax: for (initialize; test; change) { stuff } • Example • for(i=0; i<100; i=i+1) • { printf(“i is now = %u \r\n”, i); } • will print out 1 through 99, each number on a new line
While example • Syntax: while (test) { stuff } • Example Note: != means not equal • While(getc() != ‘X’) • { printf(“Still running.. /r/n”,); } • will print Still running… on a new line until the user enters X on the keyboard
If example • Syntax: if (test) { stuff } • Example • if(X < 100) • { printf(“X is less that 100 /r/n”); } • will print X is less than 100 unless X is greater than or equal to 100