stevepedwards.com/DebianAdmin linux mint IT admin tips info

Chapter 6 Notes – Practical C Programming, 3rd Edition By Steve Oualline

Chapter 6 explains simple decision statements including if, else, and for. A discussion of == versus = is presented.

If the condition is true (nonzero), the statement will be executed. If the condition is false (0), the statement will not be executed.

if (total_owed <= 0)

printf("You owe nothing.\n");

Multiple statements may be grouped by putting them inside curly braces ({}). For

example:

if (total_owed <= 0)

{

++zero_count;

printf("You owe nothing.\n");

}

An alternate form of the if statement is:

if (condition)

statement;

else

statement;

If the condition is true (nonzero), the first statement is executed. If it is false (0),

the second statement is executed.

According to the C syntax rules, the else goes with the nearest if:

if (count < 10) {

/* if #1 */

if ((count % 4) == 2)

/* if #2 */

printf("Condition:White\n");

else

printf("Condition:Tan\n");

}

The function strcmp compares two strings, and then returns zero if they are equal

or nonzero if they are different. To check if two strings are equal, we use the code:

/* Check to see if string1 == string2 */

if (strcmp(string1, string2) == 0)

printf("Strings equal\n");

else

printf("Strings not equal\n");

Some programmers omit the comment and the == 0 clause. These omissions lead to

the following confusing code:

if (strcmp(string1, string2))

printf("......");

At first glance, this program obviously compares two strings and executes the printf statement if they are equal. Unfortunately, the obvious is wrong. If the strings are equal, strcmp returns 0, and the printf is not executed. Because of this backward behavior of strcmp , you should be very careful in your use of strcmp and always comment its use.

The while statement is used when the program needs to perform repetitive tasks.

The general form of a while statement is:

while (condition)

statement;

The program will repeatedly execute the statement inside the while until the condition becomes false (0). (If the condition is initially false, the statement will not be executed.)

The Fibonacci sequence is:

1 1 2 3 5 8

The terms are computed from the equations:

1

1

2 = 1 + 1

3 = 1 + 2

5 = 2 + 3

etc.

In general terms this is:

f n = f n-1 + f n-2

This is a mathematical equation using mathematical variable names (f n ).

Mathematicians use this very terse style of naming variables. In programming, terse is dangerous, so we translate these names into something verbose for C.

Math-style name C-style name

f n next_number

f n- 1 current_number

f n- 2 old_number

In C code, the equation is expressed as:

next_number = current_number + old_number;

We want to loop until our current term is 100 or larger. The while loop:

while (current_number < 100)

will repeat our computation and printing until we reach this limit.

Fib.c

/*fib.c*/

#include <stdio.h>

int old_number; /* previous Fibonacci number */

int current_number; /* current Fibonacci number */

int next_number; /* next number in the series */

int main()

{

/* start things out */

old_number = 1;

current_number = 1;

printf("1, "); /* Print first number, no new line */

while (current_number < 100)

{

printf("%d, ", current_number); /* Print next number, no new line */

next_number = current_number + old_number;

old_number = current_number;

current_number = next_number;

}

return (0);

}

$ ./fib

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

We have used a while statement to compute the Fibonacci numbers less than 100.

The loop exits when the condition after the while becomes false (0). Loops can be exited at any point through the use of a break statement.

Suppose we want to add a series of numbers, but we don't know how many numbers are to be added together. We need some way of letting the program know that we have reached the end of our list. In Example 6-2 , we use the number zero (0) to signal the end-of-list.

Note that the while statement begins with:

