C, C++, Fortran: Basics

Similar documents
Scientific Computing

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Chapter 1 Introduction to Computers and C++ Programming

CS 376b Computer Vision

CE221 Programming in C++ Part 1 Introduction

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

Chapter 15 - C++ As A "Better C"

EC 413 Computer Organization

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

Introduction to C ++

CS2141 Software Development using C/C++ C++ Basics

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Introduction to C++ Systems Programming

CSE 333 Lecture 9 - intro to C++

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C An overview of the programming language C, syntax, data types and input/output

Program Organization and Comments

Exercise 1.1 Hello world

A SHORT COURSE ON C++

MA400: Financial Mathematics

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

CS31 Discussion 1E. Jie(Jay) Wang Week3 Oct.12

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

C programming basics T3-1 -

Your first C and C++ programs

Partha Sarathi Mandal

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

Introduction to C++ (Extensions to C)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Getting started with C++ (Part 2)

Introduction to C++: I

EP241 Computer Programming

File I/O Christian Schumacher, Info1 D-MAVT 2013

My First Command-Line Program

Professor Terje Haukaas University of British Columbia, Vancouver C++ Programming

DHA Suffa University CS 103 Object Oriented Programming Fall 2015 Lab #01: Introduction to C++

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Why VC++ instead of Dev C++?

Array Initialization

Lectures 5-6: Introduction to C

Introduction to C++ Introduction to C++ 1

C++ for Python Programmers

C++ basics Getting started with, and Data Types.

Introduction. Program construction in C++ for Scientific Computing. School of Engineering Sciences. Introduction. Michael Hanke.

WARM UP LESSONS BARE BASICS

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

ANSI C. Data Analysis in Geophysics Demián D. Gómez November 2013

An Introduction to MATLAB

Unit 1: Introduction to C Language. Saurabh Khatri Lecturer Department of Computer Technology VIT, Pune

PRINCIPLES OF OPERATING SYSTEMS

Computer Programming : C++

Homework #3 CS2255 Fall 2012

Programming in C and C++

Strings and Stream I/O

Multimedia-Programmierung Übung 3

Cours de C++ Introduction

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

F28HS2 Hardware-Software Interface. Lecture 1: Programming in C 1

Structure of this course. C and C++ Past Exam Questions. Text books

A First Program - Greeting.cpp

Introduction to Programming

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

COMP322 - Introduction to C++ Lecture 01 - Introduction

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Lectures 5-6: Introduction to C

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

File IO and command line input CSE 2451

Computational Physics Operating systems

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017

Computers in Engineering. Moving From Fortran to C Michael A. Hawker

Recap. ANSI C Reserved Words C++ Multimedia Programming Lecture 2. Erwin M. Bakker Joachim Rijsdam

CSCE 110 PROGRAMMING FUNDAMENTALS

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 1. Types Variables Expressions & Statements 2/23

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

C++ Programming Fundamentals

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Introduction to C ++

Fast Introduction to Object Oriented Programming and C++

CHAPTER 3 BASIC INSTRUCTION OF C++

Programmazione. Prof. Marco Bertini

Computer Science II Lecture 1 Introduction and Background

EMBEDDED SYSTEMS PROGRAMMING Language Basics

The C language. Introductory course #1

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Sample Code: OUTPUT Daily Highs & Lows

Character Functions & Manipulators Arrays in C++ CS 16: Solving Problems with Computers I Lecture #10

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Chapter 2: Introduction to C++

Laboratory 0 Week 0 Advanced Structured Programming An Introduction to Visual Studio and C++

OBJECT ORIENTED PROGRAMMING

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Transcription:

