Computer Science II CS132/601* Lecture #C-1.

Slides:



Advertisements
Similar presentations
Chapter 3 Top-Down Design with Functions Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National.
Advertisements

Representation of Data Types Comparing double and int data types Using integers are faster and more precise round-off errors when using doubles The range.
1 ICS103 Programming in C Lecture 5: Introduction to Functions.
11-2 Identify the parts of the “main” function, which include Preprocessor Directives main function header main function body which includes Declaration.
Lecture 2 Introduction to C Programming
TDBA66, VT-03 Lecture - Ch. 21 A complete C-program Display Fig. 2.1 and comment on different things such as Preprocessor directives Header files Identifiers.
1 CS 201 Introduction to C (1) Debzani Deb. 2 Outline Overview of C General form of a C program C Language Elements.
Software Development Method & C Language Elements H&K Chapter 1-2
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
Software Development Method. Assignments Due – Homework 0, Warmup Reading – Chapter 2 –
CS 201 Functions Debzani Deb.
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
The scanf Function The scanf function reads input from the standard input device into one or more variables Example: scanf(“%lf”, &miles); Reads a real.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
CS 201 Functions Debzani Deb.
1 CS 201 Introduction to C (2) Debzani Deb. 2 Overview C Arithmetic Expressions Formatting Numbers in Program Output Interactive Mode, Batch Mode, and.
1 ICS103 Programming in C Lecture 2: Introduction to C (1)
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
Basic Input/Output and Variables Ethan Cerami New York
Basic Elements of C++ Chapter 2.
By Dr. Awad Khalil Computer Science & Engineering Department
Chapter 2 Overview of C Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
Chapter 2 : Overview of C By Suraya Alias. /*The classic HelloWorld */ #include int main(void) { printf(“Hello World!!"); return 0; }
Chapter 2 Overview of C++ Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2: Overview of C++ Problem Solving, Abstraction, and Design using.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CPCS 202 Chapter 2 – Input/Output
Chapter 2 Overview of C Part I J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Chapter 2 Overview of C Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Pengantar C/C++. 2 Outline  C overview  C language elements  Variable declarations and data types  Executable statements  General form of a C program.
C++ Programming: Basic Elements of C++.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
ELE118 Introduction to Programming
Overview of C. C—a high-level programming language developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories. We will discuss: –the elements of a.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
1 ELE118 lecture 3 Dr. Mehmet Demirer Dr. Seniha Esen Yuksel.
CISC105 – General Computer Science Class 2 – 6/7/2006.
A.Abhari CPS1251 Topic 2: C Overview C Language Elements Variable Declaration and Data Types Statement Execution C Program Layout Formatting Output Interactive.
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
C Language Elements Preprocessor Directives # (sign for preprocessor directive commands) #include Standard header file (.h) Library.
SCP1103 Basic C Programming SEM1 2010/2011 Arithmetic Expressions Week 5.
Lecture2.
Arithmetic Expressions
CSCE 206 Structured Programming in C
Chapter Topics The Basics of a C++ Program Data Types
CS1001 Programing Fundamental Lecture 5 Top-Down Design with Functions
Computer Science 210 Computer Organization
ICS103 Programming in C Lecture 4: Data Types, Operators & Expressions
Basic Elements of C++.
What's a Computer? Monitor Disk Main mouse Memory Keyboard Network
Revision Lecture
ICS103 Programming in C Lecture 3: Introduction to C (2)
Lecture2.
Java Programming: From Problem Analysis to Program Design, 4e
Basic Elements of C++ Chapter 2.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
Computer Science 210 Computer Organization
Compiled and ready to run Memory Stack /*
CC213 Programming Applications
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
A First Book of ANSI C Fourth Edition
Lec8.
Overview of Computers and C Programming
Chapter 2 - Introduction to C Programming
Lecture3.
Chapter 2 - Introduction to C Programming
Chapter 2: Overview of C++
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
Presentation transcript:

Computer Science II CS132/601* Lecture #C-1

C language elements Preprocessor Directives Function main() Begin and end point of a program

Preprocessor Directives #include include the libraries #define define constant macro Comments make the program easy to understand

#include directive Syntax: #include <standard header file> Example: #include <stdio.h> #include <math.h> Interpretation: tell the preprocessor where to find the meaning of standard identifiers used in the program.

#define directive Syntax: #define NAME value Examples: #define PI 3.14159 #define MAX_LENGTH 100 Interpretation: the C preprocessor is notified that it is to replace each use of the identifier NAME with value.

Comments Comments provide supplementary information making it easier to understand the program, but comments are ignored by the C preprocessor and complier.

Function main Marks the beginning of the main function where program execution begins. Syntax: int main(void) { function body }

Declaration It is a part of a program tells the complier the memory cells of the data will be used in a program This can be generated according to the data requirements identified during the problem solving Examples: double kms, miles;

Executable statements The main part of a program, derived from the algorithm, it is the real problem solving procedure. These program lines will be converted to machine language instructions and executed by the computer. Punctuations and special symbols are used. (, ; { } * + = etc)

Identifiers Reserved words Standard identifiers Reserved, can not be used for other purpose Examples: int, double, break, return, void … Standard identifiers Reserved, not recommended for other purpose Examples: printf, scanf User-defined identifiers

User-defined identifiers Chosen by ourselves to name memory cells that will hold data, operations and program results Syntax: Only letters, digits and underscores Can not begin with a digit Reserved words can not be used Better not using standard identifiers Valid for first 31 characters (already extended in most C implementation)

Examples Reserved Words Standard Identifiers User-defined int, void, double, return printf, scanf KMS_PER_MILE, main, miles, kms

Variables Variable: a name associate with a memory cell whose value can change Variable declaration: a statement that communicate to the complier the names of variables in the program and the kind of information stored in each variable.

Declaration Syntax: int variable_list_1; double variable_list_2; Examples: double miles; /* input: the distance in miles */ Interpretation: a memory cell is associated for each name in the variable list.

