CS1100 Computational Engineering

Slides:



Advertisements
Similar presentations
Lecture 9. Lecture 9: Outline Strings [Kochan, chap. 10] –Character Arrays/ Character Strings –Initializing Character Strings. The null string. –Escape.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Types and Variables. Computer Programming 2 C++ in one page!
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
Data types and variables
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
Chapter 2 Data Types, Declarations, and Displays
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations System-oriented Programming, B. Hirsbrunner,
String Escape Sequences
Objectives You should be able to describe: Data Types
Types, Operators and Expressions CSE 2031 Fall /5/2015 3:59 PM.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
A Variable is symbolic name that can be given different values. Variables are stored in particular places in the computer ‘s memory. When a variable is.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
C Tokens Identifiers Keywords Constants Operators Special symbols.
Constants in C A Presentation On Department of Computer & Information Technology, M.S.P.V.L. Polytechnic College, Pavoorchatram.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
CS115 FALL Senem KUMOVA-METİN1 The Fundamental Data Types CHAPTER 3.
C++ Basics Tutorial 5 Constants. Topics Covered Literal Constants Defined Constants Declared Constants.
Constants, Variables and Data types in C The C character Set A character denotes any alphabet, digit or special symbol used to represent information.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
0 Chap.2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations 2.5Arithmetic Operators 2.6Relational.
Types Chapter 2. C++ An Introduction to Computing, 3rd ed. 2 Objectives Observe types provided by C++ Literals of these types Explain syntax rules for.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 ENERGY 211 / CME 211 Lecture 3 September 26, 2008.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
C Formatted Input/Output
The Machine Model Memory
Chapter 4 C Program Control Part I
Chap. 2. Types, Operators, and Expressions
Tokens in C Keywords Identifiers Constants
Wel come.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
A First Book of ANSI C Fourth Edition
C Short Overview Lembit Jürimägi.
Module 2 Arrays and strings – example programs.
Introduction to C Programming
C++ Simple Data Types Simple types Integral Floating
Escape Sequences What if we wanted to print the quote character?
Introduction to C++ Programming
Types, Operators and Expressions
Basics of ‘C’.
A First Book of ANSI C Fourth Edition
Introduction to C Programming
Lectures on Numerical Methods
Program Breakdown, Variables, Types, Control Flow, and Input/Output
Basic Types Chapter 7 Copyright © 2008 W. W. Norton & Company.
Your questions from last session
elementary programming
2. Second Step for Learning C++ Programming • Data Type • Char • Float
ECE 103 Engineering Programming Chapter 8 Data Types and Constants
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Fundamental Programming
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
ECE 120 Midterm 1 HKN Review Session.
Presentation transcript:

CS1100 Computational Engineering Arrays N.S. Narayanaswamy.

A data structure containing items of same data type An Array A data structure containing items of same data type Declaration: array name, storage reservation int marks[7] = {22,15,75,56,10,33,45}; a contiguous group of memory locations named “marks” for holding 7 integer items elements/components - variables marks[0], marks[1], … , marks[6] marks[i], where i is a position/subscript (0i6) the value of marks[2] is 75 new values can be assigned to elements marks[3] = 36; 22 15 75 56 10 33 45 1 2 3 4 5 6

Example using Arrays Read ten numbers into an array and compute their average #include <stdio.h> main( ){ int numbers[10], sum = 0, i; float average; for ( i = 0; i < 10; i++) scanf(“%d”, &numbers[i]); sum = sum + numbers[i]; average = (float) sum/10; printf(“The average of numbers is: %f”, average); return 0; /* should be there in all programs */ }

An array of ten integers Counting Digits in Text (Kenighan & Ritchie, pp. 59) #include<stdio.h> main( ){ int c, i, nWhite, nOther, nDigit[10]; nWhite = nOther = 0; for(i=0;i<10;i++) nDigit[i]=0; while((c = getchar( ))! = EOF){ switch(c){ case’0’:case’1’:case’2’:case’3’:case’4’:case’5’: case’6’:case’7’:case’8’:case’9’: nDigit[c-’0’]++; break; An array of ten integers 4

… Counting digits case’ ’: case’\n’: case’\t’: nWhite++; break; default : nOther++; break; } printf(“Digits: \n”) for(i=0;i<10;i++) printf(“%d occurred %d times \n”, i, nDigit[i]); printf(“White spaces: %d, other: %d\n”, nWhite, nOther); 5

Polynomial Evaluation Evaluate p(x) = anxn + an-1xn-1 + an-2xn-2 + … a1x + a0 at a given x value. Computing each term and summing up n + (n-1) + (n-2) + … + 1 + 0 = n(n+1)/2 multiplications and n additions Improved Method: p(x) = a0 + x(a1 + x(a2 + x(a3 + …+ x(an-2 + x(an-1 + xan))…))) for instance, p(x) = 10x3 + 4x2 + 5x + 2 = 2 + x(5 + x(4 + 10x)) n multiplications and n additions – will run faster!