C, C++, Fortran: Basics Bruno Abreu Calfa Last Update: September 27, 2011 Table of Contents Outline Contents 1 Introduction and Requirements 1 2 Basic Programming Elements 2 3 Application: Numerical Linear Algebra 6 1 Introduction and Requirements Compiled Languages C, C++, and Fortran are compiled languages What you will need: Compiler C: GNU C Compiler (gcc), Intel C Compiler (icc)... C++: GNU C++ Compiler (g++), Intel C++ Compiler (icpc)... Fortran: GNU Fortran Compiler (gfortran), Intel Fortran Compiler (ifort)... What you may use: Integrated Development Environments (IDEs) Languages Standards All Platforms: NetBeans, Eclipse... Mac OS: XCode Windows: Visual Studio C, C++, and Fortran have been revised and enhanced throughout the years It is highly recommended to adhere to ANSI/ISO standards The standards adopted in this presentation are: C: ISO C99 C++: ISO C++98 1

Fortran: ISO Fortran 90/95 (some Fortran 2003) Fortran 2003 received several enhancements including: Better interoperability with C Object-Oriented Programming Procedure pointers Possible References Google Books C: C++: Kernighan, B. W., Ritchie, D. M. (1988) The C Programming Language. 2nd Edition. Prentice Hall. Stroustrup, B. (1997) The C++ Programming Language. 3rd Edition. Addison-Wesley Professional. Yang, D. (2000) C++ and Object-Oriented Numeric Computing for Scientists and Engineers. Springer. Fortran: Chapman, S. J. (2003) Fortran 90/95 for Scientists and Engineers. 2nd Edition. McGraw-Hill. Metcalf, M., Reid, J., Cohen, M. (2004) Fortran 95/2003 Explained. Oxford University Press. 2 Basic Programming Elements Basic Differences C and C++ are case sensitive, while Fortran is case insensitive Primitive Data Types C C++ Fortran Meaning bool bool LOGICAL Logical values (TRUE or FALSE) char char CHARACTER Strings of alphanumeric characters int int INTEGER Integer values float float REAL Real values (single precision) double double REAL Real values (double precision) Selecting the precision in Fortran involves more details (compiler and processor dependent) Recommended: use the KIND parameters in the ISO_FORTRAN_ENV module, e.g. REAL(KIND=REAL64) means 64-bit real value C and C++ programs require a main function in either of the forms: int main(); int main(void); int main(int argc, char* argv[]); Hello, world! Program C: #include <stdio.h> int main() { printf("hello, world!\n"); return 0; 2

C++: #include <iostream> int main() { std::cout << "Hello, world!" << std::endl; return 0; PROGRAM main WRITE(*,*) Hello, world! END PROGRAM main Vectors int a[5] = {1, 2, 3, 4, 5; float b[] = {3.14, 2.72; a[0] // First element of vector a = 1 b[1] // Second (and last) element of vector b = 2.72 INTEGER, DIMENSION(5) :: a = (/ 1, 2, 3, 4, 5 /) REAL(KIND=REAL32), DIMENSION(2) :: b = (/ 3.14, 2.72 /) a(1)! First element of vector a = 1 b(2)! Second (and last) element of vector b = 2.72 a(1:5:2)! Array subset: first:last:step = (/ 1, 3, 5 /) Arrays in C and C++ are zero-based, while in Fortran they are one-based (default, but can be changed) Matrices double c[2][3] = {{1.0, -2.3, 3.1,{0.2, 7.5, 4.8; c[0][1] // Element in first row and second column = -2.3 REAL(KIND=REAL64), DIMENSION(2,3) :: c = RESHAPE((/1.0, 0.2, -2.3, 7.5, 3.1, 4.8/), (/2, 3/)) c(1,2)! Element in first row and second column = -2.3 Arrays in C and C++ are stored in row-major order, while in Fortran they are stored in column-major order Strings char d[6] = "Hello"; char e[] = "Programming is awesome! :-P"; d[0] // First element of string d = H e[10] // Eleventh element of string e = g CHARACTER(len=5) :: d CHARACTER(len=27) :: e d = Hello e = Programming is awesome! :-P d(1)! First element of string d = H e(11)! Eleventh element of string e = g All languages have functions and operators for strings manipulation (length, concatenation, comparison...) 3

