1 / 197

Turgay Korkmaz Office: NPB 3.330 Phone: (210) 458-7346 Fax: (210) 458-4437

CS xxxx Foundations of Programming and Data Structures Ch 1 – Overview – C programming Language. Turgay Korkmaz Office: NPB 3.330 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: www.cs.utsa.edu/~korkmaz. What is C?.

carlyj
Download Presentation

Turgay Korkmaz Office: NPB 3.330 Phone: (210) 458-7346 Fax: (210) 458-4437

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS xxxx Foundations of Programming and Data Structures Ch 1 – Overview – C programming Language Turgay Korkmaz Office: NPB 3.330 Phone: (210) 458-7346 Fax: (210) 458-4437 e-mail: korkmaz@cs.utsa.edu web: www.cs.utsa.edu/~korkmaz

  2. What is C? • General purpose, machine-independent, high-level programming language • Developed at Bell Labs in 1972 by Dennis Ritchie • American National Standards Institute (ANSI) approved ANSI C standard in 1989 Source file

  3. Hello World! in Linux • Login to a linux machine • SSH Secure Shell (e.g., elk03.cs.utsa.edu) elk03:> mkdirmyprog elk03:> cdmyprog elk03:> picohello.c • Type your program … and save it (ctrl-o) • Compile and execute your program elk03:> gcchello.c –o hello elk03:> hello

  4. C Programming Language What is the best way to learn a language? Look at sample programs Read different books Practice, practice, practice… From web: “The absolute best way to immerse yourself quickly is to find a boyfriend or girlfriend who speaks the native language you are trying to learn”

  5. no yes Here is the first sample • Problem: generate a table showing the values of N2 and 2N for various values of N from 0 to 12 • I/O:  program  N, N2, 2N • Hand example N | N2 | 2N -------------- 0 | 0 | 1 1 | 1 | 2 2 | 4 | 4 3 | 9 | 8 4 | 16 | 16 5 | 25 | 32 6 | 36 | 64 … 12 | 144 | 4096 4. Develop solution and Coding 5. Testing

  6. /* * File: powertab.java * ---------------- * This program generates a table comparing values * of the functions n^2 and 2^n. */ import java.io.*; public class powertab { • /* • * Constants • * --------- • * LowerLimit -- Starting value for the table • * UpperLimit -- Final value for the table • */ • public static final init LowerLimit = 0; • public static final init UpperLimit = 12; • /* Main program */ • public static main() • { • int n; • System.out.println(" | 2 | N"); • System.out.println(" N | N | 2"); • System.out.println("----+-----+------"); • for (n = LowerLimit; n <= UpperLimit; n++) { • System.out.format(" %2d | %3d | %4d\n", n, • RaiseIntToPower(n, 2), • RaiseIntToPower(2, n)); • } • } • /* • * Function: RaiseIntToPower • * Usage: p = RaiseIntToPower(n, k); • * --------------------------------- • * This function returns n to the kth power. • */ • private static intRaiseIntToPower(int n, int k) • { • inti, result; • result = 1; • for (i = 0; i < k; i++) { • result *= n; • } • return (result); • } } /* * File: powertab.c * ---------------- * This program generates a table comparing values * of the functions n^2 and 2^n. */ #include <stdio.h> #include "genlib.h" /* * Constants * --------- * LowerLimit -- Starting value for the table * UpperLimit -- Final value for the table */ #define LowerLimit 0 #define UpperLimit 12 /* Private function prototypes */ static intRaiseIntToPower(int n, int k); /* Main program */ main() { int n; printf(" | 2 | N\n"); printf(" N | N | 2\n"); printf("----+-----+------\n"); for (n = LowerLimit; n <= UpperLimit; n++) { printf(" %2d | %3d | %4d\n", n, RaiseIntToPower(n, 2), RaiseIntToPower(2, n)); } } /* * Function: RaiseIntToPower * Usage: p = RaiseIntToPower(n, k); * --------------------------------- * This function returns n to the kth power. */ static intRaiseIntToPower(int n, int k) { inti, result; result = 1; for (i = 0; i < k; i++) { result *= n; } return (result); } Exercise: write the same program in Java

  7. Comments, Preprocessor (library inclusion, program level symbolic definitions) function prototypes main function { Variable declarations, Statements (must end with ;) } Other user-defined functions Structure of a C Program /* * File: powertab.c * ---------------- * This program generates a table comparing * values of the functions n^2 and 2^n. */ #include <stdio.h> #include "genlib.h" /* * Constants * --------- * LowerLimit -- Starting value for the table * UpperLimit -- Final value for the table */ #define LowerLimit 0 #define UpperLimit 12 /* Private function prototypes */ static intRaiseIntToPower(int n, int k); /* Main program */ main() { int n; printf(" | 2 | N\n"); printf(" N | N | 2\n"); printf("----+-----+------\n"); for (n = LowerLimit; n <= UpperLimit; n++) { printf(" %2d | %3d | %4d\n", n, RaiseIntToPower(n, 2), RaiseIntToPower(2, n)); } } /* * Function: RaiseIntToPower * Usage: p = RaiseIntToPower(n, k); * --------------------------------- * This function returns n to the kth power. */ static intRaiseIntToPower(int n, int k) { inti, result; result = 1; for (i = 0; i < k; i++) { result *= n; } return (result); }

  8. https://www.zentut.com/c-tutorial/c-comments/ Comments • Document your code to make the code easier to understand so you or someone else can maintain it better in the future. /* some description or explanation in multiple lines */ // single line description

  9. True or False? • Comments should describe why a block of code or function does instead of telling how it works. • For example, you should say “calculate the area of a circle” instead of “A product of radius and PI”. • Comments help you and other programmers understand a piece of code easier and faster in the future. • Therefore when you write comments, ask yourself if you or other can understand how it works by reading the comments only.

  10. https://www.zentut.com/c-tutorial/c-variables/ Variables • What is a variable in math? f(x) = x2+x+4 • What is a variable in C? • An identifier or variable name is used to reference a memory location that holds a data value • A variable must be declared before it is used. type name; • int a, b;

  11. Variables in Memory int x1=1,x2=7; double distance; name address Memory - content … 12 16 20 24 28 … CPU x1 x2 distance

  12. Memory Snapshot

  13. Rules for selecting a valid identifier (variable name) • Begin with an alphabetic character or underscore (e.g., abcABC_) • Use only letters, digits and underscore (no special characters ^%@) • Case sensitive (AbC, aBcare different) • Cannot use C keywords

  14. Are the following valid identifiers? initial_time DisTaNce X&Y distance 1x x_1 rate% x_sum switch

  15. Local and Global Variables int global_var; void main() { int local_a=5; global_var = 7; f1(); print global_var; } int f1() { int local_a=9; global_var = 11; } • Local scope • a local variable is defined within a function or a block and can be accessed only within the function or block that defines it • Global scope • a global variable is defined outside the main function and can be accessed by any function within the program file.

  16. C Numeric Data Types

  17. REF Example Data-Type Limits printf("sizeof(short) = %d bytes\n", sizeof(short)); printf("sizeof(int) = %d bytes\n", sizeof(int)); printf("sizeof(unsigned int) = %d bytes\n", sizeof(unsigned int)); printf("sizeof(long) = %d bytes\n", sizeof(long));

  18. C Character Data Type: char char result =‘Y’; In memory, everything is stored as binary value, which can be interpreted as char or integer. Examples of ASCII Codes

  19. char in Memory name address Memory - content How to represent ‘a’ ? char My_letter=‘a’; int My_number = 97 Always we have 1’s and 0’s in the memory. It depends on how you look at it? For example, 01100001 is 97 if you look at it as int, or ‘a’ if you look at it as char ‘3’ is not the same as 3 How to represent 2.5? … 12 16 20 … My_letter My_number

  20. String • Sequence of characters or array of characters (will be covered later) “this is a string” • There is no explicit string type in C, but • char str[20]; vs. char *str2; • there are several string functions in standard C library string.h • we will see all these libraries in ch3

  21. Boolean type • TRUE or FALSE • There is no explicit Boolean type in C • Zero means FALSE • Other than zero means TRUE

  22. https://www.zentut.com/c-tutorial/c-typedef/ Define a new type by renaming an old type typedef • What is the difference between intpartNumberT, serialNumberT; typedefintpartNumberT, serialNumberT; partNumberT x, y; vs. int x, y; • New types may provide more information • Easily change the underlying representation typedeflongpartNumberT;

  23. https://www.zentut.com/c-tutorial/c-enum/ New Atomic Data Types in C • C allows to define new atomic types called enumeration types typedefenum { element-list } type_name; For example: typedefenum { North, East, South, West }directionT; directionT dir; /* declare a variable */

  24. Internal representation of enum types • Stored as integers starting with 0 • North=0, East=1, South=2, West=3. • We can change these values typedefenum { Penny=1, Nickle=5, Dime=10, Quarter=25, HalfDollar=50 }coinT; typedefenum { January=1, February, March … }monthT; #define January 1 #define February 2 #define March 3 …

  25. Scalar types • enum types, char, and int, short, long etc are called scalar type and automatically converted to integer • So any operations on scalar type are the same as for integers directionTRightFrom(directionT dir) { return ((dir+1)%4); } … for(m=January; m <=December; m++) …

  26. Scalar types (cont’d) • You can use scalar types as integers printf(“direction is %d\n”, North); will print 0 • If you need to print the name itself you need a function like the following char *DirectionName(directionT dir) { switch(dir) { case North: return(“North”); case East: return(“East”); case South: return(“South”); case West: return(“West”); } }

  27. Exercise: Boolean type • How can we define a new bool type and use FALSE and TRUE in C? bool cond1; cond1=TRUE; typedefenum{FALSE, TRUE} bool; • How about • typedefenum{TRUE, FALSE} bool;

  28. https://www.zentut.com/c-tutorial/c-constants/ Constants • A constant is a specific value that we use in our programs. For example 3.14, 97, ‘a’, or “hello” • In your program, int a = 97; char b =‘a’; double area, r=2.0; double circumference; area = 3.14 * r*r; circumference = 2 * 3.14 * r; a b area circumference r

  29. Symbolic Constants • What if you want to use a better estimate of ? For example, you want 3.141593 instead of 3.14. • You need to replace all by hand  • Better solution, define  as a symbolic constant, e.g. #define PI 3.141593 … area = PI * r * r; circumference = 2 * PI * r; • Defined with a preprocessor directive • Compiler replaces each occurrence of the directive identifier with the constant value in all statements that follow the directive

  30. /* Declare and initialize variables. */ • double x1=1, y1=5, x2=4, y2=7, • side_1, side_2, distance; Simple I/O Recall the program computing distance between two points. Instead of giving the points in the source code, how can we get them from the user?

  31. Simple Input and Output • There is a standard I/O library for • displaying results on the screen: printf() • accepting input from user: scanf() • To use these functions, we need to use #include <stdio.h>

  32. Standard Output • printf Function • prints information to the screen • requires two arguments • control string • Contains text, conversion specifiers or both • Identifier to be printed • Example double angle = 45.5; printf(“Angle = %.2f degrees \n”, angle); Output: Angle = 45.50 degrees Conversion Specifier Control String Identifier

  33. Conversion Specifiers for Output Statements Frequently Used

  34. Standard Output Output of -145 Output of 157.8926 Exercise

  35. Exercise int sum = 65; double average = 12.368; char ch = ‘b’; Show the output line (or lines) generated by the following statements. • printf("Sum = %5i; Average = %7.1f \n", sum, average); • printf("Sum = %4i \n Average = %8.4f \n", sum, average); • printf("Sum and Average \n\n %d %.1f \n", sum, average); • printf("Character is %c; Sum is %c \n", ch, sum); • printf("Character is %i; Sum is %i \n", ch, sum); Exercise

  36. Exercise (cont’d) • Solution Sum = 65; Average = 12.4 Sum = 65 Average = 12.3680 Sum and Average 65 12.4 Character is b; Sum is A Character is 98; Sum is 65 Exercise

  37. A useful feature of printf printf(“%5d\n”, value); We can have a more general form of this as printf(“%*d\n”, fieldWidth, value); Exercise

  38. Standard Input • scanf Function • inputs values from the keyboard • required arguments • control string • memory locations that correspond to the specifiers in the control string • Example: double distance; char unit_length; scanf("%lf %c", &distance, &unit_length); • It is very important to use a specifier that is appropriate for the data type of the variable What will happen if you forget & before the variable name?

  39. Conversion Specifiers for Input Statements Frequently Used

  40. Exercise • /* if you use the • standard library */ • #include <stdio.h> • … • float f; • inti; • scanf(“%f %d“, &f, &i); • What will be the values stored in f andiafter scanf statement if following values are entered 12.5 1 12 45 12 23.2 12.1 10 12 1 Exercise

  41. Best practice • You don’t need to have a printf before scanf, but it is good to let user know what to enter: printf(“Enter x y : ”); scanf(“%d %d”, &x, &y); • Otherwise, user will not know what to do!

  42. Exercise: How to input two points without re-compiling the program /*if you use the stdio.h library*/ printf(“enter x1 y1: “); scanf(“%lf %lf“, &x1, &y1); printf(“enter x2 y2: “); scanf(“%lf %lf“, &x2, &y2); /*if you use the textbook’s library */ #include "genlib.h" #include "simpio.h" printf(“enter x1: “); x1=GetReal(); printf(“enter y1: “); y1=GetReal(); printf(“enter x2: “); x2=GetReal(); printf(“enter y2: “); y2=GetReal();

  43. Program to Print Values as Characters and Integers

  44. C Programming Language: Expressions Often we need to compute some math formulas/expressions… C expressions composed of terms (variables) and operators (+-*/%) which are very similar to the ones in math, So you can easily transform one to another

  45. Assignment Statements • Used to assign a value to a variable • General Form: identifier = expression; /* ‘=‘ means assign expression to identifier */ • Example 1 double sum = 0; • Example 2 int x; x=5; • Example 3 char ch; ch = ‘a’; sum x ch

  46. Assignment examples (cont’d) • Example 3 int x, y, z; x = y = 0; right to left! Z = 1+1; • Example 4 y=z; y=5; x y z 2 5

  47. Assignment examples with different types 2 int a, b=5; double c=2.3; … a=c; /* data loss */ c=b; /* no data loss */ a b c 5.0 • long double, double, float, long integer, integer, short integer, char • Data may be lost. Be careful!  No data loss

  48. Exercise: swap • Write a set of statements that swaps the contents of variables x and y x 3 x 5 y 5 y 3 Before After Exercise

  49. Exercise: swap First Attempt x=y; y=x; x x x 3 5 5 y 5 y 5 y 5 Before After x=y After y=x Exercise

  50. Exercise: swap Solution temp= x; x=y; y=temp; x x x x 3 5 5 3 y y y y 5 5 5 3 temp temp temp temp 3 3 3 ? Before after temp=x after x=y after y = temp Will the following solution work, too? temp= y; y=x; x=temp; Exercise

More Related