APSC 143: Introduction to Programming for Engineers

APSC 143: Introduction to Programming for Engineers

Programming Basics in C

Functions
  • Code is contained within functions.

  • Functions are defined as blocks of code (a sequence of instructions) that perform specific tasks.

  • When a function is “called” (executed), all the instructions within the function are performed.

  • This mechanism allows for code reusability.

Parts of a Function
  • Return Type: The type of variable outputted by the function.

  • Name: The identifier used to call and utilize the function.

  • Arguments: The variables passed to the function for it to work with.

The Main Function
  • All C programs are organized around the main function.

  • Characteristics of the main function:

    • Return type is int (returns 0 upon successful execution, or 1 if an error occurs).

    • Named main.

    • Contains no arguments.

  • Definition format:

  int main() {
      return 0;
  }
Using Functions
  • To call a function, type its name followed by its arguments (if any) in brackets, and terminate with a semicolon:

  nameOfFunction(argument1, argument2);
  • Functions with no arguments will have empty brackets: nameOfFunction();.

  • Returned values can be assigned to a variable:

  returnType variableName = nameOfFunction(argument);
  • Functions without a return type cannot be assigned to a variable.

Commenting Code

  • Single line comments are initiated with //, ignoring all text that follows it on the same line.

  • Multi-line comments are enclosed between /* ... */, ignoring all text in between.

  • Comments serve to explain the code to programmers.

Programming Style
  • Follow naming conventions (camelCasing).

  • Use meaningful identifiers for variables.

  • Employ comments effectively.

  • Indent code cleanly when contained within {}.

  • Example of a simple program:

  int main() {
      // Variable for my height
      float myHeight = 72.0;
  }

Printing Variables to Screen

Printing Output
  • Output to the screen can be achieved using the printf() function.

  • The standard input & output library must be included.

Headers
  • Header files have a .h extension and contain function declarations and definitions.

  • The standard input & output library header is stdio.h.

  • Include syntax:

  #include <stdio.h>
  • Note: No semicolon is placed at the end of the include statement.

Printing Text Only
  • To print text, include the text as an argument in quotation marks:

  int main() {
      printf("Hello, world!");
  }
Print Text with Variables
  • To print both text and a variable, provide the variable as an additional argument, utilizing format specifiers.

  • Common format specifiers include:

    • %d for integers

    • %f for floating-point numbers

    • %c for characters

  • Mismatched format specifiers may lead to unexpected outputs.

  • Example of usage:

  printf("The value of x is %d", x);
  printf("Height is %f and age is %d", height, age);
Formatting Options
  • Format specifiers can also specify width and precision:

    • Width: Total spaces allotted for output with optional leading zeros.

    • Precision: Number of decimal points (for floating-point numbers).
      Example syntax:

  %[width].[precision][type]

Printing Examples & The Escape Character

Examples of Print Output
  • Example C code demonstrating output formatting:

  int x = 5;
  float y = 4.83;
  printf("The value of x is %d", x);
  printf("The value of x is %4d", x);
  printf("The value of x is %04d", x);
  printf("The value of y is %f", y);
  printf("The value of y is %8.2f", y);
  printf("The value of y is %8.4f", y);
  • Demonstrated printed outputs:

    • The value of x is 5

    • The value of x is 5

    • The value of x is 0005

    • The value of y is 4.830000

    • The value of y is 4.83

    • The value of y is 4.8300

Escape Character
  • Use a backslash (\) to escape special characters in strings:

    • Examples: ", \, and .

  • Notably, to include a % character, use %%.

  • Example using escape sequences:

  printf("The word \"Hello\" contains 40%% 'l'.");
Special Escape Sequences
  • The escape character can affect output formatting:

    • \n for a new line.

    • \t for a tab.

Mathematical Expressions

What are Expressions?
  • Expressions involve mathematical operations to manipulate data and typically store the result in a variable.

  • Operators (arithmetic symbols) are applied to operands (variables or numbers).

