🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Introduction to C Programming.pptx

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Document Details

LogicalGingko3026

Uploaded by LogicalGingko3026

Central Connecticut State University

2021

Tags

C programming programming basics computer science

Full Transcript

Introduction to C Programming Prepared By Hassan Shibly, PhD Professor in Robotics and Mechatronics 2021 Programing Steps Step 1: Write the Source Code: Enter the Source Codes using a programming text editor such...

Introduction to C Programming Prepared By Hassan Shibly, PhD Professor in Robotics and Mechatronics 2021 Programing Steps Step 1: Write the Source Code: Enter the Source Codes using a programming text editor such as NotePad++ for Windows, or an Interactive Development Environment (IDE) such as CodeBlocks. Step 2: Build the Executable Code: Compile and Link the source code "Program1.c" into executable code "Program1.exe" in Windows or on IDE such as CodeBlocks, push the "Build" button. Step 3: Run the Executable Code: Execute “Run” the program on IDE such as CodeBlocks push the "Run" button. C Terminology and Syntax Case Sensitivity C is case sensitive – ROBO is not a Robo, and is not a robo. Comments A multi-line comment begins with. (Forward slash and asterisk) One line comment begins with // and lasts till the end of the line. Comments are NOT executable statements and are ignored by the compiler. Comments provide useful explanation and documentation. C Terminology and Syntax (Cont.) Statement A programming statement performs a piece of programming action. It must be terminated by a semi-colon (;). Preprocessor Directive The #include in the starting of the Source Codes is a preprocessor directive and not a programming statement. A preprocessor directive begins with hash sign (#). It is processed before compiling the program. A preprocessor directive does not terminate by semicolon. C Terminology and Syntax (Cont.) Header files consist of variables and the definition of functions, and this is incorporated using the pre-processor #include statement. As an example; is to use the printf() function. The program that we write has the line: #include All header files are in the subdirectory: /usr/include and have the extension.h Examples: #include < string.h> #include < math.h> #include < mylib.h> The use of double quotes “ ” around the file name informs the compiler to begin the search for the quoted file in the current directory. The use of angle brackets < > around the file name informs the compiler to begin the search for the specified file in the compiler’s include directories. 5 C Terminology and Syntax (Cont.) Block A block is a group of programming statements enclosed by braces { }. This group of statements is treated as one single unit. There is one block in this program, which contains the body of the main() function. There is no need to put a semi-colon after the closing brace. Whitespaces Blank, tab, and newline are collectively called whitespaces. Extra whitespaces are ignored, i.e., only one whitespace is needed to separate the tokens. They could help you to understand and remember the program. Example of Program Raw Source Code 1 4 #include // to include IO operations header file 5 6 int main() 7 // Main program entry point 8 { 9 printf("I like ROBO 110\n"); // Print on the screen 10 return 0; // Terminate main(), normal termination 11 } // End of main() Explanation of the Program Comments Multi-line Comment: begins with. End-of-line Comment: begins with // double forward slashes and lasts until the end of the current line. Calling Header File The "#include" is called a preprocessor directive. A preprocessor directive begins with a # sign, and is processed before compilation. The directive "#include " tells the preprocessor to include the "stdio.h" header file to support input/output operations. The abbreviation stdio is for Standard Input Output. This line shall be present in all programs. Explanation of the Program (Cont.) Main Function: int main() {...... } The “main()” function is the entry point of program execution. The “main()” is required to return an int (integer). Function printf("I like ROBO 110\n"); The function printf() prints the string " I like ROBO 110" followed by a newline (\n). The newline (\n) brings the cursor to the beginning of the next line. Terminating Program To terminate the main() function and returns a value of 0 to the operating system is return 0 Typically, return value of 0 signals normal termination; whereas value of non-zero (usually 1) signals abnormal termination. This line is optional. C compiler will implicitly insert a "return 0;" to the end of the main() function. The Steps of Programing Step 1: Write the source codes (.c) and call needed header files of extension (.h). Step 2: Pre-process the source codes according to the preprocessor directives. The preprocessor directives begin with a hash sign (#), such as #include and #define. They indicate that certain manipulations (such as including another file or replacement of symbols) are to be performed before compilation. Step 3: Compile the pre-processed source codes into object codes (.obj,.o). Step 4: Link the compiled object codes with other object codes and the library object codes (.lib,.a)to produce the executable code (.exe). Step 5: Load the executable code into computer memory. Step 6: Run the executable code. Process of C programs Program Template Typical C program template is as follows: Choose a meaningful filename for you source file that reflects the purpose of your program with file extension of ".c". Write your programming statements inside the body of the main() function. ……………………………………………………… #include int main() { //Program Statements return 0; } ……………………………………………………… Download IDE of “codeblocks” Code::Blocks is a free, open-source cross-platform IDE that supports multiple compilers including GCC, Clang and Visual C++. http://www.codeblocks.org/ Follow C compiler guide. Please keep with you a USB flash memory stick to save your work at class. Open Empty File Edit Save File As Select OneDrive-CCSU then go to folder ClaaApps and save it Program1 after saving Editor General Setting After Setting the Font to 16 Build and Run Result Setting the Result Widow Type of Numbers Type Keyword Value range which can be represented by this data type -32,768 to 32,767 or - Number int 2,147,483,648 to 2,147,483,647 Small Number short -32,768 to 32,767 -2,147,483,648 to Long Number long 2,147,483,647 1.2E-38 to 3.4E+38 till 6 Decimal Number float decimal places First Example: Adding Two Integer Numbers Result Program Explanation First declare three int (integer) variables: number1, number2, and sum. A variable is a named storage location that can store a value of a particular data type, in this case, int (integer). The declaration can be to declare one variable in one statement. Or to declare many variables in one statement, separating with commas, such as: int number1, number2, sum; To perform the sum of the two variables we assign values to them first and then compute the sum and store in variable sum. Function “printf” printf(“The sum of %d and %d is %d\n”, number1, numbr2, sum); The printf() function is used to print the result. The first argument in printf() is known as the formatting string, which consists of normal texts and so-called conversion specifiers. Normal texts will be printed as they are. A conversion specifier begins with a percent sign (%), followed by a code to indicate the data type, such as d for decimal integer. %d can be treated as placeholders, which will be replaced by the value of variables given after the formatting string in sequential order. The first %d will be replaced by the value of number1, second %d by number2, and third %d by sum. The \n denotes a newline character. Printing a \n bring the cursor to the beginning of the next line. printf and scanf functions The printf() function is to put out a prompting message. The scanf("%d", &number1); Then use of scanf() function is to read the user input from the keyboard and store the value into variable number1. The first argument of scanf() is the formatting string (similar to printf(). The %d conversion specifier provides a placeholder for an integer, which will be substituted by variable number1. The ampersand sign &, stands for address-of operator, before the variable. Adding Two Integer Numbers Using scanf function Result Reading Multiple Integers Multiple items can be read in one scanf() statement as follows: printf("Enter two numbers: "); // Display a prompting message scanf("%d%d", &number1, &number2); // Read two integers As an exercise repeat the previous example with one scanf statement Basic Arithmetic Operators Addition, subtraction, multiplication, division and remainder are binary operators that take two operands (e.g., x + y); While negation (e.g., -x), increment and decrement (e.g., x++, --x) are unary operators that take only one operand. Basic Arithmetic Operators (Cont.) Integer Division and the Remainder Operator Integer division yields an integer result For example, the expression 7 / 4 evaluates to 1 and the expression 17 / 5 evaluates to 3 C provides the remainder operator, %, which yields the remainder after integer division Can be used only with integer operands The expression x % y yields the remainder after x is divided by y Thus, 7 % 4 yields 3 and 17 % 5 yields 2 33 Program A program is a sequence of instructions (called programming statements), executing one after another - usually in a sequential manner. Class Practice 1. Print the first letter of your name using one printf() statement for each line of outputs. End each line by printing a newline (\n). As an example: 2. Write a program to prompt user for 5 integer numbers and print their sum. 3. Write a source code “program” to find the remainders of 12 ,75, 67 117, 1773 when they are divided by 5 and then by 3. 4. Write a program to prompt user for 5 integer numbers and print their product. Use an int variable product to store the product where the operator for multiplication is “*”. Format There are four basic data types: 1. integer as: 15 , 31 2. character as: day 3. float as: 3.14, or 2.66e6, Float stands for floating point, for numbers which may have fractional part. 4. double type higher precision than float. Declaration examples: 4. int length, i, j, k; 5. char day; 6. float x, y, distance, time; 7. double electron_mass 36 Example #include value of amount is 100 dollar #include value of income is 150.449997 dollar main () { value of group is A int amount=100; Electrical charge is 0.000165 float income=150.45; coulombs char group; char A; Process returned 40 (0x28) execution time : 0.073 s double charge; Press any key to continue. group = 'A'; charge=1.654321e-4; printf("value of amount is %d dollar \n",amount); printf("value of income is %f dollar \n",income); printf("value of group is %c \n", group); printf("Electrical charge is %f coulombs \n",charge); } 37 Specifiers 38 Special Characters for Cursor Control 39 Names in C Names (identifiers) in C begins with character or underscore as: Prog , Prog1 , prog_1, My_Name_is , _hi Users use lower case for variable name and upper case for symbolic names of constants There are reserved identifiers in C as: int , char, if , else , while … 40 Reserved Keywords Keywords auto double int struct break else long switch case enum register typedef char extern return union const float short unsigned continue for signed void default goto sizeof volatile do if static while [2000 Prentice Hall Inc.] 41 Constants in C To define a value which cannot be changed (Constant) is achieved by using the processor directive: #define. Examples: #define PI 3.14159 #define N 200 #define ON 1 #define RATE 0.05 Important points to remember that preprocessor statement: 1. Begins with # and does not end with semicolon” ;”. 2. Traditionally written at the beginning of the source file 3. Compiler handles preprocessor statements first and then constants are been replaced by their values before program compiling 42 Variables in C Variable is a named memory location Declaration of variable is an actual memory reservation for the variable Content of variable and name can change Variables must be declaredValue Name before they are used Type number 75 int pi 3.1416 float sum -356 int accuracy 0.0002 double 43 44 45 New and Old Value Swapping Two Numbers 47 48 Example of Using Math Headers File (Hypotenuse,Opposite,Adjacent) Format 50 51 52 53 54 55 56 Write a source code to convert 25o centigrade (Celsius) to Fahrenheit and vice versa. The Conversion formulas are: LOOPS while and for statements are used for repetitions while Statement while (condition test) { // C- statements, which requiresrepetition. // Increment (++) or Decrement (--) Operation. } // Example int main() { int variable=1; while (variable = 70 ) puts("C"); else if ( grade >= 60 ) puts( "D" ); else puts( "F" ); If the variable grade is greater than or equal to 90, all four conditions will be true, but only the puts statement after the first test will be executed. After that puts is executed, the else part of the “outer” if…else statement is skipped. 103 Grading Example (cont.) Example getch() This is an input function. This is used to read a single character from the keyboard like getchar() function. But getchar() function is a buffered function while getch() function is a non- buffered function. The character data read by this function is directly assign to a variable rather it goes to the memory buffer, the character data directly assign to a variable without the need to press the Enter key. Another use of this function is to maintain the output on the screen till you have not press the Enter Key. The general syntax is as: v = getch(); where v is the variable of character type. Example getche() All are same as getch() function except it is an echoed function. It means when you type the character data from the keyboard it will visible on the screen. The general syntax is as: v = getche(); where v is the variable of character type. Example Switch Multiple-Selection Statement Switch is a control statement that allows a value to change control of execution. Occasionally, an algorithm will contain a series of decisions in which a variable or expression is tested separately for each of the constant integral values it may assume, and different actions are taken. This is called multiple selection. The switch statement consists of a series of case labels, an optional default case and statements to execute for each case as shown in next slide. Switch, break Statements Between Cases 111 Example Example of Switch Case Example of Switch Case Example of Switch Case (Cont.) Next figure shows the use of switch statement to count the number of each different letter grade students earned in exam. ©2016 Pearson Education, Inc., Hoboken, 117 NJ. All rights reserved. ©2016 Pearson Education, Inc., Hoboken, 118 NJ. All rights reserved. ©2016 Pearson Education, Inc., Hoboken, 119 NJ. All rights reserved. ©2016 Pearson Education, Inc., Hoboken, 120 NJ. All rights reserved. goto Statement goto statement tells to skip and go directly to the label mentioned in the goto statement. Syntax of goto statement goto label_name; label_name: C-statements Example Example do…while Iteration Statement The do…while iteration statement is similar to the while statement. In the while statement, the loop-continuation condition is tested at the beginning of the loop before the body of the loop is performed. The do…while statement tests the loop-continuation condition after the loop body is performed. Therefore, the loop body will be executed at least once. When a do…while terminates, execution continues with the statement after the while clause. ©2016 Pearson Education, Inc., Hoboken, NJ. All rights 124 reserved. do…while Iteration Statement (Cont.) do…while Statement Flowchart The Figure shows the do…while statement flowchart, which makes it clear that the loop-continuation condition does not execute until after the action is performed at least once. 125 Example of do-while statements break and continue Statements The break and continue statements are used to alter the flow of control. break Statement The break statement, when executed in a while, for, do…while or switch statement, causes an immediate exit from that statement. Program execution continues with the next statement. Common uses of the break statement are to escape early from a loop or to skip the remainder of a switch statement. break and continue Statements (Cont.) continue Statement The continue statement, when executed in a while, for or do…while statement, skips the remaining statements in the body of that control statement and performs the next iteration of the loop. In while and do…while statements, the loop-continuation test is evaluated immediately after the continue statement is executed. In the for statement, the increment expression is executed, then the loop-continuation test is evaluated. Figure uses the continue statement in a for statement to skip the printf statement and begin the next iteration of the loop. break and continue Statements The Figure demonstrates the break statement in a for iteration statement. When the if statement detects that x has become 5, break is executed. This terminates the for statement, and the program continues with the printf after the for. The loop fully executes only four times. Example of Continue statement Example of break-continue statements Function in C Language A function is a block of code that perform a task. It takes information, does some computation, and returns a new piece of information. These functions are known as user-defined functions. Function in C language Function in C Language Example of function to find the difference of two numbers Factorial of a Number Using Recursion Example Pointers in C language A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. A Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc. Pointer Syntax : data_type *var_name; Example : int *p; char *p; The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to. Pointers in C language (Cont.) Normal variable stores the value whereas pointer variable stores the address of the variable. The content of the C pointer always be a whole number i.e. address. Always C pointer is initialized to null, i.e. int *p = null. The value of null pointer is 0. & symbol is used to get the address of the variable. * symbol is used to get the value of the variable that the pointer is pointing to. If a pointer in C is assigned to NULL, it means it is pointing to nothing. Two pointers can be subtracted to know how many elements are available between these two pointers. But, Pointer addition, multiplication, division are not allowed. The size of any pointer is 2 byte (for 16 bit compiler). How to Use Pointers? There are a few important operations, which we will do with the help of pointers very frequently. 1. Define a pointer variable, 2. Assign the address of a variable to a pointer 3. Access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand. Example Example Program for Pointers map() Re-maps a number from one range to another. A value of from Low would get mapped to Low, a value of from High to High, values in-between to values in-between, etc. Does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired. Note that the "lower bounds" of either range may be larger or smaller than the "upper bounds" so the map() function may be used to reverse a range of numbers, for example y = map(x, 1, 50, 50, 1); The function also handles negative numbers well, so that this example y = map(x, 1, 50, 50, -100); is also valid and works well. The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated, and are not rounded or averaged. } Example Code void setup() {} void loop() { int val = analogRead(0); val = map(val, 0, 1023, 0, 255); analogWrite(9, val); }

Use Quizgecko on...
Browser
Browser