Dynamic Memory Allocation Preallocate arrays at runtime (useful if dimension is unknown a priori) C: #include <stdlib.h>... int m = 1000; double* f = (double*) malloc(m*sizeof(double)); // Allocate array with 1000 elements free(f); // Deallocate memory C++: int m = 1000; double* f = new double[m]; // Allocate array with 1000 elements delete[] f; // Deallocate memory INTEGER :: m = 1000 REAL(KIND=REAL64), ALLOCATABLE, DIMENSION(:) :: f ALLOCATE(f(m))! Allocate array with 1000 elements DEALLOCATE(f)! Deallocate memory Arithmetic, Relational, and Logical Operators Arithmetic Operators: C and C++ Fortran Meaning + + Addition - - Subtraction * * Multiplication / / Division N/A ** Exponentiation Relational Operators: C and C++ Fortran Meaning >, < >, < greater than, smaller than >=, <= >=, <= greater or equal than, smaller or equal than ==,!= ==, /= equal to, not equal to Logical Operators: C and C++ Fortran Meaning &&.AND. Logical AND.OR. Logical OR!.NOT. Logical NOT if-elseif-else Statements: Flow Control if (logical_expr_1) { _1 else if (logical_expr_2) { _2 else { _3 IF (logical_expr_1) THEN _1 ELSE IF (logical_expr_2) THEN 4

_2 ELSE _3 END IF for/do Loop Statements for (index = istart; condition; index update) { The istep is optional (default: 1) DO index = istart, iend, istep END DO I/O Concepts Two main input/output devices (streams) Standard (console, terminal) File in hard disk Main I/O functions C: (<stdio.h>) Function scanf printf fscanf fprintf Meaning Reads (formatted) data from standard input Writes (formatted) data to standard output Reads (formatted) data from file Writes (formatted) data to file C++: Higher-level objects and operators For standard I/O, include <iostream> and use namespace std For files, include <ifstream> and use namespace std Examples: cin (standard input), cout (standard output), endl (newline), «( put to operator),» ( get from operator) Formatting can be achieved through set methods (width, precision, number format) or inline with <iomanip> functions Example: print x = 1.23 to standard output cout «fixed «setprecision(2) «1.2345 «endl; Fortran: Two basic functions: READ and WRITE List-directed input: READ(*,*) input_list List-directed output: WRITE(*,*) output_list Formatting can be achieved by specifying the second argument for READ and WRITE or through labeled FORMAT Example: print X = 1.23 to standard output WRITE(*,100) 1.2345 100 FORMAT( X =,F5.2) 5

Procedures: Functions and Subroutines out_type fcn_name(in_type_1 arg_1,...) { [return var;] where out_type can be void (no return value) Example: double square(double a) { return a*a; Subroutines: receive and return values through an argument list Use the reserved word CALL to call the subroutine Example: Functions: result is a single value SUBROUTINE subroutine_name(argument_list) [RETURN] END SUBROUTINE [subroutine_name] SUBROUTINE add2(a, b, c) REAL, INTENT(IN) :: a, b REAL, INTENT(OUT) :: c c = a + b END SUBROUTINE add2 [OUT_TYPE] FUNCTION function_name(argument_list) [RETURN] END FUNCTION [function_name] The function_name must appear on the LHS of at least one assignment statement in the function Example: REAL FUNCTION square(a) REAL, INTENT(IN) :: a square = a*a END FUNCTION square 3 Application: Numerical Linear Algebra Successive Over-Relaxation (SOR) Given the linear system Ax = b where A œ R n2, x œ R n, b œ R n, and initial guess x (0), compute the solution x using the SOR algorithm Iteration x (k+1) i =(1 Ê)x (k) i + Ê a ii Q ab i ÿ j>i a ij x (k) j ÿ j<i a ij x (k+1) j R b i =1, 2,...,n where 1 <Ê<2 6

Input: text file in the following format n a 11 a 1n..... a n1 a nn b 1. b n x (0) 1. x (0) n Output: text file in the following format iter x 1. x n Solution strategy Create procedure to read input data Create procedure to apply the algorithm Create procedure to write the output results 7