0

C break and continue

break and continue are two keywords that used in loops. They control the flow inside the loops. Below shows how these keywords work inside a block of code:

  // break
while (condition1) {
  statements...;

  if (condition2)
    break;

  statements...;
}

  // continue
while (condition1) {
  statements...;

  if (condition2)
    continue;

  statements...;
}

The break statement is used to skip a certain condition in a loop, discard the statements below the break statement and end the loop. For example, the loop continues to execute normally in the above code until the condition increases to condition2, it discards the “statements…” below the break statement and ends the loop on condition2.

Just as the break statement, the continue statement skips a certain condition in a loop and discards the statement below the continue statement. The difference from the break statement is that the continue statement continues to executed the loop once the specified condition is skipped. For example, the loop continues to execute normally in the above code until the condition increases to condiion2, it discards the “statements…” below the continue statement and continues the execution at condition3.

0

C do…while Loop

The do…while loop is the third type of loop for C and other programming languages. This type of loop is not very often used. It’s similar to the while loop. Here is the format of the do…while loop:

do {
  statements...;
}
while (condition);

Below are the execution steps:

  1. All the statements are executed
  2. The condition is checked
  3. The statements are executed one more time if the condition is true
  4. Repeat the above steps until the condition becomes false

The difference between do…while loop and while loop is that while loop checks the condition before the statements are executed whereas the do…while loop checks the condition after the statement are executed. This means that do…while loop executes the statements at least once, while the while loop might not execute the statements at all based on its condition.

The following is the sample code for the do…while loop:

/*
 *
 * dowhile.c
 *
 * Program to demonstrate the use of the do...while loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char type;
 int album;    // Boolean

 do {
   printf("Album or single (a for album, s for single)? ");
   while (getchar() != 'n' && getchar() != EOF)
     printf("");
   scanf("%c", &type);
   if (type != 'a' && type != 's')
     printf("Errorn");
 }
 while (type != 'a' && type != 's');

 album = type == 'a';    // Convert to boolean

 if (album)
   printf("Albumn");
 else
   printf("Singlen");

 fflush(stdin);
 getchar();
}

Note that it’s the same code as the while loop. The difference is that the type variable is not initialized anymore since it uses do…while loop.

0

C for Loop

The for loop is used when the number of time the loop repeated is specified. The format of the for loop is:

for (initialization; condition; increment) {
  statements;
}

The following steps show how the for loop is executed:

  1. Initialize variable, the value usually is 0
  2. Check the condition
  3. If the condition is true, statements are executed
  4. The value of the variable increased by 1
  5. Loop from #2 to #4 until the condition becomes false

Here is the sample code for the for loop:

/*
 *
 * for.c
 *
 * Program to demonstrate the use of the for loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int counter;
 int total = 0;

 for (counter = 1; counter <= 100; counter = counter + 1) {
   total = total + counter;
 }

 printf("The sum of all numbers from 1 to 1000 is %dn", total);

 fflush(stdin);
 getchar();
}

Note that the increment of the for loop can also be counter++ instead of counter = counter + 1.

2

C while Loop

The while loop is often used when it doesn’t know how many time the loop will be repeated. Here is the sample code for the while loop:

/*
 *
 * while.c
 *
 * Program to demonstrate the use of the while loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 char type = 'x';
 int album;    // Boolean

 while (type != 'a' && type != 's') {
  printf("Album or single (a for album, s for single)? ");
  scanf("%c", &type);
  album = type == 'a';    // Determine if type is equal to 'a'
  if (type != 'a' && type != 's')
   printf("Errorn");

   // Dummy statement to flush the input
  while (getchar() != 'n' && getchar() != EOF) {
   printf("");
  }
 }

 if (album)
  printf("Albumn");
 else
  printf("Singlen");

 fflush(stdin);
 getchar();
}

As you can see in the code above, format of the while loop is the same as the format of the if statement, except the condition is repeatedly used until the condition is true instead of used only once.

Below is the sample code for the while loop which is specified the number of repeated loops:

/*
 *
 * while2.c
 *
 * Program to demonstrate the use of the while loop
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int counter = 1;
 int total = 0;

 while (counter <= 1000) {
  total = total + counter;
  counter = counter + 1;
 }

 printf("The sum of all numbers from 1 to 1000 is %dn", total);

 fflush(stdin);
 getchar();
}
0

C Loop Introduction

A loop is the same as an if statement, except it is used for repetition of a block of code based on a certain condition. There are two types of loops:

  • Loops that specify how many times the code will be repeated when the loop start
  • Loops that do not know how many times the code will be repeated (For example, user input from the keyboard)

Note that an invalid condition could cause an infinite loop, a loop that never stops. This can have some side effects, such as OS freeze or unresponsive application.

0

A Simple C Program to Store a CD Information

Today I wrote a program to allow user to input the CD information and output back to user what he/she entered using C. This is a starter program which I will improve over time as I continued to learn C programming language. Here is the code:

/*
 *
 * database.c
 *
 * Input one CD data and output the data back to the user
 *
 * By Robby Chen, 2010
 *
 */

