Looking for a Tutor Near You?

Post Learning Requirement »
x

Choose Country Code

x

Direction

x

Ask a Question

x

x
x
x
Hire a Tutor

In To C Programming

Loading...

Published in: C / C++
5,114 Views

C is a general-purpose, procedural, imperative computer programming language developed in 1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating system. C is the most widely used computer language. It keeps fluctuating at number one scale of popularity along with Java programming language, which is also equally popular and most widely used among modern software programmers.

Prantik S / Kolkata

11 years of teaching experience

Qualification: MCA (Jaipur National University - [JNU], Jaipur - 2017)

Teaches: Basic Computer, Computer for official job, MS Office, School Level Computer, ICT Training, Computer Science, Information Practice, IT & Computer Subjects, BCA Tuition, IT, Computer, C / C++, C# (C Sharp), Java And J2EE, Python Programming, Visual Basic, BCA Subjects, Hardware Training, Networking, Java Script

Contact this Tutor
  1. INTRODUCTION C PROGRAMMING
  2. Course Strategy Not assumed that you have programming experience Course will move quickly Each subject builds on previous ones More important to be consistent than occasionally heroic Start by hacking, back up to cover more fundamental topics
  3. Holistic view WRITING A PROGRAM
  4. High-level view of programming Create nevv text file this is where instructions the comprise program will be typed this file is typically called you source code What this file looks like depends on the choice of programming language. As long as you follow synax rules for chosen language, your source code file is valid. e In this class we will start with a powerful, venerable, classic language called C.
  5. High-level view of programming Compile the source code. Compilation is the process of converting the source code into machine language — the very minimalist language that is spoken directly by the machine in use. The machine lanage is stored in a new file. Note: It is possible to program directly in machine language, but it is tedious, ugly, and error-prone. Run or execute the machine-language file. On Unix, this is done by typing the name of the executable file.
  6. GETTING STARTED WITH c
  7. Getting Started With C You will need at least: Computer with an OS (Linux) Text editor (emacs, vi) Compiler (gcc) All of the above suggestions are free in one way or another See http://www.gnu.org See http://www.cygwin.com
  8. Getting Started, Cont. These tools are not required, but they are strongly recommended Better for learning Homework must run on Linux gnu compiler Important! Become facile with simple Linux and a text editor as quickly as possible Am assuming good knowledge of Linux/emacs
  9. C PROGRAM
  10. A Simple C Program 1 / * Fig. 2.1: fig02 01. c A first program in C * / 3 #include tdio . h> 5 int main ( ) printf( "Welcome to C! \ n" ) • 9 return 10 Wel come to C ! Comments Text surrounded by / * and * / is ignored by computer Used to describe program #include Preprocessor directive Tells computer to load contents of a certain file allows standard input/output operations
  11. A Simple C Program, Cont. int main ( ) C programs contain one or more functions, exactly one of which must be main Parenthesis used to indicate a function int means that main "returns" an integer value Braces ( { and } ) indicate a block The bodies of all functions must be contained in braces
  12. 2.2 A Simple C Program: Printing a Line of Text Return O ; A way to exit a function Return o, in this case, means that the program terminated normally 12
  13. Running the Program on Linux With gcc Use emacs, vi, or some other text editor to type in and save program. Good idea to: Name program something meaningful Establish conventions for naming Add a -c suffix to the name Compile program gcc hello.c [-0 whatever]
  14. Running on Linux This produces the executable named whatever, or a.out by default. Type executable name to run. Examples. a.out. whatever. ./a.out. Etc. Note: linker will be required when our programs become more sophisticated — not necessary now. 14
  15. User variables, reading user input SECOND C PROGRAM
  16. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 / * Fig. 2.5: fig02 05. c Addi tion program * / #include tdio . h> int main ( ) integer 1, integer2, sum; int printf ( scanf ( printf ( scanf ( "Enter first integer\n" '%d", &integerl ) • "Enter second integer\n" '*d", &integer2 ) ; integer 1 + integer2 ; sum printf( "Sum is %d\n" sum ) • declaration * / prompt * / read an integer * / prompt * / read an integer * / assignment of sum * / print sum * / 1. Initialize variables 2. Input 2.1 Sum print 3. return / * indicate that program ended successfully * / Enter first integer 45 Enter second integer 72 Sum is 117
  17. C DATA TYPES
  18. What do program instructions look like? A simple program has at least these three main parts variable declaration variable initialization main body
  19. Variables in Programming Represent storage units in a program Used to store/retrieve data over life Of program Type of variable determines what can be placed in the storage unit Assignment— process of placing a particular value in a variable Variables must be declared before they are assigned The value of a variable can change; A constant always has the same value 19
  20. Naming variables When a variable is declared it is given a name Good programming practices Choose a name that reflects the role of the variable in a program, e.g. Good: customer name, ss number; Bad : cn, ss; Don't be afraid to have long names if it aids in readability Restrictions Name must begin with a letter; otherwise, can contain digits or any other characters. C is CASE SENSITIVE! Use 31 or fewer characters to aid in portability 20
  21. Variable Declaration All variables must be declared in a C program before the first executable statement! Examples: main(){ int a, b, c; float d; / * Do something here */ 21
  22. C Variable Names Variable names in C may only consist of letters, digits, and underscores and may not begin with a digit Variable names in C are case sensitive ANSI standard requires only 31 or fewer characters. Enhances portability to follow this rule Should be very descriptive 22
  23. Variable assignment After variables are declared, they must (should) be given values. This is called assignment and it is done with the = operator. Examples: float a, b; int c; b = 2.12; c = 200; 23
  24. Basic C variable types There are four basic data types in C: char A single byte capable of holding one character in the local character set. o int An integer of unspecified size float Single-precision floating point double Double-precision floating point O 24
  25. char variable type Represents a single byte (8 bits) of storage Can be signed or unsigned Internally char is just a number Numerical value is associated with character via a character set ASCII character set used in ANSI C Question: what is the difference between: printf("%c", someChar); printf("%d", someChar); 25
  26. int variable type Represents a signed integer of typically 4 or 8 bytes (32 or 64 bits) Precise size is machine-dependent Question: What are the maximum and minimum sizes of the following: 32-bit unsigned int 32-bit signed int 64-bit signed/unsigned int What happens if these limits are exceeded? 26
  27. float and double variable types Represent typically 32 and/or 64 bit real numbers How these are represented internally and their precise sizes depend on the architecture. We won't obsess over this now. Question: How large can a 64-bit float Question: How many digits of precision does a 64-bit float have? 27
  28. Additional variable types Note that other types can be constructed using the modifiers: short, long, signed, unsigned The precise sizes Of these types is machine-specific We will not worry about them for the time being To find out the meaning of short int, etc. on a given system, use 28
  29. Declaring va riables All variables must always be declared before the first executable instruction in a C program Variable declarations are always: var_type var_name; int age; float annual _ salary; double weight, height; / * multiple vars ok */ In most cases, variables have no meaningful value at this stage. Memory is set aside for them, but they are not meaningful until assigned. 29
  30. Assigning values to Variables Either when they are declared, or at any subsequent time, variables are assigned values using the operator. Examples int age = 52; //joint declaration/assignment double salary; salary = 150000.23; age = 53; //value may change at any time 30
  31. Assignment, cont. Be careful to assign proper type — contract between declaration and assignments must be honored int / * what is the value of x? */ double x = 3; / * is this ok? */ char c = 300; / * 300 > 1 byte; what happens? */ General advice Don't obsess too much over this at beginning Keep it simple, stick to basic data types We will be more pedantic later in the course
  32. Structure of a C program So far our C programs are as follows: / * description of program */ #include / * any other includes go here */ int main(){ /* program body */ return 0; Let's learn more about the structure of "program body" 32
  33. Program Body - declarations Always begins with al variable declarations. Some examples: int a, b, c; / * declare 3 ints named a,b,c */ int d, e; / * similar to above in two steps */ int g = 1, h, k=3; double pi = 3.1415926; Reading note: K&R mentions that integers can be assigned in octal and hexadecimal as well. We will discuss this later. Certainly, not important for most applications.
  34. Sta m e n Note: all statements end with a semicolon! Statements can (with a few exceptions) be broken across lines or ganged on a single line Commas separate multiple declarations Blank lines have no effect Extra spaces between tokens has no effect. Comments are ignored by the compiler 34
  35. Program Body - Executable Statements Executable statements always follow variable declarations/initializations Executable statements include any valid C code that is not a declaration, ie valid C code to do things like: "multiply the value of a by 10 and store the result in "add 1 to the value of j and test whether it is greater than the value of k" "store 5.2 in the variable x" (ie assignment) "print the value ofx,y, and z, each on a separate line"
  36. The printf Executable Statement The only executable we've seen to this point are Assignments The printf and scanf functions Assignment expressions with simple operators Very hard to write any program without being able to print output. Must look at printf in more detail to start writing useful code. 36
  37. printf(), cont. Sends output to standard out, which for now we can think of as the terminal screen. General form printf(format descriptor, varl , var2, format descriptor is composed of Ordinary characters copied directly to output Conversion specification Causes conversion and printing of next argument to printf Each conversion specification begins with %
  38. Printf() examples Easiest to start with some examples printf("%s\n", "hello world"); Translated: "print hello world as a string followed by a newline character" printf("%d\t%d\n", j, k); Translated: "print the value of the variable j as an integer followed by a tab followed by the value of the variable k as an integer followed by a new line." printf("%f : %f : %f\n", x, y, z); English: "print the value of the floating point variable x, followed by a space, then a colon, then a space, etc.
  39. More on format statements The format specifier in its simplest form is one of: 0/oS sequence of characters known as a String Not a fundamental datatype in C (really an array of char) O/od Decimal integer (ie base ten) O/of Floating point Note that there are many other options. These are the most common, though, and are more than enough to get started. 39
  40. Invisible characters Some special characters are not visible directly in the output stream. These all begin with an escape character (ie \); \n newline e horizontal tab \a alert bell e vertical tab See K&R p.38 for more details 40
  41. Arithmetic Operations Five simple binary arithmetic operators + "plus" c = a + b 'minus" -5 c = a-b 2. "times" -5 c = b 3. / "divided by" c = a/b 4. % "modulus" c = a % b 5. What are the values of c in each case above if int a = 10, b = 2; float a = 10, b = 2; int a = 10; float b = 2; ??
  42. Relational Operators Four basic operators for comparison of values in C. These are typically called relational operators: > "greater than" < "less than" 2. 'greater than or equal to" 3. "less than or equal to" 4. For the declaration int a-I ,b=2,c; what is the value of the following expressions? a > b; a=b;a
  43. Relational Operators, cont. Typically used with conditional expressions, e.g. if (a < 1) then However, also completely valid expressions which evaluate to a result — either 1 (true) or O (false). int c, a=2, ; What is the value of c? Note: We'll talk about order of precedence for multipart expressions a little later. For now, we force an order using parentheses. 43
  44. Equality Operators C distinguished between relational and equality operators. This is mainly to clarify rules of order of precedence. Two equality operators 'is equal to" 'is not equal to" 2. These follow all of the same rules for relational operators described on the previous slide. 44
  45. Logical Operators Logical Operators are used to create compound expressions There are two logical operators in C 1. 2. "logical or" A compound expression formed with Il evaluates to 1 (true) if any one of its components is true && "logical and" A compound expression formed with && evaluates to true if all of its components are true 45
  46. Logical Operators, cont. Logical operators, like relational operators, are typically used in conditional expressions = 1) ) etc. However, these can also be used in regular expressions What is the value of d here? 46
  47. Reading keyboard input To be useful, program must be able to read data from external source, e.g. User input from keyboard Database Socket o In next slide we cover the scanf library function. It is like printf but reads user- typed input rather than prints it.
  48. Scanf fu nction In , so no new #include('s) Basic syntax scanf( format-specifier, &varl , &var2, etc.); Format-specifier is identical to printf We do not need to understand everything here, just enough to do some basic I/O Examples int a; scanf("%d",&a); double x; scanf("%f" &x)• Blocks program until user enters input! 48
  49. Another technique for passing data from the keyboard main() can also be written as main(int argc, char *argv[]) If main is written in this way, information can be passed directly from the keyboard to the program at the time of execution For example, we may run a program called a-out as: PROMPT > a.out Andrew Siegel When a.out is run the two tokens Andrew and Siegel are passed into the program and can be obtained by querying argv and argc Note: this involves some concepts that go beyond what we have learned so far. We will understand fully later. 49
  50. Passing data, cont. When this technique is used, each token is stored as a separate element in the array argv The first token passed to the program is stored in argv[l], the second token in argv[2], etc. argc stores the (integer) number of tokens passed in A simple example will clarify this
  51. argc/argv example int main (int argc, char* argv[]){ printf("%s %d %s \n", "you entered", argc, "arguments"); printf("%s: %s\n", "the zeroth arg is the program name", argv[0]) ; printf("%s: %s\n", "the first argument is", argv[l l); printf("%s: %s\n", "the second argument is, argv[2]); > gcc argv_example.c —o argv_example > argv_example hello world you entered 3 arguments the zeroth argument is the program name: argv_example the first argument is hello the second argument is world 51
  52. argc/argv cont. Note that to do this completely generally we would need to use a while or for loop We will study while loops shortly Also note that argv reads all arguments as Strings (ie sequences of characters). So, we cannot simply pass two number and add them, for example. First, we would have to convert to a numeric type.
  53. Converting String to integer An important function when using argv/argc is atoi. atoi converts a String argument to an integer in the following way: int input, output; input = atoi(argv[l l); output = input + 1; printf("%d\n", output); > a.out 333 334
  54. Reading single characters Another important pair of functions for keyboard input/output is getchar/putchar getchar reads a single character from the input stream; putchar write a single character to the standard out for example: int c; c = getchar(); /* blocks until data is entered if more than one char is entered only first is read */ putchar(c) ; /* prints value of c to screen */
  55. While loops A simple technique for repeating a statement or group of statements until some specified condition IS met General form: while (expr){ statementl ; statement2; If expr evaluates to true (ie not 0), then perform statementl , etc. Otherwise, skip to end of while block. Repeat until expr evaluates to false (ie 0).
  56. While example / * a program to loop over user input and print to screen */ #include int main(int argc, char* argv[]){ int counter; /* declarations */ /* executable body */ counter = 1; while (counter < argc){ printf("%s %d: O/os\n", "argument number", counter, argv[counter]); counter = counter + 1; / * equivalent to counter++ or -PA-counter */ return 0; 56
  57. / * a program to loop over user input and print back to screen with a little error checking */ int main(int argc, char *argv[]){ int counter = 1; / * check to make sure the user entered something */ if (argc < 2){ printf("%s\n", "error; must enter at least one argument!"); / * exit(l) will end the program */ exit(l ); / * if ok, continue as before */ while (counter < argc){ printf("%s %d: %s\n", "argument number", counter, argv[counter]); counter = counter + 1; / * equivalent to counter++ or ++counter */ 57
  58. Getchar/putchar example /* uses getchar with while to echo user input */ #include int main(){ int c; /* holds the input character value */ c = getchar(); /* reads first character from input stream with keyboard, this is signaled by Enter key*/ while (1){ /* loop forever */ putchar(c); /* write char to keyboard */ c = getchar(); /*get next char in stream */
  59. Input redirection Files can be sent to an input stream by using the unix redirection command '
  60. What Is a Computer? Computer Device capable of performing computations and making logical decisions Computers process data under the control of sets of instructions called computer programs 60
  61. What Is a Computer, Cont. Hardware Various devices comprising a computer Keyboard, screen, mouse, disks, memory, CD-ROM, and processing units Software Programs that run on a computer 1.3 computer organization
  62. History of C Evolved by Ritchie from two previous programming languages, BCPL and B Used to develop UNIX Used to write modern operating systems Hardware independent (portable) By late 1970's C had evolved to "traditional C" 62
  63. History of C Standardization Many slight variations of C existed, and were incompatible Committee formed to create a "unambiguous, machine-independent" definition Standard created in 1989, updated in 1999
  64. Language Types Three types of programming languages 2. Machine languages Strings of numbers giving machine specific instructions o Example: o +1300042774 +1400593419 +1200274027 Assembly languages O o English-like abbreviations representing elementary computer operations (translated via assemblers) Example: Load Add Store BASE PAY overpay GROSSPAY 64
  65. Language Types, Cont. 3. High-level languages Codes similar to everyday English Use mathematical notations (translated via compilers) Example: gross Pay basePay + overTimePay
  66. High-level Languages 'high-level" is a relative term C is a relatively low-level high-level language Pascal, Fortran, COBOL are typical high-level languages Java, Python, Perl, VB are examples of high-level high-level languages Application specific languages (Matlab, Javascript, VBScript) are even higher- level. 66
  67. C Programming Language What is C? C is a structured, relatively low-level, portable programming language. Why study C? Many popular software tools are written in C. Has strongly influenced many other languages. C-shell, java, C++, Perl, etc. Forces the user to understand fundamental aspects of programming. Very concise language.
  68. C, cont. o Is C object-oriented? No. C++ (its successor) is. Can a non 00 language be useful? Yes. o Is C a hard language to learn? No, but it does take a little getting used to. What is the ANSI part? American national standards institute — uniform standard definition of C for portability. 68
  69. C Data Types There are only a few basic data types in C: char int float double short, long, signed and unsigned are additional qualifiers. will discuss later 69
  70. C Data types, cont. char A single byte (capable of holding one character in the local character set). @ int An integer, typically reflecting the natural size of integers on the host machine. float Single precision floating point (typically 8-bit) double Double precision floating point (typicall 4-bit) 70
  71. Introduction to C: //a simple program that has variables #include int main() int x; //(32 bits) char y; //(8 bits) float z; //(32 bits) double t; //(64 bits) printf("hello world... \n") ; Basics //wrong, The variable declaration must appear first return 0;
  72. More of a simpler programming approach from here.... 72
  73. Introduction to C: Basics //reading input from console #include int main() int numl ; int num2; printf( "Please enter two numbers: " ); scanf( "%d %d", &numl ,&num2 ); printf( "You entered %d %d", numl , num2 ); retLlrn O;
  74. Introduction to C: #include int main() int age; /* Need a variable... */ printf( "Please enter your age" ); / * Asks for age */ scanf( "%d", &age ); / * The input is put in age */ if ( age < 100 ) /* If the age is less than 100 */ printf ("You are pretty young ); / * Just to show you it works else if ( age 100 ) / * I use else just to show an example */ printf( "You are old\n" ); else printf( "You are really old\n" ); return 0; / * Executed if no other statement is*/
  75. Introduction to C: Loops(for) #include int main() int x; / * The loop goes while x < 10, and x increases by one every loop*/ for (x = 0; x < 10; ) / * Keep in mind that the loop condition checks the conditional statement before it loops again. consequently, when x equals 10 the loop breaks. x is updated before the condition is checked. */ printf( "%d\n", x ); return 0;
  76. Introduction to C: Loops(while) #include int main() int x = 0; / * Don't forget to declare variables */ while (x < 10) { / * While x is less than 10 */ printf( "%d\n", x ); x++; / * Update x so the condition can be met eventually */ return 0;
  77. Introduction to C: Loops(do while) #include int main() int x; do /* "Hello, world!" is printed at least one time even though the condition is false*/ printf( x ); X-•1-4- ; } while (x 10) return 0;
  78. Introduction to C: Loops(break and continue) #include int main() int x; break; return 0; 1 2 3 4 #include int main() int x; 10;x++) if(x==5) continue; return 0; 1 2 3 4 6 7 8
  79. Introduction #include //function declaration int mult ( int x, int y ); int main() int x; int y; to C: function printf( "Please input two numbers to be multiplied: ' scanf( "%d", &x ); scanf( "%d", &y ); printf( "The product of your two numbers is %d\n", mult( x, y ) ); return 0; //define the function body //return value: int //utility: return the multiplication of two integer values //parameters: take two int parameters int mult (int x, int y) return x * y;
  80. #include //function declaration, need to define the function body in other places void playgame(); void loadgame(); void playmultiplayer(); int main() int input; printf( "1 . Play game\n" ); printf( "2. Load game\n" ); printf( "3. Play multiplayer\n" ); printf( "4. Exit\n" ); printf( "Selection: " ); scanf( "%d", &input ); switch ( input ) { case 1: /* Note the colon, not a semicolon */ switch case playgame(); //don't forget the break in each case break; case 2: loadgame(); break; case 3: playmultiplayer(); break; case 4: printf( "Thanks for playing!\n" ); break; default: printf( "Bad input, quitting ); break; return 0;
  81. Introduction to C: pointer variables Pointer variables are variables that store memory addresses. Pointer Declaration: int x, y = 5; int *ptr; /*ptr is a POINTER to an integer variable*/ Reference operator &: ptr = &y; /*assign ptr to the MEMORY ADDRESS of y.*/ Dereference operator * x = *ptr; /*assign x to the int that is pointed to by ptr */
  82. Introduction to C: pointer variables Pointer Example 1 int int int Ptr x x; x *Ptr ; pte *ptr ; 1000 1004 2000 5 5 1004
  83. Introduction to C: pointer variables Pointer Example 2 int = int *PI, - ty; 10, 5; 10 1000 1004 2000 2004 10 5 Pointer Example 2 // Not the same as *p2 = I OOO 1004 2000 2004 7 Il 1000 pi pi p2
  84. #include //swap two values void swap(int* iPtrX,int* iPtrY); void fakeswap(int x, int y); int main() int x = 10; int y = 20; int *pl = &x; int *p2 = &y; printf("before swap: x=%d y=%d\n",x,y); swap(pl ,p2); printf("after swap: x=%d y=%d\n",x,y); printf("------------------------------\n"); printf("before fakeswap: x=%d y=%d\n",x,y); fakeswap(x,y); printf("after fakeswap: x=%d y=%d",x,y); return 0; void swap(int* iPtrX, int* iPtrY) int temp; - *iPtrX; temp - *iPtrX = *iPtrY; *iPtrY = temp; void fakeswap(int x,int y) int temp; temp = x; Y = temp; CAWINDOW%ystem32icmd.exe eFore swap: x=10 y=20 Eter swap: x=20 y=10 epope fakeswap: x=20 y=10 F tee fakeswap: x=20 y=1ØPress any key to cont inue
  85. Introduction to C: struct #include //group things together struct database { int id number; int age; float salary; int main() struct database employee; employee.age = 22; employee.id_number = 1 employee.salary = 12000.21 ;
  86. //content in in.list //foo 70 //bar 98 //biz 100 #include int main() FILE *ifp, *ofp; char *mode = r , char outputFilename[] = "out.list"; char username[9]; int score; ifp = fopen("in.list", mode); if (ifp NULL) { fprintf(stderr, "Can't open input file in.list!\n"); exit(l ofp = fopen(outputFilename, "w"); if (ofp NULL) { mode: r - open for reading w - open for writing (file need not exist) a - open for appending (file need not exist) r+ - open for reading and writing, start at beginning w+ - open for reading and writing (overwrite I/O a+ - open for rea Ing and writing (append fprintf(stderr, "Can't open output file exit(l); while (fscanf(ifp, "%s 0/0d", username, &score) 2) { fprintf(ofp, "%s %d\n", username, score+10); fclose(ifp); fclose(ofp); return 0;