… Polynomial Evaluation #include <stdio.h> main( ){ int coeff[20], n, x, value, i; /*max. no. of coeff ’s is 20*/ scanf(“%d%d”, &n, &x); /*read degree and evaluation point*/ for(i = 0; i <= n; i++) scanf(“%d”, &coeff[i]); /* read in the coefficients */ /* a0, a1, … , an */ value = coeff[n]; /* an */ for(i = (n-1); i >= 0; i--) /* evaluate p(x) */ value = x*value + coeff[i]; printf(“The value of p(x) at x = %d is %d\n”, x, value); }

Sort an array of numbers into ascending order. More Exercises Sort an array of numbers into ascending order. Write the output into another array Assuming that arrays are expensive, use only one array: read in the values into an array, sort in place, and print out the array. Matrix Sorting – The input is a matrix. Identify a sequence of column interchanges such that in the resulting matrix the rows are all sorted in ascending order. Can every matrix be sorted? 8

Data, Types, Sizes, Values int, char, float, double char – one byte, capable of holding one character int – an integer, different kinds exist! Integer Qualifiers – short and long short int – 16 bits, long int – 32 bits (Typical) Size is compiler dependant based on the underlying hardware int is at least 16 bits, short is at least 16 bits, long is at least 32 bits int is no larger than long and at least as long as short 9

The Char, Signed and Unsigned Types Qualifier signed or unsigned can be applied to int or char Unsigned numbers are non-negative Signed char holds numbers between –128 and 127 Whether char is signed or unsigned depends on the system. Find out on your system. Print integers between 0 to 255 as characters, (and also integers between –128 to 127) on your system. 10

Number Systems Decimal (base 10 – uses 10 symbols {0..9}) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 … Unary (base 1) 0, 00, 000, 0000, 00000 … Binary (base 2) – uses 2 symbols {0,1}) 0, 1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010 … Octal (base 8 – start with a 0 in C) 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13… 00, 01, 02, 03, 04, 05, 06 … C treats them as octal Hexadecimal (base 16 – start with 0x) 0, 1, …, 9, A, B, C, D, E, F, 10, 11, … 19, 1A, 1B, …

Binary, Octal and Hexadecimal The internal representation of binary, octal, and hexadecimal numbers is similar Octal - 2 7 3 2 5 6 0 6 Binary - 010111011010101110000110 5 13 10 11 8 6 Hexadecimal - 5 D A B 8 6

A Funny Infinite Loop - Arithmetic This program of mine, ran into an infinite loop. I only wanted to find which numbers corresponded to which characters, the significance of signed and unsigned characters, basically relationship between which integers can be printed as characters we recognize. Why did the infinite loop happen, how to avoid it? #include<stdio.h> main( ){ char c; for(c=-128; c <= 127; c++) printf(“%d -- %c \n”, c, c); } Print it as a character Print it as a decimal number Try omitting one parameter… 13

Long double is used for extended-precision arithmetic Float and Double Two types, one for single-precision arithmetic, and the other for double precision arithmetic Long double is used for extended-precision arithmetic The size of floating pointing objects are implementation defined 14

Variable Initialization Variables may be initialized either at the time of declaration Example: #define MAXLINE 200 char esc = ‘\\’; int i = 0; int limit = MAXLINE + 1; float eps = 1.0e-5 Or they may be assigned values by assignment statements in the program Otherwise they contain some random values

Constant has a value that does not change 1234 is of type int Constants At run time, each variable holds a value, which changes from time to time Constant has a value that does not change 1234 is of type int 123456789L is a long constant 123456789ul is an unsigned long constant 123.4 is a floating point constant, so is 1e-2 which denotes .01. Their type is double. If suffixed by an f, or by l, the type is float or long double, respectively 16

Character constants can participate in arithmetic …are integers, written as one character within single quotes. Example – ‘a’, ‘x’, ‘1’, ‘2’ etc. Value of a character constant is the numeric value of the character in the machine’s character set. For example, ‘1’ has the value 49 in the ASCII character set Character constants can participate in arithmetic What does ‘1’+ ‘2’ hold? (not ‘3’!) Understand this distinction Character arithmetic is used mainly for comparisons 17

Non-printable characters Characters – escape sequences \a alert (bell) \\ backslash \b backspace \? question mark \f formfeed \’ single quote \n newline \” double quote \r carriage return \0oo octal number \t horizontal tab \xhh hexadecimal \v vertical tab Non-printable characters

Constants Expressions Expressions all of whose operands are constants These can be evaluated at compile time Examples: #define NUM_ROWS 100 #define NUM_COLS 100 #define NUM_ELTS NUM_ROWS*NUM_COLS #define is preprocessor directive (recall #include) 19

By default enum values begin with 0 Enumerated Constants By default enum values begin with 0 enum boolean {No, Yes}; defines two constants No = 0, and Yes = 1. enum months {jan = 1, feb, march, april, may, jun, jul, aug, sep, oct, nov, dec}; when a value is explicitly specified (jan=1) then it starts counting from there enum escapes {BELL = ‘\a’, BACKSPACE = ‘\b’, TAB = ‘\t’, NEWLINE =‘\n’}; more than one value can be specified

