Reading Assignment. Main Program in C. K.N. King Chapter 2. K.N. King Chapter 3. K.N. King Chapter 4. K.N. King Chapter 7. Our first C program

Similar documents
The programming language C. sws1 1

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Sources: On the Web: Slides will be available on:

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

arrays C Programming Language - Arrays

Pemrograman Dasar. Basic Elements Of Java

So far we have considered only numeric processing, i.e. processing of numeric data represented

Informatica e Sistemi in Tempo Reale

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

FEEG Applied Programming 5 - Tutorial Session

Bachelors of Computer Application Programming Principle & Algorithm (BCA-S102T)

How To Port A Program To Dynamic C (C) (C-Based) (Program) (For A Non Portable Program) (Un Portable) (Permanent) (Non Portable) C-Based (Programs) (Powerpoint)

C / C++ and Unix Programming. Materials adapted from Dan Hood and Dianna Xu

C++ Language Tutorial

The C Programming Language

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Secrets of printf. 1 Background. 2 Simple Printing. Professor Don Colton. Brigham Young University Hawaii. 2.1 Naturally Special Characters

5 Arrays and Pointers

Moving from CS 61A Scheme to CS 61B Java

CSI 333 Lecture 1 Number Systems

Programming Microcontrollers in C

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

ASSEMBLY LANGUAGE PROGRAMMING (6800) (R. Horvath, Introduction to Microprocessors, Chapter 6)

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Outline. hardware components programming environments. installing Python executing Python code. decimal and binary notations running Sage

C Programming. for Embedded Microcontrollers. Warwick A. Smith. Postbus 11. Elektor International Media BV. 6114ZG Susteren The Netherlands

CP Lab 2: Writing programs for simple arithmetic problems

Molecular Dynamics Simulations with Applications in Soft Matter Handout 7 Memory Diagram of a Struct

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

MATLAB Programming. Problem 1: Sequential

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

1 Abstract Data Types Information Hiding

An Incomplete C++ Primer. University of Wyoming MA 5310

C LANGUAGE TUTORIAL. Version Sept 8, 1996

CS 106 Introduction to Computer Science I

7th Marathon of Parallel Programming WSCAD-SSC/SBAC-PAD-2012

C++ INTERVIEW QUESTIONS

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

Chapter 3. Input and output. 3.1 The System class

Object Oriented Software Design

Useful Number Systems

Discrete Mathematics and Probability Theory Fall 2009 Satish Rao, David Tse Note 2

1. Give the 16 bit signed (twos complement) representation of the following decimal numbers, and convert to hexadecimal:

Chapter 13 - The Preprocessor

Object Oriented Software Design

As previously noted, a byte can contain a numeric value in the range Computers don't understand Latin, Cyrillic, Hindi, Arabic character sets!

C Language Tutorial. Version March, 1999

How To Write Portable Programs In C

Computer Programming Tutorial

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

PL / SQL Basics. Chapter 3

Oct: 50 8 = 6 (r = 2) 6 8 = 0 (r = 6) Writing the remainders in reverse order we get: (50) 10 = (62) 8

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Tutorial on C Language Programming

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

The C Programming Language course syllabus associate level

This is great when speed is important and relatively few words are necessary, but Max would be a terrible language for writing a text editor.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

13 Classes & Objects with Constructors/Destructors

How To Write A Programming Program

Programming in C. If you are interested in systems programming especially in the Unix context there are further notes on a wide range of topics.

23. RATIONAL EXPONENTS

sqlite driver manual

CS106A, Stanford Handout #38. Strings and Chars

Introduction to Python

Base Conversion written by Cathy Saxton

Python Lists and Loops

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Module 816. File Management in C. M. Campbell 1993 Deakin University

Fundamentals of Programming

Python Programming: An Introduction To Computer Science

University of Toronto Department of Electrical and Computer Engineering. Midterm Examination. CSC467 Compilers and Interpreters Fall Semester, 2005

1 Description of The Simpletron

Java Interview Questions and Answers

Top 10 Bug-Killing Coding Standard Rules

Number Representation

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

Chapter 4: Computer Codes

Beyond the Mouse A Short Course on Programming

CS 241 Data Organization Coding Standards

Example of a Java program

Vieta s Formulas and the Identity Theorem

Part 1 Foundations of object orientation

=

Microcontroller Systems. ELET 3232 Topic 8: Slot Machine Example

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Numerical integration of a function known only through data points

