Lecture 2, basic C. Michigan State University CSE 251,Spring 2009 Getting Started Log in using diskless (if you’re on Windows) Make sure you know how.

Slides:



Advertisements
Similar presentations
Programming In C++ Spring Semester 2013 Lecture 2 Programming In C++, Lecture 2.
Advertisements

C Programming Day 1 based upon Practical C Programming by Steve Oualline CS550 Operating Systems.
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
Introduction to C Programming
Introduction to C Programming
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
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.
Introduction to C Programming
Basic Input/Output and Variables Ethan Cerami New York
1 Lecture 3  Lexical elements  Some operators:  /, %, =, +=, ++, --  precedence and associativity  #define  Readings: Chapter 2 Section 1 to 10.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Computer Science 210 Computer Organization Introduction to C.
EG280 - CS for Engineers Chapter 2, Introduction to C Part I Topics: Program structure Constants and variables Assignment Statements Standard input and.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
C Programming Lecture 4 : Variables , Data Types
CS1 Lesson 2 Introduction to C++ CS1 Lesson 2 -- John Cole1.
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.
Input, Output, and Processing
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
/* C Programming for the Absolute Beginner */ // by Michael Vine #include main() { printf(“\nC you later\n”); system(“pause”); }
Week 1 Algorithmization and Programming Languages.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
CSCI 171 Presentation 2. Program Components main() #include Variable Definition Function Prototype Program Statements Function Call Function Definition.
Introduction to C++ Basic Elements of C++. C++ Programming: From Problem Analysis to Program Design, Fourth Edition2 The Basics of a C++ Program Function:
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
C++ Programming Lecture 3 C++ Basics – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Operating System Discussion Section. The Basics of C Reference: Lecture note 2 and 3 notes.html.
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.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Introduction to Algorithmic Processes CMPSC 201C Fall 2000.
1 C Syntax and Semantics Dr. Sherif Mohamed Tawfik Lecture Two.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Lecture 3: Getting Started & Input / Output (I/O)
Last week: We talked about: History of C Compiler for C programming
C++ First Steps.
CSCE 206 Structured Programming in C
Topics Designing a Program Input, Processing, and Output
Computer Science 210 Computer Organization
Chapter 2 - Introduction to C Programming
Getting Started with C.
Chapter 2 - Introduction to C Programming
Computer Science 210 Computer Organization
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Introduction to CS Your First C Programs
Introduction to C++ Programming
Chapter 2 - Introduction to C Programming
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 2 - Introduction to C Programming
Topics Designing a Program Input, Processing, and Output
Introduction to C Topics Compilation Using the gcc Compiler
Topics Designing a Program Input, Processing, and Output
Chapter 2 - Introduction to C Programming
Variables in C Topics Naming Variables Declaring Variables
Introduction to C Programming
Getting Started With Coding
Presentation transcript:

Lecture 2, basic C

Michigan State University CSE 251,Spring 2009 Getting Started Log in using diskless (if you’re on Windows) Make sure you know how to do the following:  Open a new shell window  Open a browser - browser is now installed  Read a pdf file (go to the class web site and download the pdf slides for this lecture) – pdf viewer is now installed  Use gedit to edit programs  Go to your home directory (using the folders and using “cd” command) – e.g., /user/yourname

Example 0 (All examples can be downloaded from the class web page)

Michigan State University CSE 251,Spring 2009 hello world #include /* hi mom */ int main () { printf(“hello world\n”); } This is your first C program

Michigan State University CSE 251,Spring 2009 hello world #include /* hi mom */ int main () { printf(“hello world\n”); } #include statement

Michigan State University CSE 251,Spring 2009 hello world #include /* hi mom */ int main () { printf(“hello world\n”); } #include statement comments

Michigan State University CSE 251,Spring 2009 hello world #include /* hi mom */ int main () { printf(“hello world\n”); } #include statement commentsMain program

Michigan State University CSE 251,Spring 2009 #include statement Provides definitions for libraries  library contains the “built-in” functions for various tasks (printing, reading input, etc) and definitions of “built-in” variables (e.g., M_PI)  Built-in libraries are mostly found in /usr/include (their filenames end in *.h, i.e., a header file) Try opening the stdio.h and math.h files  “definitions” mean that the “form” of the functions and variables provided by the libraries, but not the actual code itself

