C Programming Fundamentals: Math, Control Structures, and Arrays, Study notes of Engineering

Various fundamental concepts in c programming, including arithmetic and mathematical operations, increment and decrement operators, mixed operations, switch-case structures, while and for loops, assignment operators, and arrays (1-d and 2-d). It includes examples and best practices for each concept.

Typology: Study notes

Pre 2010

Uploaded on 09/02/2009

koofers-user-z26
koofers-user-z26 🇺🇸

10 documents

1 / 15

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
ENGR 0012 – Dr. Lund’s 10am Section
March 13 & 15, 2007
Section 5.3 – Basic Mathematical Operations
Arithmetic operations
Assignment operators
Mathematical functions (<math.h>)
Section 5.4 – Program Control
Branching (IF & SWITCH-CASE)
Looping (FOR, WHILE, & DO-WHILE)
Using FOR loops with arrays
Summary of String Concepts
Arithmetic Operations
+ - * / follow same rules of precedence as Matlab
Must maintain consistency in how variables are declared
and used
A number without a decimal point will be treated as an
integer, until multiplied or divided by a real number
This can cause problems…
Ex: double a;
a = 1/3 +1/3 + 1/3;
#include <stdio.h>
void main(void)
/* This program illustrates
importance of decimal point */
{double a, b;
a=1/3+1/3+1/3;
printf("a = %lf\n", a);
b=1./3+1./3+1./3;
printf("b = %lf\n", b);
}
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download C Programming Fundamentals: Math, Control Structures, and Arrays and more Study notes Engineering in PDF only on Docsity!

ENGR 0012 – Dr. Lund’s 10am Section

March 13 & 15, 2007

• Section 5.3 – Basic Mathematical Operations

– Arithmetic operations

– Assignment operators

– Mathematical functions (<math.h>)

• Section 5.4 – Program Control

– Branching (IF & SWITCH-CASE)

– Looping (FOR, WHILE, & DO-WHILE)

– Using FOR loops with arrays

• Summary of String Concepts

Arithmetic Operations

• + - * / follow same rules of precedence as Matlab

• Must maintain consistency in how variables are declared

and used

• A number without a decimal point will be treated as an

integer, until multiplied or divided by a real number

• This can cause problems…

Ex: double a;

a = 1/3 +1/3 + 1/3;

#include <stdio.h> void main(void)

/* This program illustrates importance of decimal point */ { double a, b;

a=1/3+1/3+1/3; printf("a = %lf\n", a);

b=1./3+1./3+1./3; printf("b = %lf\n", b); }

Arithmetic Operations

• Bonus arithmetic operators:

– i++, ++i (increments i by one, i = i + 1)

– k = i++ is same as k = i; i = i + 1 (post-increment)

– k = ++i is same as k = i +1 (pre-increment)

– % gives remainder of one integer divided by another

• Math functions included in <math.h> library:

– pow(x,y)

– sin(x), cos(x), tan(x), sinh(x), cosh(x), tanh(x)

– log(x), log10(x)

– exp(x)

– abs(x)

Increment/Decrement

  • For integer math only!
  • Preincrement (++a) will

increment the variable by

1 and then print the

output

  • Post increment will print

the output and then

increment by 1

  • Similar operations for

decrementing by one

  • Very useful for loops

#include <stdio.h>

main()

int a = 10;

++a; /* same as a = a + 1; */

printf(“a = %d\n”, a);

printf(“a = %d\n”, ++a);

a++;

printf(“a = %d\n”, a);

printf(“a = %d\n”, a++);

a--;

printf(“a = %d\n”, a);

printf(“a = %d\n”, a--);

IF Control Structures in C

• Simple if structure:

if (condition)

{ statement(s)}

• Relational operators Logical Expressions

< >! NOT

<= >= && AND

= =! = || OR

• Example:

if ( x <= 10.0)

y = x*x;

printf(“Whatever…”);

If – Else and If – Else if - Else

  • if (a != 1)

if ( b > 1)

statements;

else

statements;

else

statements;

  • if (a <= 0 && b <= 0)

statements;

else if (a = = 0)

statements;

else if (b = = 0)

statements;

else

statements;

Note nesting.

Example

#include <stdio.h> void main(void) { int option;

printf("Please type 1, 2, or 3\n" "1. Breakfast\n" "2. Lunch\n" "3. Dinner\n"); scanf("%d",&option);

if(option==1) { printf("Good morning\n"); printf("Order breakfast\n"); } else if (option==2) { printf("Order lunch\n"); } else if (option==3) { printf("Order dinner\n"); } else { printf("Order nothing\n"); } }

Type in this code:

SWITCH / CASE structures

• switch ( variable )

case value1 : statement;

statement;

break;

case value2 : statement;

statement;

break;

default:

statements;

Note:

1. location of braces

2. colon after value

3. break;

4. default:

Simple for loop structure

• i = control variable

• Control variable must be declared in program

• for loop expression within parentheses contains three

components:

• i = 1; Initialization expression