csce4313 Programming Languages Scanner (pass/fail)

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Chapter 5 Names, Bindings, Type Checking, and Scopes

C++ Essentials. Sharam Hekmat PragSoft Corporation

Chapter 13 Storage classes

Transcription:

Reading Assignment Main Program in C In C the main program is a function called main The body of the function is enclosed in left ( ) and right ( ) curly braces. K.N. King Chapter 2 K.N. King Chapter 3 K.N. King Chapter 4 K.N. King Chapter 7 In Standard C, the return type of main must be int. If we do not specify the return type, it defaults to int. We might also be able to get away without having a return statement. Good Style: Specify int as the return type for main and always have an explicit return statement! There are 3 steps to get a C program from text to executable code: preprocessing, compiling and linking If you want to give it a try before the first tutorial, use the following command: gcc first.c -o first 50 51 Our first C program /******************************************* Name: first.c Purpose: Prints a traditional C greeting. Author: Iqbal Mohomed Date: September 10 th 2002 *******************************************/ #include <stdio.h> int main() { /* Print Greeting */ printf("hello World\n"); return 0; } C Programming Language Very widely used general purpose programming language Available on many machines and operating systems Designed to be flexible, powerful, and unconstraining Originally a replacement for assembly language C requires extreme care in programming C requires really extreme care in programming Traditional C and ANSI C C++ is a superset of C with Object Oriented features 52 53

BE REALLY REALLY CAREFUL IN C C provides NO run-time checking e.g. array subscripts, undefined variables Programmer must manage dynamic storage allocation Pointers are widely used but are unchecked Program with extreme care Program with extreme care There are good software tools for developing C programs debuggers, program checking aids large libraries of existing software Good Style:, Good Technique: and WARNING: Good Style: indicates a preferred way of programming in C. Programs with Good Style: are easier to read, understand, modify and get correct. Markers just love programs that exhibit Good Style:. Good Technique: indicates a good way to do some particular programming task in C. The technique is good because its efficient, easy to understand, easy to get correct. An entire slide of Good Technique: usually has HOW TO in the title. WARNING: is used to indicate a particularly tricky or dangerous part of C. Good programmers avoid WARNING: constructs or are extremely careful about how they use them. 54 55 Identifiers (basic names) Identifiers start with a letter or ( underscore ) Identifiers contain letters, digits or Upper and lower case letters are distinct, e.g. A is not the same as a Examples: i, I, total, bignumber, DEBUG, testing 123 Words that have a special meaning in C (keywords, See King Table 2.1 ) are reserved and can not be used as identifiers. Examples: int, while, if Identifiers are used to name variables, constants, types and functions in C. Good Style: Use mnemonic identifiers!! Mnemonic means that the identifier describes its purpose in the program, e.g. use sum and index instead of Q and fabulous Mnemonic identifiers help you (and others) understand what the program is supposed to do. Basic Data Types Use keyword(s) constants integers unsigned, int, short, long -237, 0, 23, 101467 real numbers float, double -0.123, +417.6, 1234e+7, 0.23e-12 characters char a, A, 3, + Values of type char can be used in integer expressions. The character data type is for single characters. Character strings will be described later. Notation: the phrase type-name will be used to denote any valid type in C. int, double and char are instances of type-name. 56 57

