1 Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa.

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

Programming Languages and Paradigms The C Programming Language.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Debugging What can debuggers do? Run programs Make the program stops on specified places or on specified conditions Give information about current variables’
Miguel Garzon CrUise Lab - SITE. #include dynamic memory allocationdynamic memory allocation Input/output String handlingString handling Mathematical.
11-2 Identify the parts of the “main” function, which include Preprocessor Directives main function header main function body which includes Declaration.
Unix Continuum of Tools Do something once: use the command line Do something many times: –Use an alias –Use a shell script Do something that is complex.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
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.
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
Introduction to C Language
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.
CS140: Intro to CS An Overview of Programming in C by Erin Chambers.
1 Course Lectures Available on line:
1 Unix Editors (ee, ed, ex, vi, vim) and Compilers (g77, gcc) Speaker: Li-Wen Chen Date:
DAT602 Database Application Development Lecture 5 JAVA Review.
SOFTWARE TECHNOLOGY - I CONSTANTS VARIABLES DATA TYPES.
13&14-2 Know the forms of loop statements in C (while,do/while,for). Understanding how data conversion occurs. Read/Write data in files using Unix redirection.
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 4.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Chapter 3 Control Flow Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh University.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
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.
Homework K&R chapter 4. HW3: ASCII Hex to Integer int axtoi (char s[ ]) { int i, n, flag; n = 0; flag = 1; for ( i = 0; flag; i++) /* for (i = 0; ; i++)
CIS-165 C++ Programming I CIS-165 C++ Programming I Bergen Community College Prof. Faisal Aljamal.
1 Programming in C Hello World! Soon I will control the world! Soon I will control the world!
CSE 232: C++ debugging in Visual Studio and emacs C++ Debugging (in Visual Studio and emacs) We’ve looked at programs from a text-based mode –Shell commands.
CS Class 05 Topics  Selection: switch statement Announcements  Read pages 74-83, ,
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Unix Environment Input Output 2  List Content (ls) ◦ ls (list current directory) ◦ ls –all (include hidden files/folders)  Make directory (mkdir) ◦
Makefiles. Multiple Source Files (1) u Obviously, large programs are not going to be contained within single files. u C provides several techniques to.
1 SEEM3460 Tutorial Compiling and Debugging C programs.
C By Example 1 The assumption is that you know Java and need to extend that knowledge so you can program in C. 1. Hello world 2. declarations 3. pass by.
C++ / G4MICE Course Session 1 - Introduction Edit text files in a UNIX environment. Use the g++ compiler to compile a single C++ file. Understand the C++
COP 3530 Spring2012 Data Structures & Algorithms Discussion Session Week 2.
1 Homework Done the reading? –K&R –Glass Chapters 1 and 2 Applied for cs240? (If not, keep at it!) Gotten a UNIX account? (If not, keep at it!)
Minimal standard C program int main(void) { return 0 ; }
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
CSC Java Programming, Spring, 2010 Week 2: Java Data Types, Control Constructs, and their C++ counterparts.
CSE 1320 Basics Dr. Sajib Datta
CMSC 104, Version 8/061L14AssignmentOps.ppt Assignment Operators Topics Increment and Decrement Operators Assignment Operators Debugging Tips Reading Section.
2. C FUNDAMENTALS. Example: Printing a Message /* Illustrates comments, strings, and the printf function */ #include int main(void) { printf("To C, or.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Lecture 3 Translation.
Chapter 7 User-Defined Methods.
Computer Science 210 Computer Organization
A bit of C programming Lecture 3 Uli Raich.
Day 01 Introduction to Linux and C
Lecture 13 & 14.
Linux 104 Training Module File Editing.
Lecture Note Set 1 Thursday 12-May-05
C Basics.
Chapter 4 – Control Structures Part 1
Computer Science 210 Computer Organization
Govt. Polytechnic,Dhangar
Introduction to C Topics Compilation Using the gcc Compiler
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
C Programming Getting started Variables Basic C operators Conditionals
Introduction to C Topics Compilation Using the gcc Compiler
CSC Java Programming, Spring, 2012
Programming Languages and Paradigms
An Overview of C.
Makefiles, GDB, Valgrind
Presentation transcript:

1 Lab 2: The Unix environment, Using vi, C programming SITE, uOttawa

2 Practical tools Editor Editor Vi (emac) Vi (emac) Compiler Compiler gcc gcc Makefile Makefile make make Debugging Debugging gdb gdb

3 Using C/Unix/Linux at SITE $ ssh linux

4 Vi Editor A screen-based editor used by Unix users An experience with vi Starting the editor Cutting and Pasting/Deleting text Inserting New Text Moving the Cursor Within the File Moving the Cursor Around the Screen Replacing Text Searching for Text or Characters Saving and Quitting

5 Vi Basic Commands mkdir - create a directory cp - copy a file rm - delete a file vi - open a file pressing the key turns off the Insert mode :q – quit with saving :x – quit without saving :i – insert text before cursor, until hit :a – append text before cursor, until hit $ - move cursor to the end of the current line :w – move cursor to the beginning of next word 0 – move cursor to the start of current line :o – open and put text in a new line after the cursor y1 – copy current character Yn – copy n characters yy – copy current line p - paste characters x – delete single character under cursor dd – delete the current line u – undo the last action :w – save a file / - search the string forward ? - search the string backward

6 Avi Exercise Create and edit test.c file Create and edit test.c file #include #include main(){ printf(“Hello world, …\n”); printf(“Hello world, …\n”);}

7 C programming/Unix #include #include main(){ printf(“hello, wolrd…\n”); printf(“hello, wolrd…\n”);} $ mkdir csi3130 $cd csi3130 $ vi test.c $cc test.c $a.out

8 Compiler GNU Compiler Collection GNU Compiler Collection A compiler system produced by the GNU Project supporting various programming languages includes front ends for C (gcc), C++ (g++), Java (gcj), and Fortran (gFortran) intro.html

9 GCC Compile C code to an executable Compile C code to an executable gcc -o gcc -o Reporting all warning messages Reporting all warning messages gcc -Wall -o gcc -Wall -o

10 GCC (Cont’d) An example of compiling two.c files into an executable program An example of compiling two.c files into an executable program gcc -Wall -o assign1prob1 main.c list.c gcc -Wall -o assign1prob1 main.c list.c An example of compiling two files and then link them separately An example of compiling two files and then link them separately gcc -Wall -o main.o -c main.c gcc -Wall -o main.o -c main.c gcc -Wall -o list.o -c list.c gcc -Wall -o list.o -c list.c gcc -Wall -o assign1prob1 main.o list.o gcc -Wall -o assign1prob1 main.o list.o

11 Make command make automates the process of compiling a program make automates the process of compiling a program Makefile Makefile $ make $ make $ make clean $ make clean

12 Debugging gdb is GNU Debugger gdb is GNU Debugger A debugger for several languages Inspecting what the program is doing at a certain point during execution Errors like segmentation faults may be easier to find with the help of gdb /html_node/gdb_toc.html

13 GDB enable built-in debugging support enable built-in debugging support gcc [other flags] -g -o gcc [other flags] -g -o generating an expanded symbol table for use with gdb generating an expanded symbol table for use with gdb Example: gcc -Wall -Werror -ansi - pedantic-errors -g prog1.c -o prog1.x Example: gcc -Wall -Werror -ansi - pedantic-errors -g prog1.c -o prog1.x

14 GDB (Cont’d) enter gdb enter gdb gdb gdb enter gdb enter gdb quit quit printing line from a source file printing line from a source file list list running a program running a program run run breakpoint at a line number breakpoint at a line number break : break : break break break at a particular function break at a particular function break : break : set a breakpoint with condition set a breakpoint with condition break if break if deleting breakpoints deleting breakpoints delete delete proceed onto the next breakpoint proceed onto the next breakpoint continue continue Single step Single step step step

15 debugging exercise Reverse a string Reverse a string #include char * reverse(char s[]) { int c, i, j; For(i =0, j=strlen(s)-1; i< j; i++, j--) { c = s[i]; S[i] =s[j]; S[j]=c; } Main() { printf(“%s \n”,reverse(“database”)); }

16 GDB debugging exercise Program failed, why??? Load the program into GDB

17 GDB debugging exercise Here failed? What is the value of i

18 GDB debugging exercise Try the basic GDB commands here! Track your program step by step, inspect the variables..

19 Correct code #include char * reverse(char s[]) { int c, i, j; for(i =0, j=strlen(s)-1; i< j; i++, j--) { c = s[i]; s[i] =s[j]; s[j]=c; } return s; } int main() { char myStr[9]="database"; printf("%s \n",reverse(myStr)); return 0; }

20 From Java to C

21 Types, Operators and Expressions Data type Data type char, int, float, double, short int, long int Constants Constants #define PI Typedef: assigning alternative names to existing Typedef: assigning alternative names to existing typedef int myInteger; Relational and logical operators Relational and logical operators > >= < <= == != Increment and decrement operators Increment and decrement operators b = a++; b = ++a; b = a--; b = --a;

22 Control Flow The semicolon is a statement terminator The semicolon is a statement terminator If-Else, Else-If If-Else, Else-If if (expression) statement1 statement1 elseelse if (expression) statement2 statement2 else statement3 For loop For loop you need to define the counter variable before the loop for(expr1; expr2; expr3) statement While-Do While-Do expr1; While(expr2) statement expr3; Do-While Do-While do statement While(expression);

23 Control Flow (Cont’d) Switch Switch switch (expression){ case const-expr : statements default: statements } Conditional expressions (expr1 ? expr2 : expr3) Conditional expressions (expr1 ? expr2 : expr3) if(a>b) if(a>b) z=a;z = (a > b) ? a : b ; z=a;z = (a > b) ? a : b ; else else z=b; z=b;

24 Function declaration Return value Return value Default return value of a function in C is int Default return value of a function in C is int Java Java The use of function may appear earlier than its definition The use of function may appear earlier than its definition C program C program Should be declared somewhere earlier than their invocations Should be declared somewhere earlier than their invocations int power(int b, int e); … /* call power() here */ /* call power() here */… int power(int b, int e) { int r = 1; int r = 1; while (e-- > 0) r *= b; while (e-- > 0) r *= b; return r; return r; } int power(int b, int e) { int r = 1; int r = 1; while (e-- > 0) r *= b; while (e-- > 0) r *= b; return r; return r; }main(){... /* call power() here */ }

25 Input and Output printf(“the int value is %d”, var); printf(“the string value is %s”, var); printf(“the charactr and double values are %c and %e”, var); printf(“the double value is %e”, var); scanf(“enter an int: %d”, var); scanf(“enter a string: %s”, var); scanf(“enter a character and a double: %c %e”, var); scanf(“enter a string: %s”, var); Do not forget including

26 Variable scope int globalVar = 34; myFun(){ int x =1; } Global; outside of the function Local

27 Some details about C No boolean type in C No boolean type in C No explicit boolean type No explicit boolean type #define TRUE 1 #define TRUE 1 #define FALSE if (a){ #define FALSE if (a){ … } No function overloading in C No function overloading in C Two functions cannot have the same name Variables must be declared at the top of a basic block (for some c systems) Variables must be declared at the top of a basic block (for some c systems) The following may not pass the compiler { int a; printf("Hello world\n"); char b; } { int a; printf("Hello world\n"); char b; } Lack of exceptions Lack of exceptions Illegal activity may not be told (e.g. access memory that hasn’t been allocated in some way) No automated garbage collection in C No automated garbage collection in C you must free the memory

28 Standard library dynamic memory allocation dynamic memory allocation Input/output Input/output String handling String handling Mathematical functions Mathematical functions Characters Characters

29 Some common errors if (a=1){ if (a=1){ some stuff } some stuff } == Boolean evaluation = Variable assignment operator void myfunc(int a) { /*... */ } void myfunc(int a) { /*... */ } void myfunc(float b) { /*... */ } error: myfunc already defined

30 Exercise Write a program that Write a program that Accepts an input “x” (A value to progress up to) Accepts an input “x” (A value to progress up to) Starting at 0 and 1, outputs the Fibonacci sequence up to “x” permutations. Starting at 0 and 1, outputs the Fibonacci sequence up to “x” permutations. There should be two functions, for clarity. There should be two functions, for clarity. (main) Accepts the input and calls the fibonacci function. (main) Accepts the input and calls the fibonacci function. (fibonacci) One that accepts the value of x and outputs the sequence. (fibonacci) One that accepts the value of x and outputs the sequence.

31 Fibonacci in Java import java.io class Fibonacci { public static void main(String args[]) { System.out.println("How many numbers of the sequence would you like?"); InputStreamReader sr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(sr); try { String input = br.readLine(); int n = Integer.valueOf(input).intValue(); fibonacci(n); } catch (NumberFormatException e){System.out.println("That is not an integer. Please enter an integer value"); } catch (IOException e) { System.out.println("I did not recieve an input"); } } public static void fibonacci(int n){ int a=0,b=1; for (int i=0;i<n;i++){ System.out.println(a); a=a+b; b=a-b; }

32 Fibonacci in C #include int main () { int n; printf("\nHow many numbers of the sequence would you like?\n"); scanf("%d",&n); fibonacci(n); return 0; } int fibonacci(int n) { int a = 0; int b = 1; int sum; int i; for (i=0;i<n;i++) { printf("%d\n",a); sum = a + b; a = b; b = sum; } return 0; }