A Guide to Unix Using Linux Fourth Edition

Slides:



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

COSC 120 Computer Programming
Structure of a C program
Your First C++ Program Aug 27, /27/08 CS 150 Introduction to Computer Science I C++  Based on the C programming language  One of today’s most.
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.
Three types of computer languages
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
If You Missed Last Week Go to Click on Syllabus, review lecture 01 notes, course schedule Contact your TA ( on website) Schedule.
1 Key Concepts:  Why C?  Life Cycle Of a C program,  What is a computer program?  A program statement?  Basic parts of a C program,  Printf() function?
CS31: Introduction to Computer Science I Discussion 1A 4/2/2010 Sungwon Yang
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
CS100A, Fall 1997, Lectures 221 CS100A, Fall 1997 Lecture 22, Tuesday 18 November Introduction To C Goal: Acquire a reading knowledge of basic C. Concepts:
1 ICS103 Programming in C Lecture 2: Introduction to C (1)
Guide To UNIX Using Linux Third Edition
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 1 Introduction.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Basic Elements of C++ Chapter 2.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Copyright 2003 Scott/Jones Publishing Brief Version of Starting Out with C++, 4th Edition Chapter 1 Introduction to Computers and Programming.
Computer Science 210 Computer Organization Introduction to C.
Chapter Introduction to Computers and Programming 1.
COMPUTER SCIENCE I C++ INTRODUCTION
High-Level Programming Languages: C++
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
Goals of Course Introduction to the programming language C Learn how to program Learn ‘good’ programming practices.
Introduction to C++ Systems Programming. Systems Programming: Introduction to C++ 2 Systems Programming: 2 Introduction to C++  Syntax differences between.
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
History of C 1950 – FORTRAN (Formula Translator) 1959 – COBOL (Common Business Oriented Language) 1971 – Pascal Between Ada.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
1 C++ Syntax and Semantics, and the Program Development Process.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Programming Fundamentals. Today’s Lecture Why do we need Object Oriented Language C++ and C Basics of a typical C++ Environment Basic Program Construction.
C++ Programming: Basic Elements of C++.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
THE BASICS OF A C++ PROGRAM EDP 4 / MATH 23 TTH 5:45 – 7:15.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
An overview of C Language. Overview of C C language is a general purpose and structured programming language developed by 'Dennis Ritchie' at AT &T's.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
1 8/30/06CS150 Introduction to Computer Science 1 Your First C++ Program.
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 2: Basic Elements of C++
Chapter 15 - C++ As A "Better C"
Chapter 1.2 Introduction to C++ Programming
Chapter 2: Basic Elements of C++
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
Computer Science 210 Computer Organization
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Introduction to C++ Systems Programming.
Computing Fundamentals
Basic Elements of C++.
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Basic Elements of C++ Chapter 2.
Computer Science 210 Computer Organization
2.1 Parts of a C++ Program.
Govt. Polytechnic,Dhangar
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Chapter 2: Introduction to C++.
C programming Language
Engineering Problem Solving with C++ An Object Based Approach
C – Programming Language
Presentation transcript:

A Guide to Unix Using Linux Fourth Edition Chapter 10 Developing UNIX/Linux Applications in C and C++

Objectives Understand basic elements of C programming Debug C programs Create, compile, and test C programs Use the make utility to revise and maintain source files A Guide to Unix Using Linux, Fourth Edition

Objectives (continued) Identify differences between C and C++ programming Create a simple C++ program Create a C++ program that reads a text file Create a C++ program that demonstrates how C++ enhances C functions A Guide to Unix Using Linux, Fourth Edition

Introducing C Programming Unix was developed and refined in the C language Original UNIX OS was written in assembly language Assembly language: low-level language; provides maximum access to all the computer’s devices Ritchie and Kernighan from AT&T Bell Labs rewrote most of UNIX using C in early 1970s C is native to UNIX/Linux Works best as an application development tool Example: daemons are written in C C is a compiled language A Guide to Unix Using Linux, Fourth Edition

Creating a C Program A Guide to Unix Using Linux, Fourth Edition

C Keywords Keywords have special meanings Cannot be used as names for variables or functions A Guide to Unix Using Linux, Fourth Edition

The C Library The C language is very small No input or output facilities All I/O is performed through the C library C library: consists of functions that perform file, screen, and keyboard operations Other tasks: functions to perform string operations, memory allocation, control, etc. To perform one of these operations in program, place a function call Linker joins code of library function with program’s object code to create executable file A Guide to Unix Using Linux, Fourth Edition

Program Format C programs are made up of one or more functions Every function must have a name Every C program must have a main() function: int main() { } A Guide to Unix Using Linux, Fourth Edition