Michigan State University CSE 251,Spring 2009 Comments standard C comments are bracketed between the symbols /* and the symbols */ Anything in between (spacing, tabs, newlines, punctuation, code, etc.) is ignored /* hi mom */ “hi mom” is a comment

Michigan State University CSE 251,Spring 2009 the main function Every C program that can be run must have a main function. When the system starts the executable, it runs that function by default int main () { /* your code goes here */ }

Michigan State University CSE 251,Spring 2009 The { } symbols In python, a “suite” was a set of statements grouped together, also called a block. A “block” is indicated here by the beginning and end of the { } symbols

Michigan State University CSE 251,Spring 2009 ; The ; character is used to indicate the end “of a statement” The end of a statement is not necessarily the end of a line. Statement is logical, line is layout

Michigan State University CSE 251,Spring 2009 hello world #include /* hi mom */ int main () { printf(“hello world\n”); } No semicolon here Don’t care whether there are semicolons or not Main program Each statement should be terminated with a semicolon unless it defines a block of statements {…}

Michigan State University CSE 251,Spring 2009 printf printf is the function that takes a string as input and prints it as indicated Strings are listed between “ “. Remember that to get a newline, you must explicitly include \n  Example: printf(“hello world\n”);

Michigan State University CSE 251,Spring 2009 Escape characters Characters that are hard to express: \nnewline \ttab \’print a single quote \\print a backslash many others

Example 1 A more complex C program

Michigan State University CSE 251,Spring 2009 #include #include "simpleCalc.h” int main(){ int installations; // number of installations float yardsOfPipe, // yards of pipe used during installations feetOfPipe, // feet of pipe used during installations revenue; // revenue generated printf("Please enter the number of installations: "); scanf("%d",&installations); printf("Please enter the yards of pipe used: "); scanf(”%f",&yardsOfPipe); feetOfPipe = 3 * yardsOfPipe; revenue = installations * INSTALLATION_FEE + feetOfPipe * COST_PER_FOOT; // cap values from include printf("The revenue generated = $%f\n\n",revenue); return 0; } What’s New?

Michigan State University CSE 251,Spring 2009 #include #include "simpleCalc.h” int main(){ int installations; // number of installations float yardsOfPipe, // yards of pipe used during installations feetOfPipe, // feet of pipe used during installations revenue; // revenue generated printf("Please enter the number of installations: "); scanf("%d",&installations); printf("Please enter the yards of pipe used: "); scanf(”%f",&yardsOfPipe); feetOfPipe = 3 * yardsOfPipe; revenue = installations * INSTALLATION_FEE + feetOfPipe * COST_PER_FOOT; // cap values from include printf("The revenue generated = $%f\n\n",revenue); return 0; } Another type of include statement

Michigan State University CSE 251,Spring 2009 #include #include "simpleCalc.h” int main(){ int installations; // number of installations float yardsOfPipe, // yards of pipe used during installations feetOfPipe, // feet of pipe used during installations revenue; // revenue generated printf("Please enter the number of installations: "); scanf("%d",&installations); printf("Please enter the yards of pipe used: "); scanf(”%f",&yardsOfPipe); feetOfPipe = 3 * yardsOfPipe; revenue = installations * INSTALLATION_FEE + feetOfPipe * COST_PER_FOOT; // cap values from include printf("The revenue generated = $%f\n\n",revenue); return 0; } Another type of include statement C++ style comments

Michigan State University CSE 251,Spring 2009 #include #include "simpleCalc.h” int main(){ int installations; // number of installations float yardsOfPipe, // yards of pipe used during installations feetOfPipe, // feet of pipe used during installations revenue; // revenue generated printf("Please enter the number of installations: "); scanf("%d",&installations); printf("Please enter the yards of pipe used: "); scanf(”%f",&yardsOfPipe); feetOfPipe = 3 * yardsOfPipe; revenue = installations * INSTALLATION_FEE + feetOfPipe * COST_PER_FOOT; // cap values from include printf("The revenue generated = $%f\n\n",revenue); return 0; } Another type of include statement Variable Declaration C++ style comments

Michigan State University CSE 251,Spring 2009 #include #include "simpleCalc.h” int main(){ int installations; // number of installations float yardsOfPipe, // yards of pipe used during installations feetOfPipe, // feet of pipe used during installations revenue; // revenue generated printf("Please enter the number of installations: "); scanf("%d",&installations); printf("Please enter the yards of pipe used: "); scanf(”%f",&yardsOfPipe); feetOfPipe = 3 * yardsOfPipe; revenue = installations * INSTALLATION_FEE + feetOfPipe * COST_PER_FOOT; // cap values from include printf("The revenue generated = $%f\n\n",revenue); return 0; } Another type of include statement Variable Declaration Another built-in function C++ style comments