#include <stdio.h>

main() {
 char title[91]; // Title of the CD
 char author[51]; // Author of the CD
 int tracks; // Number of tracks in the CD
 char aOrS; // Is the CD album or single
 float price; // The price of the CD

   // Output the welcome message
 printf("nWelcome to the CD databasen");
 printf("Please enter the following: nn");

   // Title field
 printf("Title: ");
 scanf("%[^n]", title);

   // Author field
 printf("Author: ");
 while (getchar() != 'n' && getchar() != EOF)
   printf("");
 scanf("%[^n]", author);

   // Tracks field
 printf("Number of tracks: ");
 while (getchar() != 'n' && getchar() != EOF)
   printf("");
 scanf("%d", &tracks);

   // Album or single field
 printf("Album or single (Enter a for album, s for single): ");
 while (getchar() != 'n' && getchar() != EOF)
   printf("");
 scanf("%c", &aOrS);

   // Price field
 printf("Price: ");
 while (getchar() != 'n' && getchar() != EOF)
   printf("");
 scanf("%f", &price);

   // Output the result
 printf("nYou entered following CD information: n");
 printf("====================================n");
 printf("Title: %sn", title);
 printf("Author: %sn", author);
 printf("Number of tracks: %dn", tracks);
 if (aOrS == 'a') // Character variable uses single quote
   printf("Albumn");
 else
   printf("Singlen");
 printf("Price: $%.2fn", price);

 printf("nPress ENTER to exit the program.");
 while (getchar() != 'n' && getchar() != EOF) // For the getchar() to work
   printf("");
 getchar();

}

This is a database program which means it will work with files once I know how to manipulate files using C.

0

C goto Statement

The goto statement looks like:

  statements...;
  goto label;
  statements..;
label:
  statements...;

Below is the sample code for the statement:

