Programming in C Variables, Controls, Arrays, Functions.

Slides:



Advertisements
Similar presentations
Variables in C Amir Haider Lecturer.
Advertisements

Chapter 10 C Structures, Unions, Bit Manipulations and Enumerations Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
IT 325 OPERATING SYSTEM C programming language. Why use C instead of Java Intermediate-level language:  Low-level features like bit operations  High-level.
Enumerated data type & typedef. Enumerated Data Type An enumeration consists of a set of named integer constants. An enumeration type declaration gives.
ENUMERATED, typedef. ENUMERATED DATA TYPES An enumeration consists of a set of named integer constants. An enumeration type declaration gives the name.
Introduction to C Programming CE Lecture 1 Introduction to C.
Structure of a C program
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
0 Chap. 2. Types, Operators, and Expressions 2.1Variable Names 2.2Data Types and Sizes 2.3Constants 2.4Declarations Imperative Programming, B. Hirsbrunner,
Guide To UNIX Using Linux Third Edition
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
An Introduction to C Programming Geb Thomas. Learning Objectives Learn how to write and compile a C program Learn what C libraries are Understand the.
Multidimensional Arrays C++ also allows an array to have more than one dimension. For example, a two-dimensional array consists of a certain number of.
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.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Programming Functions Macros. Functions vs. Methods Java classes include methods which can be called from any code with appropriate access (recall public.
Language Elements 1. Data Types 2 Floating Point (real) Single Precision Double Precision Decimal Fixed Point (integer) Byte Short Integer Long Numerical.
Programming With C.
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.
Programming in C Structs and Unions. Java vs C Suppose you were assigned a write an application about points and straight lines in a coordinate plane.
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",
CIS-165 C++ Programming I CIS-165 C++ Programming I Bergen Community College Prof. Faisal Aljamal.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
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 Programming
 2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 5P. 1Winter Quarter C Programming Basics Lecture 5.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
Chapter 4 Literals, Variables and Constants. #Page2 4.1 Literals Any numeric literal starting with 0x specifies that the following is a hexadecimal value.
Chapter 7 C supports two fundamentally different kinds of numeric types: (a) integer types - whole numbers (1) signed (2) unsigned (b) floating types –
Programming in C Variables, Controls, Functions. 7/28/09 Different Kinds of Languages  Java is an object-oriented programming (OOP) language  Problem.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
C Part 1 Computer Organization I 1 August 2009 © McQuain, Feng & Ribbens A History Lesson Development of language by Dennis Ritchie at Bell.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
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.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
The Machine Model Memory
Computer Science 210 Computer Organization
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
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.
C Basics.
Introduction to C Programming Language
Computer Science 210 Computer Organization
Introduction to the C Language
C Structures, Unions, Bit Manipulations and Enumerations
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 2: Introduction to C++.
Introduction to C Topics Compilation Using the gcc Compiler
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
Module 2 Variables, Data Types and Arithmetic
C Language B. DHIVYA 17PCA140 II MCA.
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C Programming
Presentation transcript:

Programming in C Variables, Controls, Arrays, 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 The C Standard The first standard for C was published by the American National Standards Institute (ANSI) in 1989 and is widely referred to as “ANSI C” (or sometimes C89)The first standard for C was published by the American National Standards Institute (ANSI) in 1989 and is widely referred to as “ANSI C” (or sometimes C89) A slightly modified version of the ANSI C standard was adopted in 1990 and is referred to as “C90”. “C89" and "C90" refer to essentially the same language.A slightly modified version of the ANSI C standard was adopted in 1990 and is referred to as “C90”. “C89" and "C90" refer to essentially the same language. In March 2000, ANSI adopted the ISO/IEC 9899:1999 standard. This standard is commonly referred to as C99, and it is the current standard for the C programming language.In March 2000, ANSI adopted the ISO/IEC 9899:1999 standard. This standard is commonly referred to as C99, and it is the current standard for the C programming language. The C99 standard is not fully implemented in all versions of C compilers.The C99 standard is not fully implemented in all versions of C compilers.

7/28/09 C99 on GL The GNU C compiler on the GL systems (gcc version 4.1.2) appears to support several useful C99 features.The GNU C compiler on the GL systems (gcc version 4.1.2) appears to support several useful C99 features. These notes include those C99 features supported by gcc on GL since our course use that compiler.These notes include those C99 features supported by gcc on GL since our course use that compiler. These features will be noted as C99 features when presented.These features will be noted as C99 features when presented.

7/27/10 Hello World This source code is in a file such as hello.c /* file header block comment */ #include #include int main( ) { // print the greeing ( C99 ) printf( “Hello World\n”); return 0; }

7/28/09 Compiling on Unix Traditionally the name of the C compiler that comes with Unix is “”. Traditionally the name of the C compiler that comes with Unix is “ cc ”. The UMBC GL systems use the “GNU Compiler Collection” named “” for compiling C (and C++) programs. The UMBC GL systems use the “GNU Compiler Collection” named “ gcc ” for compiling C (and C++) programs. The default name of the executable program that is created by is The default name of the executable program that is created by gcc is a.out unix> unix> gcc hello.c

1/13/10 Compiler Options -c-c –Compile only (create a.o file), don’t link (create an executable) gcc -c hello.c -o filename-o filename gcc -o hello hello.c –Name the executable filename instead of a.out gcc -o hello hello.c -Wall-Wall gcc -Wall hello.c –Report all warnings gcc -Wall hello.c Use them togetherUse them together gcc -Wall -o hello hello.c Note: the -ansi switch enforces the original ANSI C standard and disables C99 features.Note: the -ansi switch enforces the original ANSI C standard and disables C99 features.

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 -Wall -o hello hello.c Execute your program by typing the name of the executable at the Unix prompt 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 We assume that you are proficient in JavaWe assume that you are proficient in Java

7/26/10 Integral Data Types C data types for storing integer values areC data types for storing integer values are –int (the basic integer data type) –short int (typically abbreviated just as short ) –long int (typically abbreviated just as long ) –long long int (C99) –char (C does not have “ by t e ”) should be used unless there’s a very good reason to use one of the othersint should be used unless there’s a very good reason to use one of the others is stored in 1 bytechar is stored in 1 byte The number of bytes used by the other types depends on the machine being usedThe number of bytes used by the other types depends on the machine being used

7/27/10 Integral Type Sizes The C standard is specifically vague regarding the size of the integral typesThe C standard is specifically vague regarding the size of the integral types –A short int must not be larger than an int. –An int must not be larger than a long int. –A short int must be at least 16 bits long. –An int must be at least 16 bits long. –A long int must be at least 32 bits long. –A long long int must be at least 64 bits long. The standard does not require that any of these sizes be necessarily different.The standard does not require that any of these sizes be necessarily different.

7/26/10 Integral Specifiers Each of the integral types may be specified as eitherEach of the integral types may be specified as either –signed (positive, negative, or zero) –unsigned (positive or zero only) is the default qualifiersigned is the default qualifier Much more on this laterMuch more on this later

7/28/09 Integral Variables Each of the following is a valid variable declarationEach of the following is a valid variable declaration int age = 42; signed int age = -33; long area = ; short int height = 4; unsigned char IQ = 102; unsigned int length = 8282; unsigned long int SATscore = 800;

7/26/10 Floating Point Data Types C data types for storing floating point values (those with a decimal part) areC data types for storing floating point values (those with a decimal part) are –float, the smallest floating point type –double, a larger type with a larger range of values –long double, an even larger type with an even large range of values is typically used for all floating point values unless there’s a compelling need to use one of the othersdouble is typically used for all floating point values unless there’s a compelling need to use one of the others Floating point variables may store integer valuesFloating point variables may store integer values

7/28/09 Size of Floating Point Type A variable can be marked as being a, which the compiler may use to select a larger floating point representation than a plain.A double variable can be marked as being a long double, which the compiler may use to select a larger floating point representation than a plain double. The standard is unspecific on the relative sizes of the floating point values, and only requires a not to be larger than a, which should not be than a.The standard is unspecific on the relative sizes of the floating point values, and only requires a float not to be larger than a double, which should not be larger than a long double.

7/28/09 Floating Point Declarations Each of the following is a valid floating point variable declarationEach of the following is a valid floating point variable declaration float avg = 10.6; double median = 88.54; double homeCost = 10000;

7/28/09 Character Data Types C has just one data type for storing charactersC has just one data type for storing characters –char, which is just one byte Because a is just one byte, C only supports the ASCII character set (more on this later)Because a char is just one byte, C only supports the ASCII character set (more on this later)

sizeof( ) Because the sizes (number of bits/bytes) of the C data types are vaguely specified, C provides the operator to determine the size of any data type (in bytes).Because the sizes (number of bits/bytes) of the C data types are vaguely specified, C provides the sizeof( ) operator to determine the size of any data type (in bytes). should be used everywhere the size of a data type is required so that your code is portable to other hardware on which the size of the data types may be different.sizeof( ) should be used everywhere the size of a data type is required so that your code is portable to other hardware on which the size of the data types may be different. On GL, On GL, –sizeof( short ) = 2 –sizeof( int ) = sizeof( long ) = 4 –sizeof (long long) = 8 –sizeof( float ) = 4 –sizeof( double ) = 8

7/28/09 const Qualifier Any of the variable types found above may be qualified as.Any of the variable types found above may be qualified as const. variables may not be modified by your code. Any attempt to do so will result in a compiler error.const variables may not be modified by your code. Any attempt to do so will result in a compiler error. Since they may not be modified, variables must be initialized when declaredSince they may not be modified, const variables must be initialized when declared const double PI = ; const int myAge = 39;

7/28/09 Variable Declaration ANSI C requires that all variables be declared at the beginning of the “block” in which they are defined, before any executable line of code.ANSI C requires that all variables be declared at the beginning of the “block” in which they are defined, before any executable line of code. C99 allows variables to be declared anywhere in the code (like Java and C++)C99 allows variables to be declared anywhere in the code (like Java and C++) In any case, variables must be declared before they can be used.In any case, variables must be declared before they can be used.

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 Boolean Data Type ANSI C has no Boolean typeANSI C has no Boolean type The C99 standard supports the Boolean data typeThe C99 standard supports the Boolean data type To use,, and, your code must includeTo use bool, true, and false, your code must include #include bool isRaining = false; if ( isRaining ) printf( “Bring your umbrella\n”);

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) Integral types may also be treated as Boolean expressionsIntegral types may also be treated as Boolean expressions –Zero is considered “false” –Any non-zero value is considered “true”  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