Binary Arithmetic Operators
  • Operators that operate on two operands include:

    • Addition (+) – Example: y = x + 5;

    • Subtraction (-) – Example: y = x - 5;

    • Multiplication (*) – Example: y = x * 5;

    • Division (/) – Example: y = x / 5;

    • Modulus (%) – Example: y = x % 5; (remainder after division).

Unary Arithmetic Operators
  • Operators that operate on a single operand include:

    • Unary plus (+) – Example: y = +x;

    • Unary minus (-) – Example: y = -x;

    • Increment (++) – Example: y = ++x; or y = x++;

    • Decrement (--) – Example: y = --x; or y = x--;

Evaluating Increment and Decrement Operators
  • Preceding Operator: Changes the value before evaluation:

  int n = 1;
  int x = 2 * (++n); // x = 4, n = 2
  • Following Operator: Uses original value before changing:

  int n = 1;
  int x = 2 * (n++); // x = 2, n = 2
Assignment Operators
  • Using assignment operator to combine operations:

    • For example, y = y + 5; is equivalent to y += 5;.

  • Other examples include:

    • y = y - 5; equivalent to y -= 5;

    • y = y / x; equivalent to y /= x;

    • y = y * (x + 1); equivalent to y *= (x + 1);

Order of Operations (BUDMMASA)
  • Expressions evaluated per order:

    • Brackets: Innermost first.

    • Unary Operations: Right to left.

    • Division, Multiplication, Modulus: Left to right.

    • Addition, Subtraction: Left to right.

    • Assignment Operations: Not applicable.

Mathematical Functions & Constants

Mathematical Functions
  • Functions exist for nearly all mathematical operations in code.

  • To utilize built-in functions, include the math library via:

  #include <math.h>
Common Mathematical Functions
  • Examples of useful mathematical functions:

    • Sine: sin(double) (in radians).

    • Cosine: cos(double) (in radians).

    • Tangent: tan(double) (in radians).

    • Exponential: exp(double).

    • Power: pow(double, double) (e.g., pow(2, 3) = 8).

    • Square Root: sqrt(double).

    • Natural Logarithm: log(double).

    • Absolute Value: abs(int) (e.g., abs(-2) = 2).

    • Rounding functions like round(double), floor(double), and ceil(double), with respective example usages.

Constants
  • The math library contains useful constants (e.g., M_PI for π).

  • Custom constants can be defined using:

  #define NAME value
  • Requires no type declaration; conventional naming is all capital letters.

  • Once defined, constants can be reused throughout the program.

Example Using Constants
  • Example code showing computation with defined constants:

  #include <math.h>
  #define PI 3.14159

  int main() {
      int radius = 4;
      float area = PI * pow(radius, 2);
      printf("The area of the circle is %f", area);
  }
  • Possible output: The area of the circle is 50.334400.

Mixing Variable Types & Casting

Mixing Variable Types
  • Mixed variable types in expressions yield results of the largest type:

    • Order of type precedence: int < long < float < double.

    • Result type gets converted to the variable type assigned.

Truncation
  • Truncation occurs when a floating-point value is stored as an integer:

  int x = 7.6;
  printf("x = %d", x);
  • Output: x = 7.

Example of Truncation Effects
  • Operations may cause truncation even if results are stored as float:

  float x = 21/4; // evaluates as integer due to division
  printf("x = %0.2f", x);
  • Output: x = 5.00.

    • Correct floating-point evaluation:

  float x = 21.0/4;
  printf("x = %0.2f", x);
  • Output: x = 5.25.

Casting
  • Casting allows explicit type conversion in expressions:

    • Syntax for casting:

  float x = (float) 21/4;
  printf("x = %0.2f", x);
  • Output: x = 5.25.

Casting with Multiple Variables
  • Casting can be applied on operations with multiple variables:

  int y = 21;
  int z = 4;
  float x = (float) y/z;
  printf("x = %0.2f", x);
  • Output: x = 5.25.