Michigan State University CSE 251,Spring 2009 #include #include "simpleCalc.h” int main(){ int installations; // number of installations float yardsOfPipe, // yards of pipe used during installations feetOfPipe, // feet of pipe used during installations revenue; // revenue generated printf("Please enter the number of installations: "); scanf("%d",&installations); printf("Please enter the yards of pipe used: "); scanf(”%f",&yardsOfPipe); feetOfPipe = 3 * yardsOfPipe; revenue = installations * INSTALLATION_FEE + feetOfPipe * COST_PER_FOOT; // cap values from include printf("The revenue generated = $%f\n\n",revenue); return 0; } Another type of include statement Variable Declaration Another built-in function Arithmetic expression C++ style comments

Michigan State University CSE 251,Spring 2009 #include #include "simpleCalc.h” int main(){ int installations; // number of installations float yardsOfPipe, // yards of pipe used during installations feetOfPipe, // feet of pipe used during installations revenue; // revenue generated printf("Please enter the number of installations: "); scanf("%d",&installations); printf("Please enter the yards of pipe used: "); scanf(”%f",&yardsOfPipe); feetOfPipe = 3 * yardsOfPipe; revenue = installations * INSTALLATION_FEE + feetOfPipe * COST_PER_FOOT; // cap values from include printf("The revenue generated = $%f\n\n",revenue); return 0; } Another type of include statement Variable Declaration Another built-in function Arithmetic expression Return an exit code C++ style comments

Michigan State University CSE 251,Spring 2009

Michigan State University CSE 251,Spring 2009 #include: versus “ “ means get the built-in variable/function definitions from “the standard place” (usually /usr/include) “ “ means get them from the current directory, ie, your own variable/function definitions #include #include "simpleCalc.h”

Michigan State University CSE 251,Spring 2009 simplecalc.h (Header file) double INSTALLATION_FEE = , // installation fee COST_PER_FOOT = 3.25; // pipe cost per foot

Michigan State University CSE 251,Spring 2009 Single-line comment: // in C99 you can use // as a comment Ignore everything from // to the end of the line double INSTALLATION_FEE = ; // installation fee This is the comment part

variables

Michigan State University CSE 251,Spring 2009 Why do we need variable declaration? Answer: memory Here is how C deals with memory Imagine the system memory as a nice, flat stretch of beach You want a variable, you need to dig a hole in the sand and dump the value in How big a hole?

Michigan State University CSE 251,Spring 2009 Declare variable before use When you declare a variable, you are telling the compiler the size of value the variable may hold (its type) You cannot change the type of value a variable can hold once declared (well, pretty much anyway) In fact, everything needs a type in C and it must be declared before use!

Michigan State University CSE 251,Spring 2009 Common types, “regular” C int : an integer, usually 4 bytes float: float, usually 4 bytes double : float, usually 8 bytes char : single char, value in single quotes

Michigan State University CSE 251,Spring 2009 Must declare before use Every variable must be declared before it can be used (its type must be indicated) Syntax: [ = ]; Example: int length, width = 5, height = 10;

Michigan State University CSE 251,Spring 2009 Rules for Variable Names Must begin with a letter any combination of letters, digits and underscore at least as long as 31 chars, C99 at least 63 cannot match with a C keyword  E.g., int int; int long;

Michigan State University CSE 251,Spring 2009 C Keywords autodoubleintstruct breakelselongswitch caseenumregistertypedef charexternreturnunion constfloatshortunsigned continueforsignedvoid defaultgotosizeofvolatile doifstaticwhile

printf, more detail

Michigan State University CSE 251,Spring 2009 Example of String Formatting

Michigan State University CSE 251,Spring 2009 Many descriptors %s string %d decimal %e floating point exponent %f floating point decimal %u unsigned integer and others

Michigan State University CSE 251,Spring 2009 Full Format string The format string contains a set of format descriptors that describe how an object is to be printed % -# h d start specification Flags Width Precision size modifier (h for short int) Conversion Type (d for decimal)