/*
 *
 * goto.c
 *
 * Demonstrate the use (or misuse) of the goto statement
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int age;
 char name[41];
 int very_old;

 printf("Please enter your age: ");
 scanf("%d", &age);
 printf("You are %d years oldn", age);

 if (!(age <= 19 && age >= 13))
   goto other;
 if (age > 19 || age < 13)
   printf("You are not a teenagern");

up:
 if (age == 10 || age == 20 || age == 30 || age > 100)
   printf("You have a special agen");

 printf("Please enter your name: ");
 scanf("%s", name);

 if (!(strcmp(name, "Bruce") != 0 && age != 40))
   printf("You not called Bruce and are aged 40.n");
 if (strcmp(name, "Bruce") == 0 || age == 40)
   printf("You not called Bruce and are aged 40.n");

other:
 very_old = age > 80;

 if (!very_old)
   printf("You are not very oldn");
 if (very_old == 0)
   printf("You are not very oldn");

 if (age > 10)
   goto up;

 fflush(stdin);
 getchar();
}

Most programmers often don’t use the goto statement because it makes the code unreadable. This statement is used to loop between the code process. I think that it is best used to evaluate inputted value. For instance,

  printf("Please enter your age: ");
input:
  scanf("%d", &age);

  if (age <= 0) {
    printf("You entered an invalid age. Please re-enter: ");
    goto input;
  }
0

C Advanced Relational Operators

The following are the advanced relational operators:

  • && and
  • || or
  • ! not

(The precedence is very important while using these operators.)

Here is the sample code for the advanced relational operators:

/*
 * age4.c
 *
 * Demonstrate the use of the various relational operators
 * AND
 * Demonstrate the concept of advanced relational operators
 *
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int age;
 char name[41];
 int very_old;

 printf("Please enter your age: ");
 scanf("%d", &age);
 printf("You are %d years oldn", age);

 if (!(age <= 19 && age >= 13))    // this condition is false
   printf("You are not a teenagern");

 if (age > 19 || age < 13)    // It is the same as above conditional statement
   printf("You are not a teenagern");

 if (age == 10 || age == 20 || age == 30 && age > 100)    // Always false
   printf("You have a special agen");

 printf("Please enter your name: ");
 scanf("%s", name);

 if (!(strcmp(name, "Bruce") != 0 && age != 40))
   printf("You are called Bruce. Do you mind if I call you Bruce?n");

 if (strcmp(name, "Bruce") != 0 || age == 40))
   printf("You are not called Bruce. Do you mind if I call you Bruce?n");

 very_old = age > 80;

 if (!very_old)
   printf("You are not very oldn");

 if (very_old == 0)    // same as the last statement
   printf("You are not very oldn");

 fflush(stdin);
 getchar();
}

Note that the code above is the continuation of the basic relational operators. The not(!) operator reverses a conditional statement. It can make true conditions false and false conditions true.

0

C Boolean Expressions

Since boolean expressions are hard to explain. Here is the sample code that contains a boolean expression:

/*
 *
 * age5.c
 * Demonstrate the concept if boolean expressions
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int age;
 int magic_age = 80;
 int very_old;

 printf("Please enter your age: ");
 scanf("%d", &age);
 printf("You are %d years oldn" , age);

 very_old = age >= 80;    // The answer for this statement is either 1 or 0

 if (very_old)    // This is a boolean expression
   printf("My, you are very old!n");

 fflush(stdin);
 getchar();
}

As you can see in the above code, a condition is a boolean expression. The meaning of boolean is true or false. It also means 1 or 0 in the programming environment.

The boolean expression could be an integer expression like the above if statement. For example, 3 + 4. The if statement treated 3 + 4 as true because the boolean exression only treats 0 as false, otherwise is true. Note that the definition of true or false in C is that true is other than 0, while false is 0, even the negative values are true.

1

C Relational Operators

The 6 relational operators in C are:

  • == equals (= is used as variable assignment, == is used as comparison between values)
  • != does not equal
  • > is greater than
  • < is less then
  • >= is greater than or equal to
  • <= is less than or equal to

Here is the sample code for the relational operators:

/*
 * age4.c
 * Demonstrate the use of the various relational operators
 * by Mark Virtue, 2001.
 *
 */

#include <stdio.h>

main() {
 int age;
 char name[41];

 printf("Please enter your age: ");
 scanf("%d", &age);
 printf("You are %d years oldn", age);

 if (age <= 19) {
   if (age >= 13)
     printf("You are a teenagern");
   else
     printf("You are just a kidn");
 }
 else
   printf("My, you are very old!n");

 printf("Please enter your name: ");
 scanf("%s", name);

 if (strcmp(name, "Bruce") != 0)
   printf("You are not called Bruce. Do you mind if I call you Bruce?n");

 ...    // To be continued
}

Notice that there is a new string function. strcmp() function is used to compare two strings. The strings are the same if this function returns 0, otherwise it returns either less than 0 or greater than 0 depending on the first letter of the string.

Pages ... 1 2 3