(Occurs at beginning of first pass through loop)

• i <= 10; Continuation or test expression

(Loop continues if this expression is TRUE)

• i = i + 1 Increment Expression

(Occurs after statements are completed)

for (i = 1; i <= 10; i = i + 1)

statements

Some variations on loop expression…

• for (i = start; i < end; i = i + 1)

i, start, end must be declared

• for (test = 10; test >= 1; test = test –1)

loop variable can start high to low

• for (k = 2; k < 100; k = k * 2)

loop variable can be incremented in any way

• for (j = 1; j <= finish; j++)

increment expression can be written in short

form:

j++ is same as j = j + 1

j- - is same as j = j – 1

j+=2 is same as j = j + 2

j*=2 is same as j = j * 2

Assignment Operators

x += 2 is equivalent to x = x + 2

x -= 3 is equivalent to x = x – 3

x *= -5 is equivalent to x = x * -

x /= 7 is equivalent to x = x / 7

x %= 4 is equivalent to x = x % 4

  • Convenient shortcuts and they execute faster as well

Simple for loop example

/* sum the first n digits (1, 2,.. ., n) */

#include <stdio.h>

main() { int count, /* the loop index / n, / the number of digits (number of passes) / sum; / the cumulative sum */

printf("Sum the first n digits\n\n"); printf("How many digits? "); scanf("%d", &n);

sum = 0; for (count = 1; count <= n; count++) { sum = sum + count; }

printf("\nThe sum is %d\n", sum); }

One last loop… the do / while loop

General format:

do

statements;

} while (test expression);

#inlcude <stdio.h>

main ()

int j = 4;

do

printf(“Old j = %d, “, j);

j = j - 1;

printf(“new j = %d\n”, j);

} while (j >= 1);

while loop vs. do / while loop

#inlcude <stdio.h>

main ()

int j = 4;

do

printf(“Old j = %d, “, j);

j = j - 1;

printf(“new j = %d\n”, j);

} while (j >= 1);

#inlcude <stdio.h>

main ()

int j = 4;

while (j >= 1)

printf(“Old j = %d, “, j);

j = j - 1;

printf(“new j = %d\n”, j);

The only difference between a while loop and a do/while loop is that if the

test expression is FALSE at the beginning of a while loop, the loop will not

execute; whereas with the do/while loop, if the expression is FALSE to begin

with, the loop would be executed once before exiting.

An array is a collection^ of elements that have the same name.

All elements must be of the same data type.

An integer-valued subscript is used to access an individual array element.

Subscripts range in value from 0 to n - 1 , where n is the size of the array.

x[0] x[1] x[2] x[n−2] x[n−1]

“1-d Arrays” (vectors)

Contiguous Physical Memory Locations…

Declaring 1-D Arrays

#include <stdio.h>

void main(void) {

float x[100], y;

int values[50], m, n;

  • Defines a 100-element array called x.
  • All 100 elements are floating point.
  • Individual array elements are x[3], x[i], x[j + 2], etc. (where i and j are integer variables). Note: 3, i and j + 2 are subscripts.
  • Subscript values range from 0 to 99. First element is x[0]
  • Defines a 50-element array called values.
  • All elements are integers.
  • Subscript values range from 0 to 49.

Type Name Length temp[0] temp[1] temp[2] temp[3] temp[4]

int temp [100];

Memory Addresses: 1000 1004 1008 1012 1016

?????

2-Dimension Arrays

• Syntax for a 2-D array

matrix_a[rows][cols]

• Example

• matrix_a[2][3] = -

matrix_a

  • Note separate brackets for each dimension
  • Rows are specified in first set of brackets

Storage of 2-D Arrays

• Data is stored in memory by rows, i.e.

right most variable varies first

• For x [3][4] which has 3 rows, 4

columns…

x[0][0] x[0][1] x[0][2] x[0][3] x[1][0] x[1][1]

Memory Address (4 bytes per number)

x[1][2] x[1][3] x[2][0] …

FF74 FF78 FF7C FF80 … (hexadecimal address system)

Remember! In C, the first element of an array dimension is a zero

Declaring 2-D Arrays

There are several ways 2-D arrays can be

declared…

  • double a[2][3]; //Not initialized; max of 2 rows, 3 columns
  • double a[2][3]={1,2,3,4,5,6}; //Initialize on one line
  • double a[2][3]={{1,2,3}, {4,5,6}}; //Initialize by rows in { }
  • double a[ ][3]={1,2,3,4,5,6}; //Let C determine number of rows
  • double a[2][3]={ }; //Initialize with all zeroes

Input / Output with 2-D Arrays

#include <stdio.h> #define N 3

main() { double a[N][N]; int i, j;

printf("\n\nPlease enter the elements of MATRIX A:\n"); for (i=0; i<N; i++) { for (j=0; j<N; j++) { printf("Enter element in ROW=%d, COL=%d: ", i+1, j+1); scanf("%lf", &a[i][j]); } }

Continued on next page…