Day 01 Introduction to CWhy learn C (after Java)?Goals of this tutorialCreating an executableTypes of filesExternal library files libname.a or libname.soSlide 7Summarizing the ExampleCompiling and running from the command line in UNIX/LinuxSlide 10Summary: Using external library filesPre-processor directivesExample of pre-processor directives#defineSimple Data TypesSlide 16Slide 17Slide 18Slide 19String – an array of charactersStrings – character arrayOther string functionsStrings contd.Slide 24StructuresSlide 26Slide 27User-defined header filesCommand line argumentsExample 7File handlingSlide 32Reading till end of fileFunctions – C methodsSlide 351Day 01 Introduction to C2Why learn C (after Java)?Both high-level and low-level languageBetter control of low-level mechanismsPerformance better than Java But,….Memory management responsibilityExplicit initialization and error detectionMore room for mistakes3Goals of this tutorialTo introduce some basic C concepts to youso that you can read further details on your ownTo warn you about common mistakes made by beginners4Creating an executableSource: http://www.eng.hawaii.edu/Tutor/Make/1-2.html5Types of filesC source files (.c)C header files (.h)Object files (.o)Executable files (typically no extension – by default : a.out)Library files (.a or .so)6External library fileslibname.a or libname.so Special functionality is provided in the form of external libraries of ready-made functions Ready-compiled code that the compiler merges, or links, with a C program during compilation For example, libraries of mathematical functions, string handling functions, and input/output functions Look for the library files under /usr/lib and header files under /usr/include7Example 1 – What is the output of this program?#include <stdio.h> //#include “myheader.h”intmain(){ printf(“Hello World. \n \t and you ! \n ”);/* print out a message */ return 0;}8Summarizing the Example#include <stdio.h> = include header file stdio.hNo semicolon at end Small letters only – C is case-sensitive int main(){ … } is the only code executed printf(“ /* message you want printed */ ”); \n = newline \t = tab \ in front of other special characters within printf creates “escape sequences”. printf(“Have you heard of \”The Rock\” ? \n”);9Compiling and running from the command line in UNIX/Linux prompt>gcc eg1.c (Creates a.out)prompt>./a.out (Runs the executable)prompt>gcc eg1.c –o eg1 (Creates eg1 not a.out)prompt>./eg1 (Runs the executable)10To compile, use flag “l” and name i.e. –lname.To compile, use flag “l” and name i.e. –lname.e.g. e.g. gcc –o test test.c –lm gcc –o test test.c –lm where “m” in “lm” comes from libm.so i.e. the where “m” in “lm” comes from libm.so i.e. the math library.math library.11Summary: Using external library filesTo use the library files, you must:include the library header files You may also have to:link the library with a -l option to gcc12Pre-processor directivesA preprocessor is a program that examines C code before it is compiled and manipulates it in various ways. Two commonly used pre-processor directives#include – to include library files.#define - to define macros (names that are expanded by the preprocessor into pieces of text or C code)13Example of pre-processor directivesExample 2:#include <stdio.h> #define STRING1 "A macro definition\n" #define STRING2 "must be all on one line!\n" #define EXPRESSION1 1 + 2 + 3 + 4 #define EXPRESSION2 EXPRESSION1 + 10 #define ABS(x) ((x) < 0) ? -(x) : (x) #define MAX(a,b) (a < b) ? (b) : (a) #define BIGGEST(a,b,c) (MAX(a,b) < c) ? (c) : (MAX(a,b)) intmain (){ printf (STRING1); printf (STRING2); printf ("%d\n", EXPRESSION1); printf ("%d\n", EXPRESSION2); printf ("%d\n", ABS(-5)); printf ("Biggest of 1, 2, and 3 is %d\n", BIGGEST(1,2,3)); return 0; }14#defineThe expression is NOT evaluated when it replaces the macro in the pre-processing stage.Evaluation takes place only during the execution phase.15%i2short%l4long%lf8double%f4float%c1char%d %i4intShort-hand# of bytes (typical)Data-typeString - %s address - %p(HEX) or %u (unsigned int)Use sizeof() to determine number of bytes. Simple Data Types16#include <stdio.h>intmain(){int nstudents = 0; /* Initialization, required */ float age = 21.527;printf(“How many students does KU have ?”); scanf (“%d”, &nstudents); /* Read input */printf(“KU has %d students.\n”, nstudents); printf(“The average age of the students is %3.1f\n”,age);//3.1 => width.precisionreturn 0;}$How many students does KU have ?:2000 (enter)KU has 2000 students.The average age of the students is 21.5$Example 317Like JavaOperators similar to those in Java: Arithmeticint i = i+1; i++; i--; i *= 2;+, -, *, /, %,Relational and Logical<, >, <=, >=, ==, !=&&, ||, &, |, !Syntax same as in Java:if ( ) { } else { }while ( ) { }do { } while ( );for(i=1; i <= 100; i++) { }switch ( ) {case 1: … }continue; break;18Example 4#include <stdio.h>#define DANGERLEVEL 5 /* C Preprocessor -- substitution on appearance *//* like Java ‘final’ */intmain(){float level=1; /* if-then-else as in Java */if (level <= DANGERLEVEL){ /*replaced by 5*/ printf(“Low on gas!\n”); } else printf(“On my way !\n”);return 0;}19One-Dimensional ArraysExample 5:#include <stdio.h>intmain() { int number[12]; /* 12 numbers*/ int index, sum = 0;/* Always initialize array before use */ for (index = 0; index < 12; index++) {number[index] = index; } /* now,number[index]=index; will cause error:why ?*/ for (index = 0; index < 12; index = index + 1) {sum += number[index]; /* sum array elements */ } return 0;}String – an array of characters_char name[10];___ /*declare a string called name of 10 characters *//* Initialize “name” to “ALICE” */name[0] = ‘A’; name[1] = ‘l’; name[2] = ‘i’; name[3] = ‘c’; name[4] = ‘e’;name[5] = ‘\0’;/* Print “name” to the screen */ printf(“%s”, name);Strings – character array/* Declaring and Initializing strings */char name[ ] = {‘A’,’l’,’i’,’c’,’e’,’\0’}; char name [ ] = “Alice”; char name [6] = {‘A’,’l’,’i’,’c’,’e’,’\0’}; /*
View Full Document