Better than #define, the constant values are generated for us enum and #define Better than #define, the constant values are generated for us Values from 0 onwards unless specified Not all values need to be specified If some values are not specified, they are obtained by increments from the last specified value Variables of enum type may be declared but the compilers need not check that what you store is a valid value for enumeration 21

Declaring Constants The qualifier const applied to a declaration specifies that the value will not be changed. Example: const int J = 25; /* J is a constant through out the program */ Response to modifying J depends on the system. Typically, a warning message is issued while compilation. Example: const char MESG[] = “how are you?”; The character array MESG is declared as a constant which will store “how are you?” 22

A string is written in double quotes “ ” – empty string Strings A string is a array of characters terminated by the null character, ‘\0’ A string is written in double quotes Example: “This is a string” “ ” – empty string Anything within single quotes gets a number associated with it ‘This is rejected by the C Compiler’ Exercise: understand the difference between ‘x’ and “x” 23

Functions to Handle Strings a non basic data type, a constructed data type we require functions to handle them Typical functions are: Length of a string; string comparison; string concatenation, etc. Standard functions are provided with string.h strlen( ); strcmp( ); strcpy( ); strncpy( ); strcat( ); strncat( ); 24

32-bit Numbers Internally: 4,294,967,296 (232) different permutations that 32 bits can represent Signed 32 bit integers vary from -2,147,483,648 to 2,147,483,647 -231 to 231-1 Unsigned 32 bit integers vary from 0 to 4,294,967,295 0 to 232-1

Overflow in Integers… #include <stdio.h> main( ) { int i = 2147483647; unsigned int j = 4294967295; printf("%d %d %d\n", i, i+1, i+2); printf("%u %u %u\n", j, j+1, j+2); } Here is the result for some system: 2147483647 -2147483648 -2147483647 4294967295 0 1 231 - 1 232 - 1

#include <stdio.h> main( ){ Printing Directives #include <stdio.h> main( ){ unsigned int un = 3000000000; /* system with 32-bit int */ printf("un = %u and not %d\n", un, un); return 0; } un = 3000000000 and not -1294967296 Both have the same internal representation Both have the same internal representation

Printing a short decimal as a normal int is okay Printing Directives #include <stdio.h> main( ){ short end = 200; /* and 16-bit short */ printf("end = %hd and %d\n", end, end); return 0; } end = 200 and 200 short decimal Printing a short decimal as a normal int is okay

#include <stdio.h> main( ){ long big = 65537; Printing Directives #include <stdio.h> main( ){ long big = 65537; printf("big = %ld and not %hd\n", big, big); return 0; } big = 65537 and not 1 When the value 65537 (216 + 1) is written in binary format as a 32-bit number, it looks like 00000000000000010000000000000001. Using the %hd specifier persuaded printf() to look at just the last 16 bits; therefore, it displayed the value as 1.

Assignment and Arithmetic Rules Basic data types, numbers, and characters can be assigned to their corresponding variables Example: char c = ‘a’; char no = ‘1’; int j = 25; Arrays can be initialised when declared: char mesg[] = “hello”; //is a valid declaration int numbers[5] = {0,1,2,3,4}; //is a valid declaration But an assignment to an array in the program is a syntax error 30

Relational operators (comparisons) Recap Variables Assignments Relational operators (comparisons) Selection and repetition constructs: control structures Data types and their limitations Arrays : arrayName[n], single dimensional array arrayName[m][n] – 2D array arrayName[i][j] gives the element in the i-th row and j-th column 31

Boolean AND ( && ) and Boolean OR ( || ) Logical Operators Recall relational operators {<=, <, >, >=} to compare values Boolean AND ( && ) and Boolean OR ( || ) Expressions involving these as operations take Boolean values, and their operands also take Boolean values Called truth values also E1&&E2 is true if and only if both E1 and E2 are true E1||E2 is true if and only if either E1 or E2 or both are Precedence of && is higher than ||, and both are lower than relational or equality operators 32

How to use these in a program They are used when composite conditions are to be tested in decision statements for(i=0;i < lim–1&&(c=getchar())!=‘\n’&&c!=EOF;i++) s[i] = c; The loop is executed as long as all the test conditions are true The loop is exited when any test condition becomes false For example when an <Enter> is read from keyboard 33

Increment operator: effect is to increment value of a variable Operators Increment operator: effect is to increment value of a variable x = j++ //x gets the value of j, and then j is incremented x = ++j //j is incremented first, then assigned to x Decrement operators – decrements values x = j-- //x gets the value of j, then j is decremented by 1 x = --j //j is first decremented, and then assigned to x Assignment operator short cut E1 op= E2 is equivalent to the assignment E1 = E1op E2 x -= 5; same as: x = x – 5; 34

Exercise Write a program which will exit when a certain number of occurrences of any keystroke is read. You need arrays Loops Loops with logical operations and so on. 35