Caution During Casting
  • Brackets impact the casting process:

  float x = (float) (21/4);
  printf("x = %0.2f", x);
  • Output: x = 5.00.

    • Correct casting with brackets:

  int y = 21;
  int z = 4;
  float x = (float) (y/z);
  printf("x = %0.2f", x);
  • Output: x = 5.00.

Getting User Input

User Input
  • Programs can cater to different scenarios by accepting user input.

  • Utilize scanf() from the standard input & output library for this purpose:

  scanf("%f", &usersFloat);
Using scanf
  • scanf requires two arguments:

    • A format specifier for the type of input.

    • The address of a variable where input is stored (indicated by &).

Getting Multiple Inputs
  • scanf can read multiple inputs either:

    • Through sequential function calls.

    • Through a single scanf call with multiple format specifiers:

  scanf("%f %f %f", &variable1, &variable2, &variable3);
  • Users can provide inputs on separate lines or in a single line separated by spaces.

Our First Programs

Example Program for Getting User Input
  • Sample C program prompting user for integers and outputting their sum:

  #include <stdio.h>

  int main() {
      int value1;
      int value2;
      printf("Please give two integer values\n");
      scanf("%d %d", &value1, &value2);
      printf("The sum is %d", value1 + value2);
  }

Our First Errors

Types of Programming Errors
  • Three primary categories of programming errors include:

    • Syntax Errors: Detected by the compiler.

    • Runtime Errors: Cause the program to unexpectedly abort.

    • Logic Errors: Produce incorrect results despite no errors in the code.

Error Demonstrations
  • Syntax Error Example: Misassigned value:

  i = 30;
  printf("%d", i);
  • Runtime Error Example: Division by zero:

  int i = 1/0;
  printf("%d", i);

Printing Student Information Example

Student Information Output
  • Task: Output information about two anonymous students (e.g., names, ages, heights):

  #include <stdio.h>

  int main() {
      char student = 'B';
      int age = 34;
      float height = 173.7;
      printf("Student %c is %d years old and %.1f cm tall. \n", student, age, height);
      student = 'C';
      age = 28;
      height = 165.1;
      printf("Student %c is %d years old and %.1f cm tall. \n", student, age, height);
  }
  • Example Output:

    • Student: B Age: 34 years Height: 173.7 cm

    • Student: C Age: 28 years Height: 165.1 cm

Computing the Volume of a Sphere Example

Volume Calculation
  • Task: Compute volume of a sphere with radius r = 4.2 cm:

    • Formula: V=rac43imesextπr3V = rac{4}{3} imes ext{π} r^3

  #include <stdio.h>
  #include <math.h>

  int main() {
      float radius = 4.2;
      float volume;
      volume = (4/3.0) * M_PI * pow(radius, 3);
      printf("Volume is %.3f cm cubed.", volume);
  }

Computing the Impact Velocity of a Sphere Example

Velocity Calculation
  • Task: Determine the velocity of a ball dropped from a height of h = 2.75 m:

    • Formula: v=ext(2h)v = ext{√}(2h), where gravitational acceleration g=9.8racms2g = 9.8 rac{m}{s^2}

  #include <stdio.h>
  #include <math.h>

  int main() {
      float height = 2.75;
      float g = 9.8;
      float velocity;
      velocity = sqrt(2 * g * height);
      printf("The velocity of the ball when it hits the floor is %2f m/s. \n", velocity);
  }

Computing the Average Number of Goals Scored Example

Goals Calculation
  • Task: Compute total goals and average from individual player goals:

  #include <stdio.h>

  int main() {
      int goals_1, goals_2, goals_3;
      int total;
      float average;
      goals_1 = 14;
      goals_2 = 21;
      goals_3 = 27;
      total = goals_1 + goals_2 + goals_3;
      average = (goals_1 + goals_2 + goals_3) / 3.0;
      printf("The total number of goals is %d. \n", total);
      printf("The average number of goals is %f. \n", average);
  }
  • Individual player goals: 14, 21, 27.