Michigan State University CSE 251,Spring 2009 Examples printf(“%f\n”,M_PI);  printf(“%.4f\n”,M_PI);  (4 decimal points of precision, with rounding) printf(“%10.2f\n”,M_PI);  3.14 (10 spaces in total including the number and the decimal point) printf(“%10.2f is PI\n”,M_PI);  3.14 is PI

Input

Michigan State University CSE 251,Spring 2009 scanf Scanf is an input routine useful for reading in string input and doing conversion to the correct type, all at once syntax is “kind of like” printf beware the use of the & operator!!! printf("Please enter the yards of pipe used: "); scanf(”%f",&yardsOfPipe);

Michigan State University CSE 251,Spring 2009 Basic form To understand input, it is probably better to start with an example. scanf(“%d, %f”, &myInt, &myFloat); is waiting for input of the exact form 25,

Michigan State University CSE 251,Spring 2009 format string the same What is typed in the format string is the same as what the input expects, in this case:  a decimal number  a comma  a floating point number

Michigan State University CSE 251,Spring 2009 The & Hard to explain at the moment, but any variable that gets read in needs that ampersand character It is the address of the variable more on that later

Arithmetic Expression

Michigan State University CSE 251,Spring 2009 Types determine results For integers: +,-,*,/ all yield integers. Thus division can lead to truncation (2/3 has value 0). % gives the remainder For floats: +,-,*,/ all work as advertised. No remainder.

Michigan State University CSE 251,Spring 2009 Mixed computation As with most languages, C expects to work with like types , When mixing, usually errors except where C can “help” It will promote a value to a more “detailed” type when required yields a float (1 promoted to 1.0)

Michigan State University CSE 251,Spring 2009 coercion, cast Explicit type conversion: (double) 3  convert int 3 to double 3.0. Note the parens! (int) 3.14  convert 3.14 to int. No rounding! Makes a new value, does not affect the old one!

Example 2

Michigan State University CSE 251,Spring 2009 #include int main(){ // const means the variable value cannot be changed from this initial setting const int A = 3, B = 4, C = 7; const double X = 6.5, Y = 3.5; printf("\n*** Integer computations ***\n\n"); printf("%d + %d equals %d\n",A,B,A+B); printf("%d - %d equals %d\n",A,B,A-B); printf("%d * %d equals %d\n",A,B,A*B); printf("%d / %d equals %d with remainder %d\n",A,B,A/B,A%B); printf("\n"); printf("\n*** Real computations ***\n\n"); printf("%f + %f equals %f\n",X,Y,X+Y); printf("%f - %f equals %f\n",X,Y,X-Y); printf("%f * %f equals %f\n",X,Y,X*Y); printf("%f / %f equals %f\n",X,Y,X/Y);

Michigan State University CSE 251,Spring 2009 printf("\n*** Mixed-type computations ***\n\n"); printf("%f + %d equals %f\n",X,A,X+A); printf("%f - %d equals %f\n",X,A,X-A); printf("%f * %d equals %f\n",X,A,X*A); printf("%f / %d equals %f\n",X,A,X/A); printf("\n*** Compound computations ***\n\n"); printf("%d + %d / %d equals %d\n",C,B,A,C+B/A); printf("(%d + %d) / %d equals %d\n",C,B,A,(C+B)/A); printf("\n"); printf("%d / %d * %d equals %d\n",C,B,A,C/B*A); printf("%d / (%d * %d) equals %d\n",C,B,A,C/(B*A)); printf("\n*** Type conversions ***\n\n"); printf("Value of A: %d\n",A); printf("Value of (double)A: %f\n",(double)A); printf("Value of X: %f\n",X); printf("Value of (int)X: %d\n",(int)X); return 0; } Try it out on your own

Assignment

Michigan State University CSE 251,Spring 2009 = does not mean equal to the “=“ means assignment, not equalty. Assignment means:  do everything on the lhs of the =, get a value  dump the value into the memory indicated by the variable on the rhs  variable now associated with a value declare first, assign second!

Michigan State University CSE 251,Spring 2009 example int val1, val2; val1 = 7 * 2 + 5;// 19 now in val1 val2 = val1 + 5;// 24 in val2 val2 = val2 + 10;// calc lhs (34), // reassign to val2

Michigan State University CSE 251,Spring 2009 rules rhs must yield a value to be assigned lhs must be a legal name type of the value and the variable must either match or there be a way for a conversion to take place automatically