1 / 46

Engineering Problem Solving with C Fundamental Concepts

Engineering Problem Solving with C Fundamental Concepts. Chapter 2 Simple C Programs. Overview. Program Structure Constants and Variables Assignment Statement Standard Input and Output Mathematical Function Character Function. Program Structure. Program Structure - General Form.

clarkpaul
Download Presentation

Engineering Problem Solving with C Fundamental Concepts

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. Engineering Problem Solving with C Fundamental Concepts Chapter 2 Simple C Programs

  2. Overview • Program Structure • Constants and Variables • Assignment Statement • Standard Input and Output • Mathematical Function • Character Function

  3. Program Structure

  4. Program Structure - General Form preprocessing directives int main(void) { declarations; statements; } #include <stdio.h> eg #include <math.h>

  5. Program Structure • Comments begin with the characters /* and end with the characters */ • Preprocessor directives give instructions to the compiler. Provides instructions that are performed before the program is compiled. • stdioh.h file = contains info related to the o/p statement used in the program. • math.h file = contain info related to the function used in the program to compute a mathematical function (eg:square root).

  6. Program Structure - continued • Every C program contains one function named main. • Int : indicates the function returns an integer value to the OS. • Void: indicates the function is not receiving any info from OS. • The body of the main function is enclosed by braces, { }

  7. Program Structure - continued • The main function contains two types of commands: declarations and statements. • Declaration: define the memory locations that will be used by the statements. • It may or may not give initial values to be stored. • Declarations and statements are required to end with a semicolon (;) • Preprocessor directives do not end with a semicolon • To exit the program, use a return0; statement

  8. Header Files • Information about the functions can be supplied to the program by using header files • The files have a “.h” extension • The header file is added to the program using the #include preprocessor directive • The #include directive tells the compiler to read in another file and include it in your program • The most common header file is “stdio.h”

  9. Preprocessing directive This file has information about the library function printf has that we have used in our program The mandatory name for the first function to be executed is main The function printf requires that the string be enclosed in double quotes The terms void indicate that nothing is received from the operating system and nothing is return to the operating system. C program body are terminated with a semicolon Terminated the body with a semicolon The string enclosed in parentheses are sent to the library function The beginning and end of the body Call library function printf by using its name followed by parentheses Components of the Lesson #include <stdio.h> void main(void) { printf(“This is C!”); }

  10. Program Structure - First Program /******************************************************************/ /* Program chapter1 */ /* */ /* This program computes the sum two numbers */ #include <stdio.h> int main(void) { /* Declare and initialize variables. */ double number1 = 473.91, number2 = 45.7, sum; /* Calculate sum. */ sum = number1 + number2; /* Print the sum. */ printf(“The sum is %5.2f \n”, sum); /* Exit program. */ return 0; } /***************************************************************************/

  11. Constants and Variables

  12. Constants and Variables • A constant is a specific value • A variable is a memory location that is assigned a name or an identifier • An identifier is used to reference a memory location. • Rules for selecting a valid identifier • must begin with an alphabetic character or underscore • may contain only letters, digits and underscore (no special characters) • case sensitive; thus uppercase letters are different from lower case letter. • cannot use keywords as identifiers (pg 38, table 2.1). This is because keywords have special meaning to the C compiler.

  13. Keywords

  14. Practice!

  15. C Data Types • Integers • short • int • long • Floating-Point Values • float • double • longdouble • Characters • char

  16. short maximum: 32767 int maximum: 2147483647 long maximum: 2147483647 float precision digits: 6 float maximum exponent: 38 float maximum: 3.402823e+038 double precision digits: 15 double maximum exponent: 308 double maximum: 1.797693e+308 long double precision: 15 long double maximum exponent: 308 long double maximum: 1.797693e+308

  17. Symbolic Constants • Defined with a preprocessor directive that assigns an identifier to the constant. • Compiler replaces each occurrence of the directive identifier with the constant value in all statements that follow the directive • Example • #define PI 3.141593

  18. These preprocessor directives cause DAYS_IN_YEAR and PI to be replaced with 365 and 3.14159, respectively in the source code Example #include <stdio.h> #define DAYS_IN_YEAR 365 #define PI 3.14159 void mail() { statement; }

  19. Practice! Give the preprocessor directives to assign symbolic constants for these constants: 1. Speed of light,c =2.99792 X 108 m/s 2. Charge of an electron, e = 1.602177 X 10-19 C • Avogadro’s number, NA =6.022 X 1023 mol-1 • Accelaration of gravity, g =9.8 m/s2 • Unit of length, Unit_length = ‘m’ • Unit of time, Unit_Time = ‘s’

  20. Assignment Statements

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

  22. Assignment Statements - continued • Example 3 int x, y, z; x=y=0; z=2; x y z • Example 4 y=z; y 0 0 2 2

  23. Arithmetic Operators • Addition + • Subtraction - • Multiplication * • Division / • Modulus % • Modulus returns remainder of division between two integers • Example 5%2 returns a value of 1

  24. Mixed Operation • Operation between values with different types • Before operation the value with the lower type is converted or promoted to the higher type • eg: • Cast operator – specify the type change in the value before the next compuation • eg: int sum, count; float average; average = (float)sum/count float converted int float float float

  25. Integer Division • Division between two integers results in an integer. • The result is truncated, not rounded • Example: 5/3 is equal to 1 3/6 is equal to 0

  26. Priority of Operators • Parentheses Inner most first • Unary operators Right to left (+ -) • Binary operators Left to right (* / %) • Binary operators Left to right (+ -)

  27. Increment and Decrement Operators • Increment Operator ++ • post increment x++; • pre increment ++x; • Decrement Operator - - • post decrement x- -; • pre decrement - -x;

  28. Increment and Decrement Operators • If the increment/decrement operator is in prefix position,the identifier is modified and the new value is used to evaluate the rest of the expression. • If the increment/decrement operator is in postfix position, the old value of the identifier is used to evaluate the rest of the expression and then the identifier is modified.

  29. Output: Before increment : i = 1, j = 1 After increment: i = 2, j = 2, k=1, h = 2 Example #include <stdio.h> void main(void) { int i = 1, j = 1, k , h; printf(“Before increment: i = %d, j=%d”, i, j); k= i++; h= ++j; printf(“After increment: i =%d, j=%d, k=%d, h=%d”,i ,j , k, h); }

  30. Practice! For the following statements find the values generated for p and q? int p = 0, q = 1; p = q++; p = ++q; p = q--; p = --q;

  31. Practice • Assume : • int counter=4, a=5, b=-7, c; • And the arithmetic expression statement: c = a % counter++ - b; Answer: counter = ? , c = ?

  32. Abbreviated Assignment Operator operator example equivalent statement += x+=2; x=x+2; -= x-=2; x=x-2; *= x*=y; x=x*y; /= x/=y; x=x/y; %= x%=y; x=x%y;

  33. Abbreviated Assignment Operator • C allows simple assignment statements to be abbreviated. • x=x+3;  x += 3; • sum=sum + x;  sum += x; • d=d/4.5;  d /= 4.5; • r=r%2;  r %=2;

  34. Practice! • Give a memory snapshot after each statement is executed, assuming that x is equal to 2 and that y is equal to 4 before the statement is executed. Also, assume that all the variables are integers. • z=x++*y; • z=++x*y; • x+=y; • y%=x;

  35. Standard Input and Output

  36. Standard Output • printf Function • prints information to the screen • requires two arguments • control string • conversion specifier • Example double angle = 45.5; printf(“Angle = %.2f degrees \n”, angle); Output: Angle = 45.50 degrees Control string Conversion specifier

  37. 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("%1f %c", &distance, &unit_length); • It is very important to use a specifier that is appropriate for the data type of the variable

  38. Practice! Assume that the integer variable sum contains the value 65, the double variable average contains the value 12.368 and that the char variable ch contains the value '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);

  39. Practice! • Write a program to convert from Fahrenheit to Celsius values. The program should prompt the user for Fahrenheit value and then accept the user input (a floating point value). After the input is read into a variable (called fahr), convert the Fahrenheit value according to celsius = (5.0 / 9.0) * (fahr – 32.0) In the above program, change the expression (5.0 / 9.0) to (5 / 9), recompile and run the program, and study the output. Why is the answer wrong?

  40. Library Functions

  41. Library functions • The library functions are important component of C programs • The ANSI C standard specifies a minimum set of library functions to be supplied by all compilers • This is called the: C standard library • The standard library contains functions to perform disk I/O, string manipulation etc. • The code for the library functions is added to the program at ‘link’ time • Using functions for I/O increases flexibility

  42. Math Functions fabs(x) Absolute value of x. sqrt(x) Square root of x, where x>=0. pow(x,y) Exponentiation, xy. Errors occur if x=0 and y<=0, or if x<0 and y is not an integer. ceil(x) Rounds x to the nearest integer toward  (infinity). Example, ceil(2.01) is equal to 3. floor(x) Rounds x to the nearest integer toward - (negative infinity). Example, floor(2.01) is equal to 2. exp(x) Computes the value of ex. log(x) Returns ln x, the natural logarithm of x to the base e. Errors occur if x<=0. log10(x) Returns log10x, logarithm of x to the base 10. Errors occur if x<=0.

  43. TrigonometricFunctions sin(x) Computes the sine of x, where x is in radians. cos(x) Computes the cosine of x, where x is in radians tan(x) Computes the tangent of x, where x is in radians. asin(x) Computes the arcsine or inverse sine of x, where x must be in the range [-1, 1]. Returns an angle in radians in the range [-/2,/2]. acos(x) Computes the arccosine or inverse cosine of x, where x must be in the range [-1, 1]. Returns an angle in radians in the range [0, ]. atan(x) Computes the arctangent or inverse tangent of x. The Returns an angle in radians in the range [-/2,/2]. atan2(y,x) Computes the arctangent or inverse tangent of the value y/x. Returns an angle in radians in the range [-, ].

  44. Character Functions toupper(ch) If ch is a lowercase letter, this function returns the corresponding uppercase letter; otherwise, it returns ch isdigit(ch) Returns a nonzero value if ch is a decimal digit; otherwise, it returns a zero. islower(ch) Returns a nonzero value if ch is a lowercase letter; otherwise, it returns a zero. isupper(ch) Returns a nonzero value if ch is an uppercase letter; otherwise, it returns a zero. isalpha(ch) Returns a nonzero value if ch is an uppercase letter or a lowercase letter; otherwise, it returns a zero. isalnum(ch) Returns a nonzero value if ch is an alphabetic character or a numeric digit; otherwise, it returns a zero.

More Related