CPSC 441 TUTORIAL – JANUARY 16, 2012 TA: MARYAM ELAHI INTRODUCTION TO C.

Slides:



Advertisements
Similar presentations
Introduction to C++ An object-oriented language Unit - 01.
Advertisements

C++ Introduction.
C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables.
Computer Science 1620 Math Library. Remember this program? suppose that I invest $25000 into a mutual fund that returns 8% per year. Write a program to.
Copyright 2013 – Noah Mendelsohn Compiling C Programs Noah Mendelsohn Tufts University Web:
Chapter 16 Exception Handling. What is Exception Handling? A method of handling errors that informs the user of the problem and prevents the program from.
Threads Relation to processes Threads exist as subsets of processes Threads share memory and state information within a process Switching between threads.
Java Applets:. How Applets differ from application?: They do not use main method but init(), start() and paint() methods of the applet class They can.
Week 4 – Functions Introduction. Functions: Purpose Breaking a large problem into a series of smaller problems is a common problem- solving technique.
第三次小考. #include using namespace std; int aaa(int *ib,int a1,int a2) { int u,v; int m=(a1+a2)/2; if(a1==a2)return ib[a1]; u=aaa(ib,a1,m); cout
Adding Dynamic Content to your Web Site
Software. What Is Software? software –Also called Computer programs –Are a list of instructions –Instructions are called code –CPU performs the instructions.
1 CSSE 332 Course Introduction. Roll Call and Introductions Name (nickname) Name (nickname) Hometown Hometown Local Residence Local Residence Major Major.
Command-line arguments CS 201 Fundamental Structures of Computer Science.
CS 202 Computer Science II Lab Fall 2009 September 17.
Lab2 TA Notes. Set up for Visual C++ New Workspace Win32 Console Application – This runs from a command line Chose Blank Project Add your.C file Build.
General Computer Science for Engineers CISC 106 Lecture 26 Dr. John Cavazos Computer and Information Sciences 04/24/2009.
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.
COMPUTER PROGRAMMING. Introduction to C++ History Merges notions from Smalltalk and notions from C The class concept was borrowed from Simular67 Developed.
CPSC 441 Tutorial TA: Fang Wang Introduction to C.
Intro. to Game Programming Want to program a game?
University of Calgary – CPSC 441. C PROGRAM  Collection of functions  One function “main()” is called by the operating system as the starting function.
1 EMT 101 – Engineering Programming Dr. Farzad Ismail School of Aerospace Engineering Universiti Sains Malaysia Nibong Tebal Pulau Pinang Week 1.
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.
Rutgers University Excellence Campaign 2/20/2004 Java Native Interface Tutorial Xiaolin Li Rutgers.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Creating your first C++ program
ITEC 320 C++ Examples.
Multiple Files. Monolithic vs Modular  one file before  system includes  main driver function  prototypes  function.
1 Programming in C Hello World! Soon I will control the world! Soon I will control the world!
C/C++ Programming Environment
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
1 Original Source : and Problem and Problem Solving.ppt.
CS-1030 Dr. Mark L. Hornick 1 Java Review Interactive.
1 A simple C++ program // ======================================================= // File:helloworld.cpp // Author:Vana Doufexi // Date:1/4/2006 // Description:Displays.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 05, 2005 Lecture Number: 4.
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Functions & Pointers in C Jordan Erenrich
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Java and C++ Transitioning. A simple example public class HelloWorldApp { public static void main(String[] args) { //Display the string. System.out.println("Hello.
CSE 1341 Honors Note Set 2 1. Overview  Java vs. C++  Functions in C++  First Programming Packet  Development Environment 2.
C is a high level language (HLL)
Chapter 2 Creating a C++ Program. Elements of a C++ Program Four basic ways of structuring a program Four basic ways of structuring a program 1.Sequencing.
1 Structure of Simple C++ Program Chapter 1 09/09/13.
1 8/30/06CS150 Introduction to Computer Science 1 Your First C++ Program.
Software Engineering Algorithms, Compilers, & Lifecycle.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
CPSC 233 Tutorial January 21 st /22 nd, Linux Commands.
Tutorial 1 Writing Your First C++ Program CSC1110C Introduction to Computer Programming By Paul Pun Acknowledgement: Special thanks to Dr. Michael Fung.
Program Execution in Linux David Ferry, Chris Gill CSE 522S - Advanced Operating Systems Washington University in St. Louis St. Louis, MO
1 CS 192 Lecture 4 Winter 2003 December 8-9, 2003 Dr. Shafay Shamail.
Lecture 3: Getting Started & Input / Output (I/O)
KYC - Know your compiler Introduction to GCC
Command Line Arguments
Command Line Arguments
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.
Day 01 Introduction to Linux and C
Program Execution in Linux
Quick Start Guide for Visual Studio 2010
C Stuff CS 2308.
Code::Block vs Visual 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.
Program Execution in Linux
Functions Imran Rashid CTO at ManiWeber Technologies.
Introduction to Algorithms and Programming COMP151
Makefile Assignment Create a file called f1.cpp. It should contain the following function: int squareIt ( int x ) { //insert code to calc and return the.
ENERGY 211 / CME 211 Lecture 29 December 3, 2008.
SPL – PS1 Introduction to C++.
Presentation transcript:

CPSC 441 TUTORIAL – JANUARY 16, 2012 TA: MARYAM ELAHI INTRODUCTION TO C

C VS. JAVA C program Collection of functions One function “main()” is called by the operating system as the starting function Compile output: executable file. Running the executable (default name a.out) starts main function Typically, single program with all user code linked in – but can be dynamic libraries (.dll,.so) Java program Collection of classes Class containing main method is starting class Compile output: jar file. Running “java StartClass” invokes StartClass.main method JVM loads other classes as required C++ is C extended with object oriented functionality (and more!) 2

// C #include int main(int argc, char *argv[])) { printf("Hello world!\n"); return 0; } // C++ #include using namespace std; int main(int argc, char *argv[]) { cout << "Hello world!" << endl; return 0; } SIMPLE C/C++ EXAMPLE 3

COMPILING C gcc invokes C compiler gcc translates C program into executable for some target default file name a.out Example: compile and run hello.c 4 $ gcc hello.c $ a.out Hello, World! $ gcc hello.c –o hello $./hello Hello, World!

COMPILING C++ To compile C++, use g++ Example: compile and run hello.c 5 $ g++ hello.c $ a.out Hello, World! $ g++ hello.c –o hello $./hello Hello, World!

HANDS ON Demo: 1. Write code 2. Compile 3. Run 6

SOME OPTIONS Some useful command line options: [-o file]: specifies the output file for object or executable [-Wall]: show all warnings (highly recommended) [-l libnam]: Links the library libname, e.g., -lsocket If you get errors saying the library cannot be found, make sure the path is correctly set, and you do have the libraries you need. 7

MAIN ARGUMENTS int main(int argc, char *argv[]) argc: number of arguments passed to the program argv: array of strings showing command line arguments Name of executable + space-separated arguments Name of executable is stored in argv[0] The return value is int convention: 0 means success, > 0 some error 8

PASSING ARGUMENTS EXAMPLE 9

PRIMITIVE DATA TYPES 10 NameDescriptionSize* (32bit)Range* (32bit system) char Character or small integer.1byte signed: -128 to 127 unsigned: 0 to 255 short int (short) Short Integer.2bytes signed: to unsigned: 0 to int Integer.4bytes signed: to unsigned: 0 to long int (long) Long integer.4bytes signed: to unsigned: 0 to bool Boolean value. It can take one of two values: true or false. 1byte true or false float Floating point number.4bytes +/- 3.4e +/- 38 (~7 digits) double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits) long double Long double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits) *Size and Range depend on the system the program is compiled for. From:

TYPECASTING EXAMPLE 11 Caution: be careful with typecasting, especially implicit conversions.

ARRAYS Array declaration: int a[]; C/C++ arrays have no length attribute! Note: when passing an array to a function, typically you have to pass the array size as a separate argument as well. You have to take care of array bounds yourself int input[10]; input[10] = 20; // out of bound! input[-1] = 5; // out of bound! This code could compile and run, but most likely, you’ll see unexpected behavior or crash your program. Array’s name is a pointer to its first element 12

STRUCTURES C struct is a way to logically group related types Is very similar to (but not same as) C++/java classes Is somehow a class without methods Members are always public (no encapsulation concept in c) A struct component can be of any type (including other struct types), but cannot be recursive Example: 13 struct student{ char* name; unsigned int ID; struct Address; }; struct address{ char* street; char* city; char* zip; };

POINTERS A pointer is just an address to some memory location. Another variable Some dynamically allocated memory Some function NULL 14 &x (address of x) 4 int *p = &x; int x = 4; Address of allocated memory int *p = malloc (sizeof int); ? allocated memory

POINTERS IN C Declaration: using “ * ” symbol before variable name. int * ptr = NULL; //creates pointer to integer Allocation: allocate new memory to a pointer using the keyword malloc in C ( new in C++) int *p = malloc(sizeof(int)); int *p = (int *) malloc(10 * sizeof (int)); // array of int Deallocation: clear the allocated memory when you are done using it. Otherwise, Memory Leak!!! free(p); Dereferencing: accessing data from the pointer x = *p; 15

STRING In C, string is an array of char terminated with “\0” (a null terminator: ‘\0’) “hello” = hello\0 Declaring and initialize a string char str1[10]; // a string of 10 characters char str2[10]={“hello”}; //initialized string char *strp1; // a char pointer char *strp2 = malloc(sizeof(char)*10); // a char pointer initialized to point to a chunck of memory. 16

STRING LIBRARY #include Functions: char *strcpy(char *dest, char *source) copies chars from source array into dest array up to NUL char *strncpy(char *dest, char *source, int num) copies chars; stops after num chars if no NUL before that; appends NUL int strlen(const char *source) returns number of chars, excluding NUL char *strchr(const char *source, const char ch) returns pointer to first occurrence of ch in source; NUL if none char *strstr(const char *source, const char *search) return pointer to first occurrence of search in source 17

FORMATTED STRINGS int sscanf(char *string, char *format,...) parse the contents of string according to format return the number of successful conversions int sprintf(char *buffer, char *format,...) produce a string formatted according to format directives and place this string into the buffer return number of successful conversions 18

FORMATTED STRINGS 19 Formatting codes for sscanf Codemeaningvariable %c matches a single characterchar %d matches an integer in decimalint %f matches a real number (ddd.dd)float %s matches a string up to white spacechar * %[^c] matches string up to next c charchar *

FORMATTED STRINGS 20 Formatting codes for sprintf Values normally right-justified; use negative field width to get left-justified Codemeaningvariable %nc%nc char in field of n spaceschar %nd%nd integer in field of n spacesint, long %n.mf%n.mf real number in width n, m decimals float, double %n.mg%n.mg real number in width n, m digits of precision float, double %n.ms%n.ms first m chars from string in width nchar *

21 STANDARD C LIBRARY #include Formatted I/O int scan f(const char *format,...) read from standard input and store according to format. int printf(const char *format,...) write to standard output according to format File I/O: FILE * FILE *fopen(const char *path, const char *mode) open a file and return the file descriptor int fclose(FILE *stream) close the file; return 0 if successful, EOF if not

STANDARD C LIBRARY #include Other I/O operations: int getchar() read the next character from stdin; returns EOF if none char *fgets(char *buf, int size, FILE *in) read the next line from a file into buf int fputs(const char *str, FILE *out) output the string to a file, stopping at ‘\0’ returns number of characters written or EOF 22

LETS WRITE SOME CODE! Sample C program: Input: list of grades of student homework. Output: The computed final marks. 23

REFERENCES C for Java programmers: C tutorial: Socket programming with C: (for next session) Beej's Guide to Network Programming Using Internet Sockets