XSEDE Scholars Program Introduction to C Programming. John Lockman III June 7 th, 2012

Similar documents
Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

C: How to Program. Week /Mar/05

Fundamentals of Programming

Chapter 2 - Introduction to C Programming

Fundamental of Programming (C)

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

A Fast Review of C Essentials Part I

The component base of C language. Nguyễn Dũng Faculty of IT Hue College of Science

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

BLM2031 Structured Programming. Zeyneb KURT

University of Technology. Laser & Optoelectronics Engineering Department. C++ Lab.

Syntax and Variables

DEPARTMENT OF MATHS, MJ COLLEGE

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Data types, variables, constants

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Procedures, Parameters, Values and Variables. Steven R. Bagley

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

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

6.096 Introduction to C++ January (IAP) 2009

Presented By : Gaurav Juneja

Variables. Data Types.

C Language, Token, Keywords, Constant, variable

BASIC ELEMENTS OF A COMPUTER PROGRAM

Basic Types, Variables, Literals, Constants

Programming and Data Structures

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Programming Fundamentals (CS 302 ) Dr. Ihsan Ullah. Lecturer Department of Computer Science & IT University of Balochistan

Programming in C++ 4. The lexical basis of C++

Basic Elements of C. Staff Incharge: S.Sasirekha

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

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

Chapter 1 & 2 Introduction to C Language

VARIABLES AND CONSTANTS

Programming. C++ Basics

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Work relative to other classes

P.G.TRB - COMPUTER SCIENCE. c) data processing language d) none of the above

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Data Types and Variables in C language

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

ME240 Computation for Mechanical Engineering. Lecture 4. C++ Data Types

C Programming Language Training. This instruction relies on the C language described in C++: The Complete Reference Third Edition By Herbert Schildt

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

3. Java - Language Constructs I

In this session we will cover the following sub-topics: 1.Identifiers 2.Variables 3.Keywords 4.Statements 5.Comments 6.Whitespaces 7.Syntax 8.

from Appendix B: Some C Essentials

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

ET156 Introduction to C Programming

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

CMPE-013/L. Introduction to C Programming

Course Outline Introduction to C-Programming

!"#$% &'($) *+!$ 0!'" 0+'&"$.&0-2$ 10.+3&2),&/3+, %&&/3+, C,-"!.&/+"*0.&('1 :2 %*10% *%7)/ 30'&. 0% /4%./

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Programming. Elementary Concepts

COMP322 - Introduction to C++

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

DETAILED SYLLABUS INTRODUCTION TO C LANGUAGE

File Handling in C. EECS 2031 Fall October 27, 2014

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

UEE1302 (1102) F10: Introduction to Computers and Programming

Computer System and programming in C

Chapter 2: Overview of C. Problem Solving & Program Design in C

ET156 Introduction to C Programming

EEE145 Computer Programming

Computers Programming Course 5. Iulian Năstac

Department of Computer Applications

Programming in C and C++

Variables in C. CMSC 104, Spring 2014 Christopher S. Marron. (thanks to John Park for slides) Tuesday, February 18, 14

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Introduction to C# Applications

These are reserved words of the C language. For example int, float, if, else, for, while etc.

ANSI C Programming Simple Programs

Types, Operators and Expressions

Programming. Data Structure

DECLARATIONS. Character Set, Keywords, Identifiers, Constants, Variables. Designed by Parul Khurana, LIECA.

Tokens, Expressions and Control Structures

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University


C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

edunepal_info

CMSC 104 -Lecture 5 John Y. Park, adapted by C Grasso

UNIT- 3 Introduction to C++

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

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

Programming in C and C++

INTRODUCTION 1 AND REVIEW

PROGRAMMAZIONE I A.A. 2018/2019

Aryan College. Fundamental of C Programming. Unit I: Q1. What will be the value of the following expression? (2017) A + 9

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

HISTORY OF C LANGUAGE. Facts about C. Why Use C?

Programming with C++ Language

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

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

Transcription:

XSEDE Scholars Program Introduction to C Programming John Lockman III June 7 th, 2012

Homework 1 Problem 1 Find the error in the following code #include <stdio.h> int main(){ } printf(find the error!\n"); return(0);