8310 ) Integer Constants Type Digits Starts with Examples decimal integer 0123456789 1..9 1 123L 456790U octal integer 01234567 0 01 0123 0456707U hexadecimal integer 01234567899 abcdef ABCDEF 0x or 0X 0x14 0x123 0XDEADBEEF Add an upper case L after a constant to force it to be treated as a long number. Good Style: Don t use lowercase l (el), it looks like 1 (one). Add an upper case U after a constant to force it to be treated as an unsigned number. WARNING: numbers starting with 0 (zero) are octal constants. 123 and 0123 have different values. ( 0123 8 HOW TO Use Integer Types For almost all integer variables, use int Use short or char when saving space is really important AND IT S KNOWN that the range of values for the variable will fit in -32768.. 32767. Short or char integer variables may be slower to access. On a few machines long is 64 bits and provides a much larger range of values. Don t assume long is larger than int unless you check. Use unsigned for STRICTLY NON-NEGATIVE integer values. For maximum portability use: int or short int for integers in the range -32768.. 32767 long int for all other integers C standard only requires: sizeof( short ) int ) sizeof( sizeof( long ) 58 59 Character and String Constants Type Contains Starts and Examples ends with character a single character (single quote) a @ 1 C string arbitrary characters (double quote) abc CSC181F arbitrary The backslash ( \ ) notation can be used to create character or string constants containing arbitrary non-printable characters. See Escape Sequences in King Section 7.3. WARNING: be careful to use character constants where a single character is required and string constants where a string is required. Variables and Types Variables are the basic containers used to hold data in C. Every variable must be declared before it is used. Every variable is associated with a specific type. The type of a variable determines the kind of values that it can hold and the amount of storage that is allocated for the variable. scalar variables can hold exactly one variable at a time. Non-scalar variables (e.g. arrays) can hold many different values at the same time. 60 61

Declarations for Scalar Variables The declaration for a scalar variables has the form type-name identifierlist a ; Examples: int I, J, K ; char tempchar, nextchar ; A variable can be declared and initialized at the same time using identifier = expression Example: int xposition = 25, yposition = 30 ; WARNING: Each variable must be individually initialized. int M, N=0 ; /* only initializes N. */ Good Style: All variables should be initialized with some value before they are used in a program. BAD Style: do not depend on the system to automatically initialize variables for you. This is lazy and dangerous. Someday the variables will be initialized to RUBBISH and your program will CRASH. HOW TO Check for Uninitialized Variables In C a variable can receive a value in one of three ways a Explicit initialization in a declaration int X = 1; Assignment Statement Y=2; checked scanf function call assert ( scanf( %d, &Z ) == 1) ; For a program to be correct, every variable should receive a value BEFORE it is used. Variables are used when they occur in any form of expression. Examples T=X+3; if (Z)... a As a matter of Good Technique: we ignore the default initialization of all variables to zero that some C compilers do automatically. We think that relying on default initialization is a BAD HABIT that should be avoided. a identifierlist is a comma separated list of identifiers 62 63 To check for use of uninitialized variables, examine every place in a program that a variable is used. Do this systematically line by line, starting at the first line in the program. At EVERY place where a variable is used, complete the following statement For EVERY possible way of reaching this use of the variable, the variable MUST have a value BECAUSE. If you can not complete this statement, either You don t understand the program OR You have an uninitialized variable error at this point in the program. For a well structured program this statement should be really easy to complete for almost all uses of variables. Once a variable receives a value it is automatically not uninitialized. When completing the statement you must account for all possible ways that the use of the variable can be reached during program execution. You must also consider the possibility that a value might not be assigned to a variable due to conditional statements or an unchecked scanf. int X; int Y; int Z;......... if ( something ) for (... ; something ;... ) X=1; Y=2; scanf ( %d &Z ); If something is false then X and Y will not receive a value. The unchecked scanf statement may not assign a value to Z a. a This is why we suggest that every scanf statement must be checked to make sure it read values into the expected number of variables. 64 65

Example of Uninitialized Variable Checking main( ) /* Compute roots of equation ä x 2 b x c0 */ double a, b, c ; /* Coefficients */ double disc, discsq ; /* Discriminant */ double x1, x2 ; /* roots */ assert( scanf( %lg %lg %lg, &a, &b, &c ) == 3 ); printf( Coefficients are %g, %g, %g\n, a, b, c ); if ( a == 0.0 ) if ( b == 0.0 ) printf( Equation has no roots \n ); else printf( One real root: %g\n, - c / b ); else discsq = b * b -4.0* a * c ; if ( discsq >= 0.0 ) disc = sqrt( discq ); x1 = ( - b + disc )/2.0* a ; x2 = ( - b - disc )/2.0* a ; printf( Two real roots: %g and %g \n, x1, x2 ); else x1 = - b /(2.0* a ); x2 = sqrt( - discsq )/(2.0* a ); printf( Two complex roots: %g+%gi and %g-%gi \n, x1, x2, x1, x2 ); Named Constants A named constant is an identifier that serves as a synonym (name) for a constant value. Named constants are often used to provide a single point of definition for a constant value that is used throughout a program. Using named constant makes programs more easily modifiable and easier to understand. Named constants makes program more readable, use mnemonic name for constant. Named constants makes program correctness easier to achieve. Good Style: Avoid Magic Numbers Use named constants for all values that have any significant impact on the program s operation. 66 67 Defining Named Constants Use the #define construct to create named constants #define identifier expression The identifier becomes a synonym for the expression in the rest of the program. If the expression is a constant expression then the identifier can be used anywhere that a constant can be used Good Technique: ALWAYS enclose the expression in parentheses. Good Style: Use UPPER CASE names for defined constants to make them stand out in the program. Examples: #define CUBIC IN PER LB ( 166 ) #define SCALE FACTOR (5.0 / 9.0) #define ARRAY SIZE ( 100 ) WARNING: common errors #define N = 100 /* WRONG, defines N to be = 100 */ #define N 100 ; /* WRONG, defines N to be 100 ; */ Named Types A named type is an type that has been associated with a specific identifier. Named types are created using the typedef declaration. Named types make program more easily modifiable, since there is a single point of definition for the type. If mnemonic names are used for the types, named types make programs more readable. Named types make it easier to write a correct program. Good Style: Avoid Magic Types Use named types for all types that have any significant impact on the program s operation. 68 69

Typedef Declaration A named type is created with the declaration typedef type-name identifier ; type-name can be any valid type including compound types or a new type definition. identifier becomes a new name for this type Good Style: Use typedefs for all complicated types. Examples: typedef long int portableint ; typedef float realtype ; portableint I, J, A[ 100 ] ; realtype xaxis, yaxis, zaxis ; Reading Data and Printing in C a Input and Output are not part of the C language. Builtin library functions are used for all reading and printing. Put the construct #include stdio.h at the start of every program to make the builtin input and output functions available. The printf function does simple printing The scanf function is used to read values into variables. a The description of printf and scanf below is intended to get you started. Reading and Printing will be discussed in more detail later in the course. 70 71 Format Strings A format string is used to specify how printf and scanf should operate. For printf the format string specifes exactly how the printed output should look. For scanf the format string specifes the exact form of the input that will be read. The format string consists of conversion specifications a percent sign ( % ) followed by some optional information, followed by a conversion specifier character that indicates the type of data to be printed or read. ordinary text Everything else. Printed as is by printf. Matched against the data being read by scanf a a This feature is rarely used Conversion Specifier Characters Conversion Type Specifier int %d or %i char %c Strings %s double %f or %e or %g printf double %lf or %le or %lg scanf float %f or %e or %g short %hd long %ld Note that printf and scanf use different specifiers for double. Use%%toprinta%.Use\n toprintanewline. 72 73

The printf Function printf ( format-string, expressionlist a ) ; The format-string controls how the information is printed. The expressions in the expressionlist are printed in the order given. The type of each expression must be compatible with the % item used in the format-string By default each expression is printed using the minimum number of characters required to express its value. All formatting and spacing must be provided by the programmer. Printing Technique In a format string a constant between the % and the following control character, specifies that the expression is to be printed using the number of characters specified by the constant. This feature can be used to print columns of values. Examples: %10d %16e The printf prints to standard output. If you are working at a terminal, this means printing to your screen. There are Unix/Windows commands that let you redirect standard out to a file. WARNING: make really sure that the type of the expression matches the type of % character that you use to print it. WARNING: make really sure that you have provided a % character for each a An expressionlist is a list of expressions separated by commas expression in the expression list. 74 75 The scanf Function Examples Printing the Value of a Scalar Variable Examples: int i, height, width ; char c ; float x ; double y ; printf("%d", i) ; printf("%c", c) ; printf("%f", x) ; /* decimal form */ printf("%e", x) ; /* scientific form */ printf("%g", y) ; /* decimal or scientific form */ int scanf ( format-string, variable-address-list a ) ; The format-string controls how the information is read Any ordinary text in the format string must match the input exactly. scanf attempts to read values for each of the variables in the order given. The type of each variable must be compatible with the % item used in the format-string scanf automatically skips white space between input values printf("height is %d and width is %d\n", height, width ) ; printf("i = %8d, x = %14f\n", i, x) ; printf("\n") ; /* blank line */ a A variable-address-list is a list of addresses of variables separated by commas 76 77

scanf returns the number of variables that it successfully read and stored. Returns special value EOF if an error or end of input was detected. Use the address-of operator & to create the addresses of variables for the arguments to scanf. The address-of operator is almost always REQUIRED. WARNING: forgetting the address of operator in a call to scanf will almost certainly cause your program to CRASH. Good Style: always check the value returned by scanf to make sure that you read as many variables as you expected to a. a We may sometimes not do this check in these slides in order to keep the examples simple, Examples: int i, k ; char c ; double y ; Examples - Reading Input scanf("%d", &i) ; /* read one integer */ scanf("%c", &c) ; /* read one character */ scanf("%lf", &y) ; /* read one double value */ scanf("%d%d", &i, &j ); /* read two integers */ but it should always be done 78 79