Data types A set of values and operations can be performed on those values. E.g. int, double, char Objects of a data type can be variables or constants. int type Originally, ANSI C: -32767 32767 Now: -2147483647 2147483647 E.g. -10500, 435, +15

Data types (Cont.) double type: a real number has an integral part and a fractional part that are separated by a decimal point. We can also use C scientific notation such as 1.23e5. E.g. 3.14159, 1032.0043, 0.34e-4, 1.23e5

Data type (Cont.) Type char: represents an individual character value, a letter, a digit or a special symbol Examples: ‘A’, ‘z’, ‘3’, ‘=‘, ‘:’, ‘”’, ‘ ‘

Executable statements Program in memory memory memory Machine language Miles-to-kms Conversion program Machine language Miles-to-kms Conversion program miles kms miles kms ? ? 10.00 16.09 a) before b) after

Input/output operations All input/output operations in C are performed by special program units called input/output functions. The most common functions are supplied as C standard library. They can be accessed through stdio.h by using a function call.

Function formats Function name Function argument printf(“That equals %f kilometers. \n”, kms) Print list Format string

Placeholder A placeholder always begins with the symbol %. Placeholder Variable type Function use %c %d %f %lf char int double printf/scanf printf scanf

Newline escape sequence “\n” Display prompts: printf(“Enter the distance in miles> “); scanf(%lf”,&miles);

Input The data transfer from the outside world into memory is called an input operation Two ways: Assignment to a variable Copying the data from an input device into a variable

scanf function Syntax: scanf(format string, input list); Example: scanf(“%lf”, &miles); scanf(“%c%c%c”,&char1,&char2,&char3); & is address-of, in this context, the & tells scanf the memory address of each variable Copies the data typed at the keyboard by the user during program execution into memory.

output After a program finishes execution, the program results will be displayed to the users by an output operation.

printf function Syntax: printf(format string, print list); Examples: printf(“hello world!”); Interpretation: Display the value of its format string after substituting in left-to-right order the values of the expressions in the print list for their placeholders in the format string and after replacing escape sequences such as \n.

return statement Syntax: return expression; Example: return (0); The last list in the main function. Transfer control from your program to the operating system.

General Form of C Program preprocessor directives main function heading { declarations executable statements }

C Programming in linux complier and linker for C programs. ssh connect to a linux machine e.g. ssh inceptor.mcs.suffolk.edu Vi, pico edit the source file e.g. vi hello.c pico hello.c gcc complier and linker for C programs. e.g. gcc hello.c or gcc hello.c -o hello run the program

Data type of expressions Depends on the type(s) of its operands. For int and double type data If both are int, the expression is int as well If contains both int and double (a mixed-type expression), the type is double The expression is evaluated before the assignment is made.

Examples int m, n; double x, y, p; If m=3, n=2, p=2.0,x=m/p, y=m/n Then we get x=1.5, y=1.0 x=9*0.5 if x is int, x=4 if x is double, x=4.5

Type conversion This can be done by placing the desired type in parentheses before the expression (type cast). Example average=(double)(total_score/num);

Multiple operators Unary operators: only take one operand. Examples: x = -y p = + x Binary operators: Multiple operators: Example: x / y * z + a / b

Rules for evaluating expressions Parentheses rule: All expressions in parentheses must be evaluated separately. Nested parenthesized expressions must be evaluated from the inside out, with the innermost expressions evaluated first.

Rules for evaluating expressions (Cont.) Operator precedence rule: operators in the same expression are evaluated in the following order: Unary +, - first x = -y; p = +x * y; *, /, % next Binary +, - last

Rules for evaluating expressions (Cont.) Associativity rule: Unary operators in the same subexpression and at the same precedence level (such as + and -) are evaluated right to left (right associativity). Binary operators in the same subexpression and at the precedence level (such as + and -) are evaluated left to right (left associativity).

Example x * y * z + a / b – c * d can be represented by: area = PI * radius * radius v = ( p2 – p1 ) / ( t2 – t1 ) z – ( a + b / 2) + w * -y

Mathematical Formulas

Case Study Evaluating a collection of coins Problem: Your local bank branch has many customers who save their change and periodically bring it in for deposit. Write a program to interact with the bank’s customers and determine the value of a collection of coins