7/28/09 Arrays Like most languages, C supports arrays as a basic data structure.Like most languages, C supports arrays as a basic data structure. Array indexing starts with 0.Array indexing starts with 0. ANSI C requires that the size of the array be a constant (if specified)ANSI C requires that the size of the array be a constant (if specified) Declaring and initializing arraysDeclaring and initializing arrays int grades[44]; int areas[10] = {1, 2, 3}; long widths[12] = {0}; int IQs[ ] = {120, 121, 99, 154};

7/28/09 Variable Size Arrays C99 allows the size of an array to be a variableC99 allows the size of an array to be a variable int nrStudents = 30;... int grades[nrStudents];

7/28/09 2-D Arrays Like most languages, C supports multi- dimensional arrayLike most languages, C supports multi- dimensional array Subscripting is provided for each dimensionSubscripting is provided for each dimension For 2-d arrays, the first dimension is the number of “rows”, the second is the number of “columns” in each rowFor 2-d arrays, the first dimension is the number of “rows”, the second is the number of “columns” in each row int board[ 4 ] [ 5 ]; // 4 rows, 5 columns int x = board[ 0 ][ 0 ];// 1 st row, 1 st column int y = board[ 3 ][ 4 ];// 4 th (last) row, 5 th (last) column

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’s preprocessor replaces every instance of the name with the text that it represents.The compiler’s preprocessor 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 PI double area = PI * radius * radius;...

