690 likes | 922 Views
Lecture 2. Introduction To C Language. The next step is coding. Coding is a process of converting flowchart to program code (source code). But, before you can start doing this, you should learn some basics including the language itself. Writing a C Program is a systematic task. Problem.
E N D
Lecture 2 Introduction To C Language
The next step is coding Coding is a process of converting flowchart to program code (source code) But, before you can start doing this, you should learn some basics including the language itself.
Writing a C Program is a systematic task Problem Flowchart Intermediate code -prepare a rough code- Complete code - add details -
The conversion is almost straight forward Example: multiplying two numbers Intermediate C Code void main (void) { scanf(&A); scanf(&B); C = A * B; printf(C); } But!, the program still cannot be executed. It is not completed yet. This code is called an intermediate code.
You will get some errors Error 1: Call to undefined function ‘scanf’ The compiler doesn’t recognize ‘scanf’ Error 2: Undefined symbol ‘A’ The program is trying to use a variable A but has never been registered. Compiler doesn’t recognize the variable
Fixing the errors and completing the program This line will help the compiler to recognize words ‘scanf’ and ‘printf’. File stdio.h contains the information of those functions and some others. This tells to register (declare) variables. Compiler only recognizes registered variables. You may notice some extra things. These are called prompts. They used to let the user knows what is going on while the program is running
Example Problem: Finding the average of three numbers Flowcharts:
The ampersand (&) indicates that avrg is the output or result of the function-call. Intermediate code of the main flowchart Preparing the rough code void main () { scanf(&n1,&n2,&n3); Average(&avrg, n1, n2, n3); printf(avrg); }
The asterisk (*) indicates that result is an output parameter. Intermediate code of the function flowchart Preparing the rough code void Average(*result, a, b, c) { sum = a + b + c; *result = sum / 3.0; return; }
Complete source code Adding details to the rough code. The details are shown by bold texts #include <stdio.h> void Average(float *result, float a, float b, floatc) { float sum; sum = a + b + c; *result = sum/3.0; return; } void main () { float n1; float n2; float n3; float avrg; printf ("Enter three numbers: “); scanf(“%f%f%f”, &n1, &n2, &n3); Average(&avrg,n1,n2,n3); prinf("The average is %f“,avrg); }
Example: This example is the same as the previous one but this time the result is “return” Problem: Finding the average of three numbers Flowcharts:
Intermediate code of the main flowchart Preparing the rough code void main () { scanf(&n1,&n2,&n3); avrg = Average(n1, n2, n3); printf(avrg); }
Notice that, • result is removed • from parameter list • “void” is also removed Intermediate code of the function flowchart Preparing the rough code Average(a, b, c) { sum = a + b + c; result = sum / 3.0; return result; }
Complete source code Adding details to the rough code. The details are shown by bold texts #include <stdio.h> float Average(float a, float b, floatc) { float sum; float result; sum = a + b + c; result = sum/3.0; return result; } void main () { float n1; float n2; float n3; float avrg; printf ("Enter three numbers: “); scanf(“%f%f%f”, &n1, &n2, &n3); avrg = Average(n1,n2,n3); prinf("The average is %f“,avrg); }
Today’s Topics • Background of C • Structure of a C Program • Comments • Identifiers • Types • Variables and Constants • Formatted Input/Output
Figure 2-2: Structure of a C program Statement = Command or instruction
Figure 2-3: The greeting program The execution of the program begins at function ‘main’ void means it has no parameter Statement 1. Print output “Hello World” Statement 2. Terminate the program
Comment • Comment is a statement that will not be executed. • Compiler will ignore all comments in your program • It is used to describe part of your program; makes your program more readable. • This helps people and also yourself to understand your codes.
Figure 2-4: Examples of comments // This is single line comment
Identifiers • A symbolic name of data, functions or other objects • E.g: • main => symbolic name of main function • printf => symbolic name of a function that prints output onto the screen • Rules for identifiers: • First character must be alphabetic character or underscore • Must consist only alphabetic characters, digits, or underscores • First 31 characters of an identifier are significant • Cannot duplicate a reserved word
Example: • Valid Names: • a • student8 • student_name • _person_name • TRUE • FALSE • Invalid Names: • $a • 3name • person name • int • what?
In C language, identifiers are case-sensitive. Example: a is different from A.
A variable is a reserved location in memory that has a name has an associated type (for example, integer) holds data which can bemodified Variables
A variable must be declared before it can be used. HOW? A declaration statement has this format: type variable_name; type : what kind of data will be stored in that location (integer? character? floating point?) variable_name : what is the name of the variable? Variables
There are four basic data types in C Variable types Type Integer Floating point Character C keyword to use: int float double char
int Integer variables hold signed whole numbers (i.e. with no fractional part), such as 10, – 4353, etc. Integers typically take up 4 bytes ( = 32 bits, 1 for the sign, 31 for the number). The range of integers is typically from – 231 (approx –109) to + 231 (approx. 109) Variable types
float and double floating point variables hold signed floating point numbers (i.e. with a fractional part), such as 10.432, – 33.335, etc. double provides twice the precision of float. floats typically take up 4 bytes doubles take up 8 bytes The range of floats is approximately ±2127 (±1038) The range of doubles is approximately ±21023 (±10308) Variable types
char character variables hold single characters, such as 'a', '\n', ' ', etc. characters usually take 1 byte (8 bits). IMPORTANT : Note that the value of a character is enclosed in single quotes. Each character is essentially "encoded" as an integer. A computer normally stores characters using the ASCII code (American Standard Code for Information Exchange) Variable types
char(continued) ASCII is used to represent the characters A to Z (both upper and lower case) the digits 0 to 9 special characters (e.g. @, <, etc) special control codes For example, the character 'A' is represented by the code 65 the character '1' is represented by the code 49 IMPORTANT: the integer 1, the character '1' and the ASCII code 1 represent three different things! Variable types
After a variable has been declared, its memory location contains randomly set bits. In other words, it does not contain valid data. The value stored in a variable must be initialized before we can use it in any computations. There are two ways to initialize a variable: by assigning a value using an assignment statement by reading its value from the keyboard Variable values
The basic syntax of an assignment statement is variable = value; Example Variable values assign the value on the right hand side to the variable on the left hand side int num_students; // declare num_students = 22; // initialize
Literals are fixed values written into a program. Example: char keypressed; keypressed = ‘y’; /* ‘y’ is a character literal */ Example: double pi; pi = 3.14; /* 3.14 is a floating-point literal. */ Example: int index; index = 17; /* 17 is an integer literal */ Literals
Example /* sample program that demonstrates variable declaration and initialization. */ #include <stdio.h> int main () { int num_students; num_students = 22; return 0; }
Example /* sample program that demonstrates variable declaration and initialization. */ #include <stdio.h> int main () { double rate, amount;/* declare two double variables */ amount = 12.50; rate = 0.05; return 0; }
Example /* sample program that demonstrates how to declare and initialize a variable at the same time */ #include <stdio.h> int main () { char grade = ‘A’; return 0; }
Example /* sample program that demonstrates how to declare and initialize a variable at the same time */ #include <stdio.h> int main () { char pass_grade = ‘A’, fail_grade = ‘F’; return 0; }
printf() will print formatted output to the screen. To print a message:printf("This is a message\n"); How do we print the value of a variable? Answer: Use special format specifiers depending on the type of the variable Printing Output:printf() this is a string literal
To print an integer: Specifier for “print an integer value” “and the value of that number is read from this variable” int degreesF = 68;printf("The temperature is %d degrees.", degreesF); Output: > The temperature is 68 degrees.
If more data Data are displayed according to their order Output: 1 plus 2 is equal to 3 int a = 1; int b = 2; int c = 3; printf(“%d plus %d is equal to %d", a, b, c);
Format specifiers: %cfor single characters %d for integers %f for float/double (fractions): 1234.56 %gfor float/double (scientific): 1.23456E+3 %sfor phrases or ‘strings’
Example : Statement Output printf("|%d|", 987); |987| printf("|%2d|", 987); |987| printf("|%8d|", 987); | 987| printf("|%-8d|", 987); |987 | printf("|%0.2f|", 9876.54); |9876.54| printf("|%4.2f|", 9876.54); |9876.54| printf("|%3.1f|", 9876.54); |9876.5| printf("|%10.3f|", 9876.54); | 9876.540|
Control Characters (Escape Sequences) They are not data, but “commands” to the output device ‘\n’ is not a data to be printed. Instead, it is a command that tells the monitor to move the cursor to the next line Output: Hello World! printf(“Hello \n World!");