Including Comments /* denotes the beginning of a comment */ denotes the end of a comment Compiler ignores everything between the symbols: /* Here is a program that does nothing. */ int main() { } A Guide to Unix Using Linux, Fourth Edition

Using the Preprocessor #include Directive The following program creates output: /* A simple C program */ #include <stdio.h> int main() { printf("C is a programming language.\n"); printf("C is very compatible with UNIX/Linux.\n"); } stdio.h is a header file A preprocessor directive A Guide to Unix Using Linux, Fourth Edition

Using the Preprocessor #include Directive (continued) A Guide to Unix Using Linux, Fourth Edition

Specifying Data Types Variables and constants represent data used in a C program You must declare variables and state type of data that variable can hold A variable’s data type determines upper and lower limits of its range of values Exact limits of ranges vary among compilers and hardware platforms A Guide to Unix Using Linux, Fourth Edition

Specifying Data Types (continued) A Guide to Unix Using Linux, Fourth Edition

Character Constants Characters are represented internally in a single byte of the computer’s memory Stored according to the character’s code in the host character set Example: if machine uses ASCII codes, letter A is stored in memory as the number 65 In a program, a character constant must be enclosed in single quotation marks ‘A’ ‘c’ A Guide to Unix Using Linux, Fourth Edition

Using Strings A string is a group of characters, such as a name Strings are stored in memory in consecutive memory locations String constants are enclosed in double quotation marks "Linux is a great operating system." C does not provide a data type for character strings Use a character array instead: char name[20]; Can hold a string of 19 characters, terminated with the null character A Guide to Unix Using Linux, Fourth Edition

Including Identifiers Identifiers are names given to variables and functions First character must be a letter or an underscore For other characters, use letters, underscores, or digits Variable names can be limited to 31 characters Some compilers require first eight characters to be unique Uppercase and lowercase characters are distinct Tip: use meaningful identifiers Examples: radius, customer_name, my_name A Guide to Unix Using Linux, Fourth Edition

Declaring Variables You must declare all variables before you use them in a program int days; You can declare multiple variables of the same type on the same line int days, months, years; You can initialize variables with values at the time they are declared int days = 5, months = 2, years = 10; A Guide to Unix Using Linux, Fourth Edition

Understanding the Scope of Variables Scope of a variable: part of the program in which the variable is defined and accessible /* This program declares a local variable in function main. The program does nothing else. */ int main() { int days; } An automatic variable /* This program declares a global variable The program does nothing else. */ int days; int main() { } A global or external variable A Guide to Unix Using Linux, Fourth Edition

Using Math Operators Example: x = y + 3; Increment and decrement operators are unary Examples: count--; or x = ++j; A Guide to Unix Using Linux, Fourth Edition

Generating Formatted Output with printf() Examples: printf("Hello"); printf("Your age is %d", 30); printf("Your age is %d", age); printf("The values are %d %d", num1, num2); printf("You have worked %d minutes", hours*60); A Guide to Unix Using Linux, Fourth Edition

Generating Formatted Output with printf() (continued) A Guide to Unix Using Linux, Fourth Edition

Using the C Compiler A Guide to Unix Using Linux, Fourth Edition

Using the if Statement Example: if (weight > 1000) { printf("Warning!\n"); printf("You have exceeded the limit.\n"); printf("Please remove some weight.\n"); } A Guide to Unix Using Linux, Fourth Edition

Using the if Statement (continued) if-else construct allows program to do one thing if a condition is true and another if it is false Example: if (hours > 40) printf("You can go home now."); else printf("Keep working!"); A Guide to Unix Using Linux, Fourth Edition

Using C Loops Three looping mechanisms in C: for loop while loop for (count = 0; count < 100; count++) printf("Hello\n"); while loop x = 0; while (x++ < 100) printf("x is equal to %d\n", x); do-while loop do while (x++ < 100); A Guide to Unix Using Linux, Fourth Edition

Defining Functions To define a function, declare its name and create the function’s block of code #include <stdio.h> void message(); int main() { message(); } void message() printf("Greetings from the function message."); printf("Have a nice day."); [stephen@localhost ~] $ ./func1 Greetings from the function message. Have a nice day. Function prototype This function does not return a value A Guide to Unix Using Linux, Fourth Edition

Using Function Arguments Argument: a value passed to a function Stored in special automatic variables #include <stdio.h> void print_square(int val) main() { int num = 5; print_square(num); } printf("\nThe square is %d\n", val*val); [stephen@localhost ~]$ ./func2 The square is 25 A Guide to Unix Using Linux, Fourth Edition

Using Function Return Values #include <stdio.h> int triple(int num); int main() { int x = 6, y; y = triple(x); printf("%d tripled is %d.\n", x, y); } int triple(int num) return (num * 3); [stephen@localhost ~]$ ./func3 6 tripled is 18. A Guide to Unix Using Linux, Fourth Edition