7/28/09 #define vs const #define#define –Pro: no memory is used for the constant –Con: cannot be seen when code is compiled since they are removed by the pre-compiler –Con: are not real variables and have no type const variablesconst variables –Pro: are real variables with a type –Pro: can be examined by a debugger –Con: take up memory

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 int[3] Row; Or to give simple names to complex types - more on this laterOr to give simple names to complex types - more on this later Using makes future changes easier and makes the code more relevant to the applicationUsing typedefs 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) Behave like integersBehave like integers Names in must be distinctNames in enum must be distinct Often a better alternative toOften a better alternative to #defines ExampleExample enum months { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };... enum months thisMonth; thisMonth = SEP;// ok thisMonth = 42;// unfortunately, also ok

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 *more on this later

7/28/09 More Functions Before a function may be called, its “prototype” (aka signature -- name and parameters) must be known to the compiler so that it can verify that your code is calling the function correctly.Before a function may be called, its “prototype” (aka signature -- name and parameters) must be known to the compiler so that it can verify that your code is calling the function correctly. This is accomplished in one of two waysThis is accomplished in one of two ways –Provide the entire function definition prior to the calling code –Provide the function prototype prior to the calling code and provide the function definition elsewhere 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. Our standards dictate that function names begin with and UPPERCASE letterOur standards dictate that function names begin with and UPPERCASE letter

7/27/10 A Simple C Program #include typedef double Radius; #define PI /* given the radius, calculates the area of a circle */ double CircleArea( Radius radius ) { return ( PI * radius * radius ); } // given the radius, calcs the circumference of a circle double Circumference( Radius radius ) { return (2 * PI * radius ); } int main( ) { Radius radius = 4.5; double area = circleArea( radius ); double circumference = Circumference( radius ); // print the results return 0; }

7/28/09 Alternate Sample #include typedef double Radius; #define PI /* function prototypes */ double CircleArea( Radius radius ); double Circumference( Radius radius ); int main( ) { Radius radius = 4.5; double area = circleArea( radius ); double circumference = Circumference( radius ); // print the results return 0; } /* given the radius, calculates the area of a circle */ double CircleArea( Radius radius ) { return ( PI * radius * radius ); } // given the radius, calcs the circumference of a circle double Circumference( Radius radius ) { return (2 * PI * radius ); }

7/28/09 Typical C Program includes #include typedef double Radius; #define PI /* function prototypes */ double CircleArea( Radius radius ); double Circumference( Radius radius ); int main( ) { Radius radius = 4.5; double area = circleArea( radius ); double circumference = Circumference( radius ); // print the results return 0; } /* given the radius, calculates the area of a circle */ double CircleArea( Radius radius ) { return ( PI * radius * radius ); } // given the radius, calcs the circumference of a circle double Circumference( Radius radius ) { return (2 * PI * radius ); } defines, typedefs, data type definitions, global variable declarations function prototypes function definitions main()