Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.

Slides:



Advertisements
Similar presentations
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
Advertisements

Lecture 2 Introduction to C Programming
Introduction to C Programming
Introduction to C Creating your first C program. Writing C Programs  The programmer uses a text editor to create or modify files containing C code. 
Introduction to C Programming
C Programming Basics Lecture 5 Engineering H192 Winter 2005 Lecture 05
 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.
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
C Programming. Chapter – 1 Introduction Study Book for one month – 25% Learning rate Use Compiler for one month – 60%
Computer Science 210 Computer Organization Introduction to C.
CS 11 C track: lecture 1 Preliminaries Need a CS cluster account cgi-bin/sysadmin/account_request.cgi Need to know UNIX ITS.
C Programming Functions Macros. Functions vs. Methods Java classes include methods which can be called from any code with appropriate access (recall public.
Programming With C.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Java Programming, Second Edition Chapter One Creating Your First Java Program.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
C STRUCTURES. A FIRST C PROGRAM  #include  void main ( void )  { float height, width, area, wood_length ;  scanf ( "%f", &height ) ;  scanf ( "%f",
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Introduction to Java Java Translation Program Structure
Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.
Separate Compilation make and makefiles
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Introduction to FunctionsCIS 1057 Fall Introduction to Functions CIS 1057 Computer Programming in C Fall 2013 (Acknowledgement: Many slides based.
Programming in C Variables, Controls, Arrays, Functions.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
By Mr. Muhammad Pervez Akhtar
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
L071 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program Reading Sections
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.
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.
C Programming Functions Separate Compilation. Functions vs. Methods Java classes include methods which can be called from any code with appropriate access.
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.
Introduction to C Topics Compilation Using the gcc Compiler
UMBC CMSC 104 – Section 01, Fall 2016
CSCE 206 Structured Programming in C
The Machine Model Memory
Computer Science 210 Computer Organization
A bit of C programming Lecture 3 Uli Raich.
Yanal Alahmad Java Workshop Yanal Alahmad
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Functions Separate Compilation
Variables, Controls, Arrays, Functions
Introduction to C Topics Compilation Using the gcc Compiler
C Short Overview Lembit Jürimägi.
Introduction to C Topics Compilation Using the gcc Compiler
Computer Science 210 Computer Organization
Introduction to C Topics Compilation Using the gcc Compiler
C Programming Getting started Variables Basic C operators Conditionals
Introduction to C Topics Compilation Using the gcc Compiler
C++ Programming Basics
Module 2 Variables, Data Types and Arithmetic
An Overview of C.
C Language B. DHIVYA 17PCA140 II MCA.
Introduction to C Topics Compilation Using the gcc Compiler
SPL – PS1 Introduction to C++.
Presentation transcript:

Programming in C Variables, Controls, Functions

7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem solving centers on defining classes that model “things” like Trucks, Persons, Marbles, Strings, and CandyMachine  Classes encapsulate data (instance variables) and code (methods) C is a procedural language  Problem solving centers on defining functions that perform a single service like getValidInt( ), search( ) and inputPersonData( ).  Data is global or passed to functions as parameters  No classes

7/28/09 Libraries Because Java is an OOP language, its libraries consist of predefined classes that you can use in your applicationsBecause Java is an OOP language, its libraries consist of predefined classes that you can use in your applications –ArrayList, Scanner, Color, Integer Because C is a procedural language, its library consists of predefined functions.Because C is a procedural language, its library consists of predefined functions. –Char/string functions (strcpy, strcmp) –Math functions (floor, ceil, sin) –Input/Output functions (printf, scanf) On-line C/Unix manual -- the “man” commandOn-line C/Unix manual -- the “man” command –Description of many C library functions and Unix commands –Usage: man for C library functions or man for Unix commands man printf man dir –Search for applicable man pages using the “apropos” command or “man -k” –Learn to use the man command using “man man”

7/28/09 Hello World In JAVA -- Hello.java is in a class package hello; public class Hello { public static void main( String[ ] args ) { System.out.println( “Hello World” ); }} In C -- Hello.c stands alone #include #include int main( ) { printf( “Hello World\n” ); return 0; }

7/28/09 Compiling and Running a Java Program Java Code Java Bytecode JRE for Linux JRE for Windows Java compiler Hello.java javac Hello.java Hello.class java Hello Java interpreter translates bytecode to machine code in JRE unix> javac -d. *.java unix> java hello.Hello

7/28/09 Compiling and Running a C Program Pre- processor ( cpp ) hello.i Compiler ( cc1 ) hello.s Assembler ( as ) hello.o Linker ( ld ) hellohello.c Source program (text) Modified source program (text) Assembly program (text) Relocatable object programs (binary) Executable object program (binary) printf.o unix> gcc -o hello hello.c unix> hello

7/28/09 Language Commonality C and Java syntax have much in commonC and Java syntax have much in common –Some Data Types –Arithmetic operators –Logical Operators –Control structures –Other Operators

1/13/10 Data Types Both languages support the integral types int, short, long.Both languages support the integral types int, short, long. Both languages support the floating point types double and floatBoth languages support the floating point types double and float Both languages support the character data type charBoth languages support the character data type char Both languages support enumerations - enumBoth languages support enumerations - enum C allows the signed (default) and unsigned qualifiers for integral types ( char, int, short, long)C allows the signed (default) and unsigned qualifiers for integral types ( char, int, short, long) C does NOT support byte (use char instead)C does NOT support byte (use char instead) Both languages support arrays using [ ] and indexing starting with zero (0).Both languages support arrays using [ ] and indexing starting with zero (0).

1/13/10 True and False Java supports the bool data type and the keywords andJava supports the bool data type and the keywords true and false bool isRed = true; bool isLarge = false; C does not support the data type. Integer variables and expressions are used as insteadC does not support the bool data type. Integer variables and expressions are used as instead –Any non-zero value is considered “true” –A zero integer value is considered “false” int isRed = 55;/* “true” */ int isLarge = 0;/* “false” */

7/28/09 Arithmetic Operators Arithmetic operators are the same = is used for assignment +, -, (plus, minus) *, /, % (times, divide, mod) ++, -- (increment, decrement (pre and post)) Combinations are the same +=, -=, (plus equal, minus equal) *=, /=, %= (times equal, divide equal, mod equal)  Arithmetic Practice Arithmetic Practice Arithmetic Practice  Assignment Practice Assignment Practice Assignment Practice

7/28/09 Logical Operators Logical operators are the same in C and Java and result in a Boolean value.  && (and)  || (or)  ==, != (equal and not equal)  <, <= (less than, less than or equal)  >, >= (greater than, greater than or equal)  Boolean Logic Practice Boolean Logic Practice Boolean Logic Practice

7/28/09 Control Structures Both languages support these control structures which function the same way in C and Java  for loops  But NOT -- for (int i = 0; i < size; i++)  while loops  do-while loops  switch statements  if and if-else statements  braces ( {, } ) are used to begin and end blocks  Loop Practice Loop Practice Loop Practice

7/28/09 Other Operators These other operators are the same in C and Java  ?: (tri-nary “hook colon”) int larger = (x : y ? x : y);  >, &, |, ^ (bit operators*)  >=, &=, |=,^=  [ ] (brackets for arrays)  ( ) parenthesis for functions and type casting *much more on these later

1/13/10 #defines The directive can be used to give names to important constants in your code. This makes your code more readable and more easily changeable.The #define directive can be used to give names to important constants in your code. This makes your code more readable and more easily changeable. The compiler replaces every instance of the name with the text that it represents.The compiler replaces every instance of the #define name with the text that it represents. Note that there is no terminating semi-colonNote that there is no terminating semi-colon #define MIN_AGE if (myAge > MIN_AGE)... #define HELP “There is no hope”... printf( “%s\n”, HELP);...

1/13/10 typedefs C allows you to define new names for existing data types (NOT new data types)C allows you to define new names for existing data types (NOT new data types) This feature can be used to give application- specific names to simple typesThis feature can be used to give application- specific names to simple types typedef int Temperature; typedef long Width; Or to give simple names to complex types - more on this laterOr to give simple names to complex types - more on this later Using s makes future changes easier and makes the code more relevant to the applicationUsing typedef s makes future changes easier and makes the code more relevant to the application

7/28/09 Enumeration Constants C provides the as a list of named constant integer values (starting a 0 by default)C provides the enum as a list of named constant integer values (starting a 0 by default) Names in s must be distinctNames in enum s must be distinct Often a better alternative toOften a better alternative to #defines ExampleExample enum boolean { FALSE, TRUE }; enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

1/13/10 Miscellaneous CommentsComments –Both languages support block comments surrounded by /* and */ –C DOES NOT support // comment style* Declaring variablesDeclaring variables –All variables must be declared at the beginning of the “block” in which they are used TypecastingTypecasting –Both languages allow typecasting - temporarily treating a variable as a different type temp = (double) degrees / 4; Ask me about C99Ask me about C99

7/28/09 Functions vs. Methods Java classes include methods which can be called from any code with appropriate access (recall public methods)Java classes include methods which can be called from any code with appropriate access (recall public methods) C functions are like Java methods, but they don’t belong to any class. Functions are defined in a file and may be either global to your program or local to the file in which they are defined*.C functions are like Java methods, but they don’t belong to any class. Functions are defined in a file and may be either global to your program or local to the file in which they are defined*. Like Java methods, C functionsLike Java methods, C functions –Have a name –Have a return type –May have parameters –Pass arguments “by value” Unlike Java methods, a function in C is uniquely identified by its name. Therefore, there is no concept of method overloading in C as there is in Java. There can be only one function in a C application.Unlike Java methods, a function in C is uniquely identified by its name. Therefore, there is no concept of method overloading in C as there is in Java. There can be only one main( ) function in a C application. *more on this later

7/28/09 C Function Examples /* returns the average of two integer parameters */ int intAverage( int a, int b ) { return ( (a + b) / 2 ); } /* Simulates dog barking */ void bark (int nrTimes) { int n; for (n = 0; n < nrTimes; n++) printf(“Arf!\n”);}

7/28/09 Function Prototypes A function prototype defines the function’s name, return type, and parameters.A function prototype defines the function’s name, return type, and parameters. For example from the previous slideFor example from the previous slide void bark( int n ); int average( int a, int b ); Before a function may be called, you must provide its prototype (or the function definition itself) so that the C compiler can verify the function is being called correctly.Before a function may be called, you must provide its prototype (or the function definition itself) so that the C compiler can verify the function is being called correctly. (note the semi-colon).

7/28/09 Recursion C functions may be called recursively.C functions may be called recursively. –Typically a function calls itself A properly written recursive function has the following propertiesA properly written recursive function has the following properties –A “base case” - a condition which does NOT make a recursive call because a simple solution exists –A recursive call with a condition (usually a parameter value) that is closer to the base case than the condition (parameter value) of the current function call Each invocation of the function gets its own set of arguments and local variablesEach invocation of the function gets its own set of arguments and local variables

7/28/09 Recursion Example /* print an integer in decimal ** K & R page 87 (may fail on largest negative int) */ #include void printd( int n ) { if ( n < 0 ) { printf( “-” ); n = -n; } if ( n / 10 )/* (n / 10 != 0) -- more than 1 digit */ printd( n / 10 );/* recursive call: n has 1 less digit */ printf( “%c”, n % 10 + ‘0’); /* base case digit */ }

A Simple C Program /* convertTemps.c */ #include /* includes prototype for printf, etc */ typedef double Temperature; /* prototype for CtoF */ Temperature CtoF( Temperature degreesCelsius); int main( ) { int temp; for (temp = 0; temp < 100; temp += 20) printf(“%2d degrees F = %5.2f degrees C\n”, temp, CtoF( temp )); return 0; } /* converts temperature in Celsius to Fahrenheit */ Temperature CtoF(Temperature celsius) { Temperature fahrenheit; fahrenheit = 9.0 / 5.0 * celsius + 32; return fahrenheit; }

7/28/09 Typical C Program includes #include typedef double Temperature; Temperature CtoF( Temperature celcius); int main( ) { int temp; for (temp = 0; temp < 100; temp += 20) printf(“%2d degrees F = %5.2f degrees C\n”, temp, CtoF( temp )); return 0; } /* converts temperature in Celsius to Fahrenheit */ Temperature CtoF(Temperature celsius) { Temperature fahrenheit; fahrenheit = 9.0 / 5.0 * celsius + 32; return fahrenheit; } defines, typedefs, data type definitions, global variable declarations function prototypes function definitions main()

7/28/09 Compiling on Unix Traditionally the name of the C compiler that comes with Unix is “ cc ”. On the UMBC GL systems, use the GNU compiler named “”. On the UMBC GL systems, use the GNU compiler named “ gcc ”. The default name of the executable program that is created is The default name of the executable program that is created is a.out unix> unix> gcc convertTemps.c

1/13/10 Compiler Options -c-c –Compile only (create a.o file), don’t link (create an executable) gcc -c convertTemps.c -o filename-o filename gcc -o project1 convertTemps.c –Name the executable “filename” instead of a.out gcc -o project1 convertTemps.c -Wall-Wall gcc -Wall convertTemps.c –Report all warnings gcc -Wall convertTemps.c -ansi-ansi gcc -ansi convertTemps –Force adherence to the C ANSI standards gcc -ansi convertTemps Use them togetherUse them together gcc -ansi -Wall -o project1 convertTemps.c

7/28/09 Header Files When a file contains functions to be reused in several programs, their prototypes and important are usually placed into a header ( ) that is then #included where needed.When a file contains functions to be reused in several programs, their prototypes and important #defines are usually placed into a header (.h ) that is then #included where needed. Each file should be “stand alone”. That is, it should and #s needed by the prototypes and any files it needs to avoid compiler errors.Each.h file should be “stand alone”. That is, it should and # define s needed by the prototypes and #include any.h files it needs to avoid compiler errors. In this example, the prototype for would be placed into the file which would then be #included in convertTemps.c or any other file that usedIn this example, the prototype for CtoF() would be placed into the file CtoF.h which would then be #included in convertTemps.c or any other.c file that used CtoF( ) The code for would be placed intThe code for CtoF( ) would be placed int CtoF.c

7/28/09 CtoF.h /* CtoF.h */ /* #includes needed by prototypes */ /* relevant #defines */ /* relevant typedefs */ typedef double Temperature; /* prototype for functions defined in CtoF.c */ Temperature CtoF( Temperature celsius );

7/28/09 CtoF.c /* CtoF.c */ /* necessary #includes, #defines */ #include “CtoF.h” /* converts temp in Celsius to Fahrenheit */ Temperature CtoF(Temperature celsius) { Temperature fahrenheit; fahrenheit = 9.0 / 5.0 * celsius + 32; return fahrenheit; }

7/28/09 convertTemps.c revisited #include /* note angle brackets */ #include “CtoF.h”/* note quotes */ int main( ) { int temp; for (temp = 0; temp < 100; temp += 20) printf(“%2d degrees F = %5.2f degrees C\n”, temp, CtoF( temp )); return 0; }

1/20/10 Compiling and linking When a program’s code is separated into multiple files, we must compile each file and then combine the resulting files to create an executable program.When a program’s code is separated into multiple.c files, we must compile each.c file and then combine the resulting.o files to create an executable program. The files may be compiled separately and then linked together. The flag in the first two command tells to “compile only” which results in the creation of (object) files. In the 3 rd command, the presence of extension tells gcc to link the files into an executableThe files may be compiled separately and then linked together. The -c flag in the first two command tells gcc to “compile only” which results in the creation of.o (object) files. In the 3 rd command, the presence of.o extension tells gcc to link the files into an executable gcc -c -Wall -ansi convertTemps.c gcc -c -Wall -ansi CtoF.c gcc -Wall -ansi -o myProgram convertTemps.o CtoF.o Or it can be done all in one stepOr it can be done all in one step –gcc -Wall -ansi -o myProgram convertTemps.c CtoF.c

7/28/09 Java/C Project example Number Theory - a problem about integersNumber Theory - a problem about integers 13/fall09/code/numbertheory.txthttp:// 13/fall09/code/numbertheory.txthttp:// 13/fall09/code/numbertheory.txthttp:// 13/fall09/code/numbertheory.txt