Working with Files in C C file input/output is designed to use file pointers FILE *fp; Before you can use a file, it must be opened if ((fp = fopen("myfile.dat", "r")) == NULL) { printf("Error opening myfile.dat\n"); } When a file is closed, its buffers are flushed if (feof(fp)) fclose(fp); C provides many functions for reading/writing files ch = fgetc(fp); fputc(ch, fp); A Guide to Unix Using Linux, Fourth Edition

Using the make Utility to Maintain Program Source Files You might often work with a program that has many files of source code Advantage: break down code into smaller modules that can be reused Problem: avoid recompiling all files if only one changed make utility tracks what needs to be recompiled by using a time stamp field for each source file Must create a control file called makefile Must exist in current directory A Guide to Unix Using Linux, Fourth Edition

Using the make Utility to Maintain Program Source Files (continued) Example of a makefile: abs_main.o: abs_main.c gcc -c abs_main.c abs_func.o: abs_func.c gcc -c abs_func.c abs2: abs_main.o abs_func.o gcc abs_main.o abs_func.o -o abs2 A Guide to Unix Using Linux, Fourth Edition

Using the make Utility to Maintain Program Source Files (continued) A Guide to Unix Using Linux, Fourth Edition

Debugging Your Program Typical errors for new C programmers include using incorrect syntax Example: forgetting to terminate a statement with a semicolon (;) Example of a compiler error output: simple.c:10: unterminated string or character constant simple.c:10: possible real start of unterminated constant simple.c:4:10: missing terminating " character simple.c:5: error: syntax error before ’}’ token Compiler generally produces more error lines than the number of mistakes it finds in the code A Guide to Unix Using Linux, Fourth Edition

Debugging Your Program (continued) Steps to correct syntax errors within your programs: Write down the line number of each error and a brief description Edit your source file Start with the first line number the compiler reports Within the source file, correct the error Then, continue with the next line number After correcting errors, save and recompile A Guide to Unix Using Linux, Fourth Edition

Creating a C Program to Accept Input A Guide to Unix Using Linux, Fourth Edition

Creating a C Program to Accept Input (continued) Examples: scanf("%d", &age); scanf("%s", city); scanf("%d %f %d", &x, &y, &z); A Guide to Unix Using Linux, Fourth Edition

Introducing C++ Programming C++ is a programming language developed by Bjarne Stroustrup at AT&T Bell Labs Adds object-oriented programming capabilities Object-oriented programming uses objects for handling data C++ programs introduce objects as a new data class Object: collection of data and methods, which manipulate the data Function overloading is an additional useful feature Compiler: g++ Example: g++ myprogram.C -o myprogram Typical file extensions: .C or .cpp A Guide to Unix Using Linux, Fourth Edition

Creating a Simple C++ Program //====================================================== // Program Name: simple.C // By: MP // Purpose: First program in C++ showing how to // produce output #include <iostream> using namespace std; int main(void) { cout << "C++ is a programming language.\n"; cout << "Like C, C++ is compatible with UNIX/Linux.\n"; } A Guide to Unix Using Linux, Fourth Edition

Creating a C++ Program that Reads a Text File //====================================================== // Program Name: fileread.C // By: MP // Purpose: C++ program that reads contents of a file #include <iostream> #include <fstream> using namespace std; int main(void) { ifstream file("testfile"); char record_in[256]; if (file.fail()) cout << "Error opening file.\n"; else while (!file.eof()) file.getline(record_in, sizeof(record_in)); if (file.good()) cout << record_in << endl; } A Guide to Unix Using Linux, Fourth Edition

How C++ Enhances C Functions //====================================================== // Program Name: datestuf.C // By: MP // Purpose: Shows you two ways to access the // system date #include <iostream> #include <ctime> using namespace std; void display_time(const struct tm *tim) { cout << "1. It is now " << asctime(tim); } void display_time(const time_t *tim) cout << "2. It is now " << ctime(tim); int main(void) time_t tim = time(NULL); struct tm *ltim = localtime(&tim); display_time(ltim); display_time(&tim); A Guide to Unix Using Linux, Fourth Edition

Summary C program modules are compiled separately into object code and linked to make up a program C programs first execute instructions in main() make is used to maintain an application’s source files C follows procedural principles, while C++ primarily follows object-oriented programming principles The standard stream library used by C++ is iostream C++ provides two statements for standard input and standard output: cin and cout, respectively Function overloading allows functions to handle multiple sets of criteria A Guide to Unix Using Linux, Fourth Edition

Command Summary A Guide to Unix Using Linux, Fourth Edition