while (1) {

Left to its own devices, the program will loop forever because the while will exit

only when the expression 1 is 0. The only way to exit this loop is through a break statement.

When we see the end of the list indicator (0), we use the statement:

if (item == 0)

break;

to exit the loop.

/*total.c*/

#include <stdio.h>

char line[100];/* line of data for input */

int total; /* Running total of all numbers so far */

int item; /* next item to add to the list */

int main()

{

total = 0;

while (1) {

printf("Enter # to add \n");

printf(" or 0 to stop:");

fgets(line, sizeof(line), stdin);

sscanf(line, "%d", &item);

if (item == 0)

break;

total += item;

printf("Total: %d\n", total);

}

printf("Final total %d\n", total);

return (0);

}

$ ./total

Enter # to add

or 0 to stop:1

Total: 1

Enter # to add

or 0 to stop:2

Total: 3

Enter # to add

or 0 to stop:3

Total: 6

Enter # to add

or 0 to stop:4

Total: 10

Enter # to add

or 0 to stop:5

Total: 15

Enter # to add

or 0 to stop:0

Final total 15

breaks:

/* program like this */

while (1) {

current_number = last_number + old_number;

if (current_number >= 100)

break;

printf("Term %d\n", current_number);

}

For some strange reason, Example 6 -4 thinks that everyone owes a

balance of dollars. Why? PROB = :

if (balance_owed = 0)

printf("You owe nothing.\n");

/*owe0.c*/

#include <stdio.h>

char line[80];

int balance_owed;

/* input line */

/* amount owed */

int main()

{

printf("Enter number of dollars owed:");

fgets(line, sizeof(line), stdin);

sscanf(line, "%d", &balance_owed);

if (balance_owed == 0)

printf("You owe nothing.\n");

else

printf("You owe %d dollars.\n", balance_owed);

return (0);

}

$ ./owe

Enter number of dollars owed:12

You owe 12 dollars.

The statement:

if (balance_owed = 0)

is equivalent to:

balance_owed = 0;

if (balanced_owed != 0)

The statement should be written:

if (balance_owed == 0)

This error is the most common error that beginning C programmers make.

Write a program to find the square of the distance between two points. (For a more advanced problem, find the actual distance. This problem involves using the standard function sqrt.

Use your help system to find out more about how to use this function!!

man sqrt

SYNOPSIS

#include <math.h>

double sqrt(double x);

float sqrtf(float x);

long double sqrtl(long double x);

Link with -lm.

This bit was the missing key to compile the source file for sqrt with a declaration not just a number – I ammended the tempF prog to give roots:

gcc -o sqrt sqrt.c -lm

/*sqrt.c*/

#include <stdio.h>

#include <math.h>

char line[100];

float F;

float result;

int main ()

{

printf("Enter a number to find it's SQRT: ");

fgets(line, sizeof(line), stdin);

sscanf(line, "%f", &F );

result = F;

printf("The SQRT of %0.2f is %0.2f \n", F, sqrt(result) );

return (0);

}

$ ./sqrt

Enter a number to find it's SQRT: 2

The SQRT of 2.000000 is 1.414214

$ ./sqrt

Enter a number to find it's SQRT: 1024

The SQRT of 1024.000000 is 32.000000

Exercise 6-4 : Given an amount of money (less than $1.00), compute the number

of quarters, dimes, nickels, and pennies needed.

Exercise 6-5 : A leap year is any year divisible by 4, unless the year is divisible by

100, but not 400. Write a program to tell if a year is a leap year.

Exercise 6-6 : Write a program that, given the number of hours an employee

worked and the hourly wage, computes the employee's weekly pay. Count any

hours over 40 as overtime at time and a half.

/*pay.c; compute wages up to 40hr week with excess at 1.5 x time*/
#include<stdio.h>
char line[10]; /* Line from keyboard */
float hourly_rate; /*user inputs rate*/
float hours_worked;/*user inputs hours_worked*/
float hours_excess40; /*calc'd hours excess of 40*/
float tot_excess40;
float sum_wages_under_or40;
float sum_wages_excess40;
int main()
{
printf("Enter your total hours worked with dec point: ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%f", &hours_worked);

printf("Enter your hourly rate with dec point: ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%f", &hourly_rate);
/*do calcs */
if ( hours_worked <=40)
{
sum_wages_under_or40 = hours_worked * hourly_rate;
printf("Wages due with no OT = %0.2f\n", sum_wages_under_or40);
}
else
{
hours_excess40 = hours_worked - 40;
tot_excess40 = 1.5 * hourly_rate * hours_excess40;
sum_wages_excess40 = tot_excess40 + (40 * hourly_rate);
printf("Wages due with OT = %0.2f\n", sum_wages_excess40);
}
printf("\n");
return (0);
}

pay.c.png

 

stevee@AMD ~/Cprogs $ ./pay
Enter your total hours worked with dec point: 41.5
Enter your hourly rate with dec point: 10.70
Wages due with OT = 452.08

stevee@AMD ~/Cprogs $ ./pay
Enter your total hours worked with dec point: 39
Enter your hourly rate with dec point: 10.7
Wages due with no OT = 417.30

Comments are closed.

Post Navigation