Data requirements Problem Input: char first, middle, last int quarters int dimes int nickels int pennies Problem output: int dollars int change Additional value: int total_cents Formulas: 1 quarter= 25c; 1 dime=10c; 1 nickel= 5c, 1 penny= 1c

Design Get and display the customer’s initials Get the count of each kind of coins Compute the total value in cents Find the value in dollars and change Display the value in dollars and change

#include <stdio.h> int main(void) { char first, middle, last; /* input - 3 initials */ int pennies, nickels; /* input - count of each coin type */ int dimes, quarters; /* input - count of each coin type */ int change; /* output - change amount */ int dollars; /* output - dollar amount */ int total_cents; /* total cents */ /* Get and display the customer's initials. */ printf("Type in 3 initials and press return> "); scanf("%c%c%c", &first, &middle, &last); printf("Hello %c%c%c, let's see what your coins are worth.\n", first, middle, last); /* Get the count of each kind of coin. */ printf("Number of quarters> "); scanf("%d", &quarters); printf("Number of dimes > "); scanf("%d", &dimes); printf("Number of nickels > "); scanf("%d", &nickels); printf("Number of pennies > "); scanf("%d", &pennies); /* Compute the total value in cents. */ total_cents = 25 * quarters + 10 * dimes + 5 * nickels + pennies; /* Find the value in dollars and change. */ dollars = total_cents / 100; change = total_cents % 100; /* Display the value in dollars and change. */ printf("\nYour coins are worth %d dollars and %d cents.\n", dollars, change); return (0); }

Computer operation modes Interactive Mode user interact with the program and supply the data Batch Mode the program get the data from a file using redirection, e.g. metric <mydata

Output redirection metric >myoutput Input/output redirections metric <mydata >myoutput

Program-controlled input/output files File pointer: FILE *inp, *outp; fopen function inp=fopen(“distance.dat”, “r”); outp=fopen(“distance.out”, “w”); Access mode r, w, a fclose function fclose(inp); fclose(outp);

#include <stdio.h> #define KMS_PER_MILE 1.609 int main(void) { double miles, kms; FILE *inp, *outp; /* open the input and output files */ inp = fopen(“distance.dat”,”r”); outp = fopen(“distance.out”,”w”); /* Get the distance in miles */ fscanf(inp,“%lf”,&miles); fprintf(outp, “The distance in miles is %.2f. \n”, miles); /* Convert the distance to kilometers */ kms= KMS_PER_MILE * miles; /* Display the distance in kilometers */ fprintf(outp,“That equals %f kilometers.\n”, kms); fclose(inp); fclose(outp); return (0); }

Program errors Syntax errors Run-time errors Undetected errors Logic errors Debugging a program (error correcting process) is necessary

Library functions Code-reuse benefits: avoid redevelopment. avoid errors. C providing many predefined functions that can be used to perform certain tasks. For example, mathematic computations. sqrt(x)

Example Display the square root of two numbers provided as the input data (first and second) and the square root of their sum.

/* * Perform three square root computation */ #include <stdio.h> #include <math.h> int main(void) { double first, second, /* input – two data value */ double first_sqrt; /* output – square root of first */ double second_sqrt; /* output – square root of second */ double sum_sqrt; /* output – square root of sum */ /* Get first number and display its square root */ printf(“Enter the first number> “); scanf(“lf”, &first); first_sqrt = sqrt(first); printf(“The square root of the first number is %.2f\n”,first_sqrt); /* Get second number and display its square root */ scanf(“lf”, &second); second_sqrt = sqrt(second); printf(“The square root of the second number is %.2f\n”,first_sqrt); /* display the square root of the sum */ sum_sqrt = sqrt(first+second); printf(“The square root of the sum is %.2f\n”,sum_sqrt); return (0); }

Example Using pow and sqrt functions to compute the roots of equation: ax2 + bx + c = 0 disc= pow(b,2) – 4 * a * c root_1 = ( -b + sqrt(disc)) / (2 * a) root_2 = ( -b - sqrt(disc)) / (2 * a) a2 = b2 + c2 – 2bc cos α

Functions without arguments Function prototype: declare a function before use it, tells the C complier the data type of the function, the function name, and information about arguments The data type of a function is determined by the type of value returned by it. void function(void) example: void draw_circle(void)

Function definitions Define the function operations. Example: /* Draw a circle */ void draw_circle(void) { printf(“ * \n”); printf(“ * * \n”); printf(“ * * \n”); }

Function syntax ftype fname(void) { local declarations executable statements }

/* * Draw a triangle */ void draw_triangle(void) { draw_intersect(); draw_base(); }

Placement of functions /* draw a stick figure */ #include <stdio.h> /* function prototypes */ void draw_circle(void) // draw a circle void draw_intersect(void) // draw a intersect void draw_base(void) // draw a base void draw_triangle(void) // draw a triangle int main(void) { /* draw a circle */ draw_circle(); /* draw a triangle */ draw_triangle(); /* draw intersecting lines */ draw_intersect(); return(0); } /* Draw a circle */ void draw_circle(void) printf(“ * \n”); printf(“ * * \n”); printf(“ * * \n”);

Order of execution of functions