1.67k likes | 1.68k Views
Chapter 2. C. Figure 2.1. C, C++, Java, Python. Figure 2.2. Program Execution. A program inputs information, processes it, and outputs the results Let us see how a C program inputs, processes, and outputs values. Compiler.
E N D
Figure 2.1 C, C++, Java, Python
Figure 2.2 Program Execution • A program inputs information, processes it, and outputs the results • Let us see how a C program inputs, processes, and outputs values
Compiler • A computer can directly execute statements in machine language only at Level ISA3. • So a Level HOL6 statement must first be translated to Level ISA3 before executing. • Function of a compiler: HOL6 ISA3 Some compilers translate from Level 6 to Level 5, which then requires another translation from Level 5 to Level 3.
C • first developed by Dennis Ritchie at Bell Labs in the early 1970s • O/S: • Unix was one of the first operating systems to be written in C. Microsoft Windows, Mac OS X, and GNU/Linux are also written in C. • HOLs: • Lots of other high-level languages like Perl, PHP, Python, R, Matlab, Mathematica, etc, are written in C. • Sun JVM is written in C , Oracle JVM written in C++
Two versions of main: #include <stdio.h> int main() { printf(“hello world\n"); return 0; } #include <stdio.h> int main(intargc, char *argv[]) { printf("hello world\n"); return 0; }
The C Compiler • Running a C program is a three-step process: • Write the program in C using a text editor. This version is called the source program. • Invoke the compiler to translate, or compile, the source program from C to machine language. The machine language version is called the object program. • Execute the object program. • Some systems allow you to specify the last two of these steps with a single command, usually called the run command.
Machine Independence • Level ISA3 languages are machine dependent. • If you write a program in a Level ISA3 language for execution on a Brand X computer, it cannot run on a Brand Y computer. • An important property of the languages at Level HOL6 is their machine independence. • If you write a program in a Level HOL6 language for execution on a Brand X computer, it will run with only slight modification on a Brand Y computer.
Figure 2.3 How C achieves its machine independence
How C achieves its machine independence • You write an applications program in C to do some statistical analysis. You want to sell it to people who own Brand X computers and to others who own Brand Y. • The statistics program can be executed only if it is in machine language. • Because machine language is machine dependent, you will need two machine-language versions, one for Brand X and one for Brand Y.
Because C is a common high-order language, you will probably have access to a C compiler for the Brand X machine and a C compiler for the Brand Y machine. • If so, you can simply invoke the Brand X C compiler on one machine to produce the Brand X machine-language version, and invoke the Brand Y C compiler on the other machine for the Brand Y version. • You need to write only one C program.
Basic Structure of a C Program // include any libraries int main() { //your statements here return 0; }
Basic C data types Example #include <stdio.h> int main() { printf("sizeof(char) == %d\n", sizeof(char)); printf("sizeof(short) == %d\n", sizeof(short)); printf("sizeof(int) == %d\n", sizeof(int)); printf("sizeof(long) == %d\n", sizeof(long)); printf("sizeof(float) == %d\n", sizeof(float)); printf("sizeof(double) == %d\n", sizeof(double)); printf("sizeof(long double) == %d\n", sizeof(long double)); printf("sizeof(long long) == %d\n", sizeof(long long)); return 0; } Ex1.c
Steps to run your program • Step1: write your program using a text editor: • E.g. gedit, nano • Step2: save your program • ex1.c • Step3: compile your program • Run following command in terminal in the same directory you have the ex1.c file: • gcc –o ex1 ex1.c • This generates an executable file ex1 • Step4: run your program • ./ex1
printf #include <stdio.h> int main() { char ch = 'A'; //character char str[20] = "fresh2refresh.com"; //string: an array of characters float flt = 10.234; // float int no = 150; //int double dbl = 20.123456; //double printf("Character is %c \n", ch); printf("String is %s \n" , str); printf("Float value is %f \n", flt); printf("Integer value is %d\n" , no); printf("Double value is %lf \n", dbl); printf("Octal value is %o \n", no); printf("Hexadecimal value is %x \n", no); return 0; } ex2.c output
scanf ex3.c #include <stdio.h> int main() { char ch; //character char str[100];//string of maximum 100 characters printf("Enter any character \n"); scanf("%c", &ch); //initialize ch with user input printf("Entered character is %c \n", ch); printf("Enter any string ( upto 100 character ) \n"); scanf("%s", &str); //initialize str with user input printf("Entered string is %s \n", str); } output
Figure 2.4 #include <stdio.h> int main() { char ch; int j; scanf("%c %d", &ch, &j); j += 5; ch++; printf("%c\n%d\n", ch, j); return 0; } Input M 419 Output N 424 ex4.c
The C memory model • The C programming language has three different kinds of variables: • Global variables • Local variables and parameters • Dynamically allocated variables
Global variables: • stored at a fixed location in memory • declared outside of any function • remain in place throughout the execution of the entire program.
Local variables: • store in run-time stack • are declared within a function. • come into existence when the function is called • cease to exist when the function terminates.
Dynamically allocated variables: • stored in heap • come into existence with the execution of the malloc() function • cease to exist with the execution of the free() function.
Figure 2.4 // Stan Warford // A nonsense program to illustrate global variables. #include <stdio.h> char ch; int j; int main() { scanf("%c %d", &ch, &j); j += 5; ch++; printf("%c\n%d\n", ch, j); return 0; } Input M 419 Output N 424 ex4.c
Figure 2.4 // Stan Warford // A nonsense program to illustrate global variables. #include <stdio.h> char ch; int j; int main() { scanf("%c %d", &ch, &j); j += 5; ch++; printf("%c\n%d\n", ch, j); return 0; } Input M 419 Output N 424 Import standard input/output library functions e.g. scanf, printf Global variables (declared outside of any function) User input values for ch and j main function Output updated values for ch and j Return 0: indicate no errors occured &- address operator
area.c • Write a program to find area and circumference of a circle. The radius should come as user input. Declare all the variables you need as local variables. • Sample output: Enter radius of the circle. 3 area of the circle = 28.26 circumference of the circle = 18.84
Answer area.c #include <stdio.h> int main() { int r; float pi=3.14, area, cir; printf("Enter radius of the circle. "); scanf("%d", &r); cir = 2*pi*r; area = pi*r*r; printf("area of the circle = %.2f\n", area); printf("circumference of the circle = %.2f\n", cir); return 0; } Q0.c
Question – degrees.c • Write a program that converts 27° from degrees Fahrenheit (F) to degrees Celsius (C) using the following formula, and write the result to the screen • Sample output: [rdissanayaka@nx 238 ~/CS310/ch02]$ gcc -o degrees degrees.c [rdissanayaka@nx 239 ~/CS310/ch02]$ ./degrees 27.00 deg Fahrenheit = -2.78 deg Celsius [rdissanayaka@nx 240 ~/CS310/ch02]$
Answer #include <stdio.h> int main() { float degF = 27.0; float degC; degC = (degF - 32.0) / 1.8; printf("%.2f deg Fahrenheit = %.2f deg Celsius\n", degF, degC); return 0; } degrees.c
Question quadratic.c • Write a program that computes the (two) roots of the quadratic equation: where a=1.2 a=1.2, b=2.3b=2.3 and c=-3.4c=-3.4. • You can hard-code values of a, b and c and then compute and print the two solutions for x, to 5 decimal places. • Hint: use sqrt function in math.h • Sample output: [rdissanayaka@nx 234 ~/CS310/ch02]$ gcc -lm -o quadratic quadratic.c [rdissanayaka@nx 235 ~/CS310/ch02]$ ./quadratic 1.20 x^2 + 2.30 x + -3.40 = 0 x = 0.97861 and -2.89527 [rdissanayaka@nx 236 ~/CS310/ch02]$
Answer #include <stdio.h> #include <math.h> int main() { double a, b, c, x1, x2; a = 1.2; b = 2.3; c = -3.4; x1 = (-b + sqrt((b*b) - (4*a*c))) / (2*a); x2 = (-b - sqrt((b*b) - (4*a*c))) / (2*a); printf("%.2f x^2 + %.2f x + %.2f = 0\n", a, b, c); printf("x = %.5f and %.5f\n", x1, x2); return 0; } quadratic.c
Local variables: • store in run-time stack • are declared within a function. • come into existence when the function is called • cease to exist when the function terminates.
Figure 2.4 #include <stdio.h> int main() { char ch; int j; scanf("%c %d", &ch, &j); j += 5; ch++; printf("%c\n%d\n", ch, j); return 0; } Input M 419 Output N 424 ex4.c
The push and pop operations • Stack : • A special region of your computer's memory that stores temporary variables created by each function (including the main() function) • LIFO: last in, first out • stores values with the push operation • Every time a function declares a new variable, it is "pushed" onto the stack. • retrieves them with the pop operation. • Every time a function exits, all of the variables pushed onto the stack by that function, are deleted/popped.
Function Call • When a function executes, allocation on the run-time stack takes place in the following order: • Push storage for the return value • Push the actual parameters • Push the return address • Push storage for the local variables
Function return • Then, when the function terminates, deallocation from the run-time stack takes place in the opposite order: • Pop the local variables • Pop the return address • Pop the parameters • Pop the return value
Figure 2.4 #include <stdio.h> char ch; int j; int main() { scanf("%c %d", &ch, &j); j += 5; ch++; printf("%c\n%d\n", ch, j); return 0; } Input M 419 Output N 424 Ex4_2.c
Figure 2.5 • When a function is called, four items are allocated on the run-time stack: • return value, parameters, return address, local variables. • Because the main function in this program has no parameters and no local variables, the only items allocated on the stack are : • the return address, labeled retAddr,. • storage for the return value, labeled retVal, Global variables stored in a fixed location in memory
Figure 2.6 #include <stdio.h> int main() { const int bonus = 10; /* an integer constant with value 5*/ int exam1; /* three int local variables*/ int exam2; int score; scanf("%d %d", &exam1, &exam2); /* read two exam scores from user*/ score = (exam1 + exam2) / 2 + bonus; /* compute final score*/ printf("score = %d\n", score); /* print final score*/ return 0; } Input 68 84 Output score = 86 ex5.c
Figure 2.8 Memory model for the local variables in the program 0 0 Because bonus is not a variable, it is not pushed onto the stack.
Figure 2.9 Flow of Control • Sequence • Execute statements one after the other • Selection • C: if, switch • Repetition • C: while, do, for performs a test to possibly alter the sequential flow of control
Figure 2.10 if-else #include <stdio.h> int main() { const int limit = 100; int num; scanf("%d", &num); if (num >= limit) { printf("high\n"); } else { printf("low\n"); } return 0; } Input 75 Output low ex6.c