[go: up one dir, main page]

Academia.eduAcademia.edu

C Programming

C Programming Session 5 Prepared by: ND. Raymond Introduction What Is C? C is a programming language. The C language was first developed in 1972 by Dennis Ritchie at AT&T Bell Labs. Ritchie called his newly developed language C simply because there was a B programming language already. (As a matter of fact, the B language led to the development of C.) C is a high-level programming language. In fact, C is one of the most popular general-purpose programming languages. Introduction High-level programming languages, including C, have the following advantages: Readability: Programs are easy to read. Maintainability: Programs are easy to maintain. Portability: Programs are easy to port across different computer platforms. Historical Development of C 1960 International Committee ALGOL 60 CPL 1963 National Committee 1967 1 Man Committee Martin Richards - BCPL 1970 Ken Thompson, AT & T Bells Lab B 1972 Dennis Ritchie, AT & T Bells Lab C A Simple C Program Code Code is a series of instructions that a computer will execute when the code is run. Files Code is stored in text files that usually any text editor can open. These files contain your code and nothing else. Compiler A compiler is a program that takes a code file (or many code files) and turns it into a series of instructions that a computer will run as a program. Where C Stands LLL Machine Oriented Ex. Assembly, Machine Better Machine efficiency Computer Languages HLL Problem Oriented Ex. Basic, Fortran, Pascal,Cobol Better Programming efficiency In The Beginning... English Alphabets, Digits Words, Numbers Sentences Paragraph C Alphabets, Digits, Sp. Symbols Constants, Variables, Keywords Statements or Instructions Program Alphabets, Digits, Special Symbols Alphabets A - Z, a - z Digits 0-9 Sp. Symbols Total - 32 Constants and Variables Variables 3 x + 2 y = 20 Constants C Constants Primary Integer Real Character Secondary Pointer Array String Structure Union Enum etc. Integer Constants Ex. 421 -62 +45 4096 Rules:  1. No decimal point. 72  72.0 2. May be +ve or -ve. Default: +ve 3. No comma or spaces 32,500  4. Valid Range: -32768 to +32767 4 7 3  Real Constants Ex. 427.62 +24.297 -0.00254 Rules: 1. Must contain a decimal point. 2. May be +ve or -ve. Default: +ve 3. No comma or spaces. 4. Valid Range: -3.4x 1038 to +3.4 x 1038 Forms of Real Constants 427.62 +24.295 -0.00254 4.2762E2 2.4295e1 -2.54e-3 Exponential Form Fractional Form 4.2762 Mantissa E 2 Exponent Character Constants Ex. ’A’ ’m’ ’3’ ’+’ Rule : A single character enclosed within a pair of ’ ’. Are They OK? ‘Z’ ’Nagpur’   C Variables Primary Integer Real Character Secondary Pointer Array String Structure Union Enum etc. What Happens in Memory... Memory x=3 y=4 y 4 3 7 z x z=x+y Variables x=5 int x = 5; int y = 10; int x = 5; int z = x + y; Int This is the datatype for integers, which are numbers without a decimal point, like 2 or 20,392. In Processing, integers can be as large as 2,147,483,647 and as low as –2,147,483,648. Signed versus unsigned Sometimes an int is 4 bytes or 32 bits of information all the time and that it can store 4 bytes worth of information. If you have an int that is never going to use a negative number, you can use an unsigned int that stores anything from 0 to 4,294,967,295. Unsigned variables don’t store negative numbers, whereas signed variables do. unsigned int = 5; Float The float is the datatype for floating-point numbers, which are numbers that have a decimal point. Signed float variables can be as large as 2,147,483,647 and as low as −2,147,483,647. Char This type can contain characters, that is, single letters or typographic symbols such as A, d, and $. char firstLetter = 'a'; char secondLetter = 'b'; bool or boolean Boolean values store two possible values: true and false . In C++ and Arduino, the true is actually a 1, and the false is actually a 0. It’s usually clearer to use true and false , but you can use 1 and 0 if you like. For Arduino and Processing, you do the following: boolean b = true; In C++, you do this: bool b = true; String A string is a sequence of characters. The differences between a string and a char is that a string is always defined inside double quotes ( "Abc" ) and can consist of multiple characters, while char variables are defined inside single quotes ( 'A' ) and can consist of only one character. Arrays An array contains one or more variables in a list. Here’s what the array looks like in Arduino or C++: int arr[] = {1, 2, 3}; or: int arr[3]; or: int array[3] = {1, 2, 3}; char arr[3] = {'a', 'b', 'c'}; Operators + adds two values, for example: int apples = 5 int moreApples = apples + 3; // moreApples is equal to 8. The exception occurs when you add strings; you end up with the two strings stuck together: string first = "John"; string second = "Brown"; string full = first+second; // now full is JohnBrown The other simple mathematical operators are – (subtraction), * (multiplication), and / (division). The last mathematical operator is % , the modulo. The modulo tells you what is left over (the remainder) when the value on the left is divided by the value on the right. Here are some examples: 8 % 2 // equals 0 since there's no remainder when 8 is divided by 2 17 % 2 // equals 1 since there's a remainder of 1 when 17 is divided by 2 19 % 5 // equals 4 since the remainder is 4 when 19 is divided by 5 12 % 11 // equals 1 since the a remainder of 1 when 12 is divided by 11 19.0 % 5 // equals 4.0 since we're dealing with floats += Adds the value on the right to the value on the left: int height = 6; height += 1; // height is now 7 height += 10; // height is now 17 -= Subtracts the value on the right from the variable on the left: int size = 16; size -= 8; // height is now 8 size -= 6; // height is now 2 ++ and – Add one or subtract one from the variable on the left: int hearts = 2; hearts++; // hearts is now 3 hearts--; // hearts is now 2 again hearts--; // hearts is now 1 *= or /= These work roughly the same as the += and -= statements, multiplying or dividing the variable on the left by the value on the right: int i = 15; i /= 3; // i is now 5 int j = 20; j /= 2; // j is now 10 float k = 100.0; k /= 3.333333; // k is now 30.000004 float m = 100.0; m /= '2'; // not a good idea i *= 4; // i is now 20 m *= 0.5; // m was 2.0 and is now 1.0 == (equal to) Compares whether two things are equal. For example: 5 == 4 // false 'a' == 'a' // true (12 / 3) == (2 * 2); // true 4.1 == 4 // false char(102) == int('f') // true, because 102 is 'f' in ASCII "duck" == 0.002 // false, because it doesn't make any sense != (not equal to) Checks whether things are not equal, for example: 3 != 1 //true, they're not equal 'B' != 'b' // also true, they're not equal > (greater than) Checks whether the value on the left is greater than the value on the right, just like in math class: 4 > 3 // true 5 > 192901.2 //false "fudge" > 8 // false, because it doesn't make any sense != (not equal to) Checks whether things are not equal, for example: 3 != 1 //true, they're not equal 'B' != 'b' // also true, they're not equal >= (greater than or equal to) Checks whether the value on the left is greater than or equal to the value on the right, just like in math class: 3 >= 3 // true, since they're equal 0 >= −0.001 // since 0 is greater than −0.001, this is true '?' >= 'h' // true, since '?' is 63 in ASCII and 'h' is 104 4 >= 28 // false "happy" >= "sad" // false, because it doesn't make any sense <= (less than or equal to) Checks whether the value on the left is smaller than or equal to the value on the right, again, just like in math class: 13.001 <= 13.001 // true, since they're equal 0 <= −0.001 // since 0 is greater than −0.001, this is false '!' <= '7' // true, since '!' is 33 in ASCII and 'h' is 55 && Evaluates the statement on the left and the statements on the right and returns true if they are both true: (4 > 3) && ('f' > '1') // true ((5 * 2) == 10) && ((6 - 3) != 4) // true (5 < 10) && (2 > 4) // false, even though the left is true, the right isn't || Evaluates the statement on the left and the statements on the right and returns true if either one of them is true: (4 < 3) || ('f' > 'e') // true, left isn't true but the right is ((5 * 2) == 10) || ((6 - 3) != 4) // both are true ('b'=='g') || (2 > 4) // false, none of them are true Control Statements If one thing is true, then you’ll want to do something different if it’s false . if/then if(condition) { result if the condition is true } else { result if the condition is false } There must be a true / false expression in the brackets next to the if . Here’s an example: int myWeight = 72; if(myWeight > 100) { print(" you're getting heavy! "); } else { print(" you're still doing ok "); } You can also use the if statement without an else : int myHeight = 181; if(myHeight > 200) { print(" you're too tall "); } There is one last permutation on this pattern: if(age == 5) { print(" you're 5!"); } else if(age == 25) { print(" you're 25!"); } else { print(" can't login "); // if neither of the above is true } for Loop The for statement lets us do things over and over again, for a specified number of repetitions. int i; for(i = 0; i < 10; i++) { print(char(i)+", "); // this will print 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, } It is also entirely possible to use subtraction in the for loop: for(int i = 5; i>-1; i--) { print(i); } while Loop The while loop is similar to the for loop, but it is slightly less sophisticated: while(trueOrFalse){ //something to do each time } int j = 0; while(j < 100) { print(" what's up? "+j); j++; // if j is not incremented we end up with an infinite loop } continue The continue statement tells a loop to skip over any further instructions and go on to the next repetition. For instance, if you wanted to loop through a certain number of items and process only odd numbers for(int i = 0; i< 10; i++) { if( i % 2 == 0){ continue; } println(i + " is not divisible by 2"); } 1 is not divisible by 2 3 is not divisible by 2 5 is not divisible by 2 7 is not divisible by 2 9 is not divisible by 2 Functions A function is a name for a grouping of one or more lines of code and is somewhat like a variable in that it has a type and a name. “When someone gives you some money, add the amount given to you to the amount that you already have and report that number back to me.” There are a few parts there that can be broken out: • An amount of money that you are given • Adding the amount given to you to the amount that you already have • Reporting that number int myBank = 0; Then you create a function that takes money, adds it to myBank , and returns that value: int moneyReceived(int money){ myBank += money; return myBank; } the function always has the following pattern: type, function name, parentheses, and any parameters that need to be passed to the function: int multiplyByTwo(int value){ return value * 2; } This will work if the square() function looks like this: int square(int val) { return val*val; } int ledPin= 13; // choose the pin for the LED int buttonPin = 10; // choose the input pin (for a pushbutton) void setup() { // set the pin for the light as an output pin pinMode(ledPin, OUTPUT); // set the pin for the button as an input pin pinMode(buttonPin, INPUT); } void loop() { // get the value on the pin that the button is connected to int val = digitalRead(buttonPin); // check if the input is LOW, this will indicate // whether the button is pressed if (val == 0) { // if the button is pressed, then turn the light on digitalWrite(lightPin, HIGH); // turn LED ON // otherwise, turn the light on } else { digitalWrite(lightPin, LOW); // turn LED OFF } } The First C Program p = 1000.50 n=3 r = 15.5 si = p * n * r / 100 Declaring Variables... float p int n , r, si p = 1000.50 n=3 r = 15. 5 si = p * n * r / 100 Tip1: All variables must be declared. Printing Values... float p, r, si int n p = 1000.50 n=3 r = 15. 5 si = p * n * r / 100 printf ( ”%f”, si ) Terminology Matters () Parentheses { } Braces [] Brackets General Form of printf( ) printf ( ”format string”, list of variables ) can contain %i - integer %c - character %f - float Ex. printf ( ”%f %f %f %i”, p, r, si, n ) Statement Terminators float p, r, si int n I am a boy I go to school float p, r, si ; int n ; : colon Statement Terminator ; semicolon What To Execute main( ) Collective Name float p, r, si ; int n ; p = 1000.50 ; n=3; r = 15. 5 ; si = p * n * r / 100 ; printf ( ”%f”, si ) ; What Belongs to main( ) main( ) { float p, r, si ; int n ; p = 1000.50 ; n = 3 ; r = 15. 5 ; si = p * n * r / 100 ; printf ( ”%f”, si ) ; } Comments Are Useful /* Calculation of simple interest */ main( ) { Note float p, r, si ; int n ; p = 1000.50 ; n = 3 ; r = 15. 5 ; si = p * n * r / 100 ; printf ( ”%f”, si ) ; } Remark Tips About Comments  Any number of comments anywhere  Multiline comments /* ............................. ............................... */  Nested comments /* .............. /* ....... */ ........ */   int ledPin1 = 8; int ledPin2 = 9; int ledPin3 = 10; int ledPin4 = 11; int ledPin5 = 12; int ledArray[] = {8, 9, 10, 11, 12}; int count = 0; int timer = 75; void setup(){ for (count=0;count<5;count++){ pinMode(ledArray[count], OUTPUT); } } void loop(){ for (count=0;count<5;count++){ digitalWrite(ledArray[count], HIGH); delay(timer); digitalWrite(ledArray[count], LOW); delay(timer); } }