Get the Book Everybody should get a copy of: C Programming Language (2nd Edition) [Paperback] by Brian W. Kernighan & Dennis M. Ritchie

Additional Resources http://www.cprogramming.com/ This site has tutorials, example problems, and example quizzes.

Homework 1 Problem 1 - Solution Find the error in the following code #include <stdio.h> int main(){ } printf( Find the error!\n"); return(0);

Homework 1 Problem 2 Write a program to print your name on the screen.

Homework 1 Problem 2 - Solution #include <stdio.h> int main(){ printf( My Name is John!\n ); return 0; }

Features C is small (originally only 32 keywords!) C is common (lots of C code about) C is stable (the language hasn t change much) C is quick running (close to assembly) C syntax is the basis for many other languages (csh, C++, awk, Perl). C is one of the easiest languages to learn. Basic philosophy: Programmers know what they are doing

Comments and New Line: rules.c /* * rules.c * this is a multi-line comment */ #include <stdio.h> int main(){ // this is a single line comment printf( Hello World!\n"); printf( This code contains comments and prints to the screen\n ); return 0; }

Some C Language Keywords Category Storage class specifiers Structure & union specifiers Enumerations Type-Specifiers Type-Qualifiers Control structures Operator Other reserved words Keywords auto register static extern typedef struct union enum char double float int long short signed unsigned void const volatile if, else, do, while, for, break, continue, switch, case, default, return, goto NEVER USE sizeof asm bool friend inline

Variables Information-storage places Compiler makes room for them in the computer s memory Can contain string, characters, numbers etc. Their values can change during program execution All variables must be declared before they are used and must have a data type associated with them Variable must be initialized before they are used

Types and variables A variable defines an area of storage in memory Must declare the type of every variable before we can use it. [type modifier] <type> <comma-separated names>; Motivation: makes intent of variables explicit and prevents mistakes, i.e. typos. Basic types: int, char, long, short, float, and double. Type modifiers: signed, unsigned, long, short, and const. Declarations of types should always be at the top of a syntax block or file.

Naming variables Variables in C can be given any name made from numbers, letters and underlines (or underscore) Caveat 1: Must not begin with a number. Caveat 2: Must not be a keyword A good name for your variables is important /* City attributes for Houston */ int number_buildings; double rain_fall_average; int population; Important to pick well chosen variable names and comments on variables

The char type char stores a character variable usually 8 bits in size. A char can be assigned a value between 0 and 255, or a single quoted ASCII character. char a, b; a= 123; b= a ; /* assigning a character*/ return 0;

The int type int stores an integer variable usually 32 bits in size. An int can be assigned a value between INT_MIN and INT_MAX (defined in /usr/include/limits.h) int x, y; x = 1966; #include <limits.h> y = INT_MAX;

The float and double type float and double stores a floating point variable float single-precision (32 bits) double double-precision (64 bits) C uses the IEEE 754 float point representation standard Exponent: 8 (11) bits Fraction: 23 (52) bits sign Fraction 3.0e6 exponent MAXFLOAT and MINFLOAT (MAXDOUBLE and MINDOUBLE) defined in /usr/include/values.h

Type modifiers: Signed/unsigned, long, short, const unsigned can modify an int or char declaration. It means the variable can only be positive. signed means that it can be positive or negative. long can modify an int, float or double declaration to increase its precision. short means they have less const means a variable cannot be changed short int small_no; unsigned char uchar; long double precise_number; const double e= 2.718281828; Hardware dependent: could be 80bit or 128bit

Example of Updating Variables: myage.c #include <stdio.h> int main(){ } int age; age = 10; printf("initial value of age is: %d\n", age); age = 20; printf("updated value of age is: %d\n", age); age = age + 20; printf("new updated value of age is: %d\n", age); return 0; Output: Initial value of age is: 10 Updated value of age is: 20 New updated value of age is: 40

Casting between variables A cast is a way of telling one variable type to temporarily look like another. In many languages, this is not possible int a; double c; c = a; This is incorrect.

Casting between variables A cast is a way of telling one variable type to temporarily look like another. In many languages, this is not possible int a; double c; c = a; c= (double) a; By using (type) in front of a variable we tell the variable to act like another type of variable. We can cast between any type.

Scope of Variables A variable can be either of global or local scope Global variables are defined outside all functions and they can be accessed and used by all functions in a program file A local variable can be accessed only by the function in which it is created A local variable can be further qualified as static, in which case, it remains in existence rather than coming and going each time a function is called static int x = 0; A register type of variable is placed in the machine registers for faster access compilers can ignore this advice register int x;

Variable Scope What is scope? The scope of a variable is where it can be used in a program Normally variables are local in scope - this means they can only be used in the block where they are declared { } var1; { { } } func(var1); Scope We can also declare global variables, but try to avoid this if possible.

#include <stdio.h> int main(){ Variable Scope Local scope example } int i; i = 1966; { int i; i = 2007; printf( %d\n, i); } printf( %d\n, i); return 0; Variables here are LOCAL variables Output: 2007 1966

#include <stdio.h> Variable Scope Global scope example int i; int main() { i = 1966; { i = 2007; printf( %d\n, i); } printf( %d\n, i); return 0; } Variable here is a GLOBAL variables Output: 2007 2007

Constants MAGIC numbers in programs A lot of programs contain MAGIC numbers g = 43.2 * a + 7.1; for (i= 7; i < 103; i+=2) { printf ("%d\n",i*7); } This makes code look ugly and difficult to maintain. It is better to assign these numbers to a name and localize it so changes can be made easily. Three possible solutions: enum, #define and const.

Constants enum We can use the enum syntax to define common int and char variables. E.g.: enum { MAX_LEN= 100, LETTERX= 'x', NEWLINE= '\n' }; By convention we use all capitals for constants. for (i= 0; i < MAX_LEN; i++) printf ( %c,letterx);

Constants Const Another solution is to use the const keyword. /* Approximate value of PI */ const double PI=3.14; /* Maximum iterations to be performed before exiting */ const int MAX_ITER=1000;

Constants #define This pre-processor command replaces one thing with another before compilation NOTE NO semicolon here! #define PI 3.14 #define GRAV_CONST 9.807 #define HELLO_WORLD "Hello World!\n" // Macros PI, GRAV_CONST, and HELLO_WORLD will // be replaced with the defined values before // the real compiler gets to work. c= 2.0 * PI * r; a= GRAV_CONST * (m1*m2)/ (r * r); printf (HELLO_WORLD);

Constants and Constant Expressions The value of a constant never changes const double e = 2.71828182; Macros #define MAXRECORDS 100 In the code, identifiers (MAXRECORDS) are replaced with the values (100) Helps to avoid hard-coding of values at multiple places Example: char records[maxrecords + 1]; Can be used at any place where constants can be used Enumeration is a list of constant values enum boolean {NO, YES}; Expressions containing constants are evaluated at compile-time

Operators: increment/decrement ++i means increment i then use it i++ means use i then increment it int i= 6; int j; j = i++; /* j is assigned 6 */ int i= 6; int j; j = ++i; /* j is assigned 7 */ All of the above also applies to --.

Basic useful operators Arithmetic: + (add), - (subtract), * (multiple), / (divide) Logical: && (AND), (OR),! (NOT) (X && Y) Z /* TRUE if X and Y is TRUE OR Z is TRUE */

More useful operators += (add to a variable) E.g. -= (subtract from variable) E.g. *= (multiply a variable) E.g. /= (divide a variable) E.g. (x%y) returns remainder when x is divided by y E.g. a += 5 a = a + 5; b -= 4 b = b - 4; c *= 2 c = c * 2; f /= d f = f / d; remainder= x%y;

Precedence and Order of Evaluation Operators Associativity ( ) [ ] ->. Left to right! ~ ++ -- + - * & (type) Right to left * / % Left to right + - Left to right << >> Left to right < <= > >= Left to right ==!= Left to right & Left to right ^ Left to right Left to right && Left to right Left to right?: Right to left = += -= *= /= %= &= ^= = <<= >>= Right to left, Left to right

Homework 2 Write a program in C that declares 3 variables of type int, float, and char. You may choose any appropriate name for your variables. Use the following values for your variables: int 40 float 3.14159265 char T After you have initialized these three variables, print them to the screen.