Home | Sign Up | Log In | RSSSunday, 2019-01-20, 10:20 AM

eduCampUs

Site menu
Section categories
Education [150]
Videos [1]
Music [0]
Chat Box
500
Tags
learn c language learn c language branching and loop learn c language functions learn c language Pointer Basics how web page works Oracle Solaris 10 Oracle Solaris 10 How Web Pages Work Images How Web Pages Work Adding images&gr How Web Pages Work Introduction to How to Install WAMP How to Host Your Own Website for Fr How to Install the Apache Web Serve Atomic Structure The text provides 000 tons of conversations Introduction to How Radio Works Rad often over millions of miles citizens band radio Introduction to How the Radio Spect Can information travel faster than How F-15s Work by Tom Harris Browse How F/A-18s Work by Robert Valdes B How F/A-18s Work by Robert Valdes B Flying Video Game: In the Cockpit I How F/A-22 Raptors Work by Gary Wol 10 Unidentified Sounds That Scienti 10 Things You Didn't Know About Ein Is glass really a liquid? by Laurie How Radio Works by Marshall Brain B How Radio Works by Marshall Brain B 10 Most Terrifying Vehicle Manufact How a Top Fuel Dragster Works by Ch but can Siri meet our nee How Siri Works by Bernadette Johnso How the Tesla Turbine Works by Will Lecture 1: Inflationary Cosmology: Lecture 2: Inflationary Cosmology: Lecture 4: The Kinematics of the Ho Lecture 5: Cosmological Redshift an Lecture 6: The Dynamics of Homogene Lecture 7: The Dynamics of Homogene Lecture 8: The Dynamics of Homogene Lecture 9: The Dynamics of Homogene Lecture 10: Introduction to Non-Euc IBPS Clerical Cadre Exam Pattern De Institute of Banking Personnel Sele Educational Qualifications: A Degre INTERVIEW Candidates who have been official trailer for Mission Imposs How Relativity Connects Electric an in 1738 Kinetic Theory of Gases: A Brief Re Frames of Reference and Newton’s La attempts to measure the UVa Physics 12/1/07 “Moving Clocks Run Slow” pl More Relativity: The Train and the 12/1/07 The Formula If I walk from Adding Velocities: A Walk on the Tr 3/1/2008 The Story So Far: A Brief Mass and Energy Michael Fowler Energy and Momentum in Lorentz Tran How Relativity Connects Electric an Analyzing Waves on a String Michael by f even earlier than the bra Fermat's Principle of Least Time 9/ Hamilton's Principle and Noether's meaning they have Mechanical Similarity and the Viria Hamilton's Equations 9/10/15 A Dyna A New Way to Write the Action Integ Maupertuis came up with a kind of p Maupertuis' Principle: Minimum Acti Canonical Transformations Point Tra Introduction to Liouville's Theorem Adiabatic Invariants and Action-Ang Hyperbolas Michael Fowler Prelimina Mathematics for Orbits: Ellipses Keplerian Orbits Michael Fowler Pre Newton's equations for particle mot Dynamics of Motion in a Central Pot A Vectorial Approach: Hamilton's Eq Elastic Scattering Michael Fowler B Driven Oscillator Michael Fowler (c Dynamics of a One-Dimensional Cryst I usefor the spring constant (is a a mass on a spring Motion in a Rapidly Oscillating Fie Anharmonic Oscillators Michael Fowl in which the distance betw Motion of a Rigid Body: the Inertia Moments of Inertia: Examples Michae Euler's Angles Michael Fowler Intro or more precisely one our analysis of rotational motion h Euler's Equations Michael Fowler In Motion in a Non-inertial Frame of R Ball Rolling on Tilted Turntable Mi live cricket score roll the ball ba
Statistics

Total online: 1
Guests: 1
Users: 0
Home » 2013 » April » 22 » learn c language branching and looping
3:12 AM
learn c language branching and looping

Branching and Looping

In C, both if statements and while loops rely on the idea of Boolean expressions. Here is a simple C program demonstrating an if statement:

#include int main() { int b; printf("Enter a value:"); scanf("%d", &b); if (b < 0) printf("The value is negativen"); return 0; }

This program accepts a number from the user. It then tests the number using an if statement to see if it is less than 0. If it is, the program prints a message. Otherwise, the program is silent. The (b < 0) portion of the program is the Boolean expression. C evaluates this expression to decide whether or not to print the message. If the Boolean expression evaluates to True, then C executes the single line immediately following the if statement (or a block of lines within braces immediately following the if statement). If the Boolean expression is False, then C skips the line or block of lines immediately following the if statement.

Here's slightly more complex example:

#include <stdio.h>

int main()
{
 int b;
 printf("Enter a value:");
 scanf("%d", &b);
 if (b < 0)
 printf("The value is negative\n");
 return 0;
}

In this example, the else if and else sections evaluate for zero and positive values as well.

Here is a more complicated Boolean expression:

if ((x==y) && (j>k))
 z=1;
else
 q=10;

This statement says, "If the value in variable x equals the value in variable y, and if the value in variable j is greater than the value in variable k, then set the variable z to 1, otherwise set the variable q to 10." You will use if statements like this throughout your C programs to make decisions. In general, most of the decisions you make will be simple ones like the first example; but on occasion, things get more complicated.

Notice that C uses == to test for equality, while it uses = to assign a value to a variable. The && in C represents a Boolean AND operation.

Here are all of the Boolean operators in C:

 equality ==
 less than <
 Greater than >
 <= <=
 >= >=
 inequality !=
 and &&
 or ||
 not !

You'll find that while statements are just as easy to use as if statements. For example:

while (a < b)
{
 printf("%d\n", a);
 a = a + 1;
}

This causes the two lines within the braces to be executed repeatedly until a is greater than or equal to b. The while statement in general works as illustrated to the right.

C also provides a do-while structure:

#include <stdio.h>

int main()
{
 int a;

 printf("Enter a number:");
 scanf("%d", &a);
 if (a)
 {
 printf("The value is True\n");
 }
 return 0;
}

The for loop in C is simply a shorthand way of expressing a while statement. For example, suppose you have the following code in C:

x=1;
while (x<10)
{
 blah blah blah
 x++; /* x++ is the same as saying x=x+1 */
}

You can convert this into a for loop as follows:

for(x=1; x<10; x++)
{
 blah blah blah
}

Note that the while loop contains an initialization step (x=1), a test step (x<10), and an increment step (x++). The for loop lets you put all three parts onto one line, but you can put anything into those three parts. For example, suppose you have the following loop:

a=1;
b=6;
while (a < b)
{
 a++;
 printf("%d\n",a);
}

You can place this into a for statement as well:

for (a=1,b=6; a < b; a++,printf("%d\n",a));

It is slightly confusing, but it is possible. The comma operator lets you separate several different statements in the initialization and increment sections of the for loop (but not in the test section). Many C programmers like to pack a lot of information into a single line of C code; but a lot of people think it makes the code harder to understand, so they break it up.

Try This!

  • Try changing the Fahrenheit-to-Celsius program so that it uses scanf to accept the starting, ending and increment value for the table from the user.
  • Add a heading line to the table that is produced.
  • Try to find a different solution to the bug fixed by the previous example.
  • Create a table that converts pounds to kilograms or miles to kilometers.

Looping: A Real Example

Let's say that you would like to create a program that prints a Fahrenheit-to-Celsius conversion table. This is easily accomplished with a for loop or a while loop:

#include <stdio.h>

int main()
{
 int a;
 a = 0;
 while (a <= 100)
 {
 printf("%4d degrees F = %4d degrees C\n",
 a, (a - 32) * 5 / 9);
 a = a + 10;
 }
 return 0;
}

If you run this program, it will produce a table of values starting at 0 degrees F and ending at 100 degrees F. The output will look like this:

 0 degrees F = -17 degrees C
 10 degrees F = -12 degrees C
 20 degrees F = -6 degrees C
 30 degrees F = -1 degrees C
 40 degrees F = 4 degrees C
 50 degrees F = 10 degrees C
 60 degrees F = 15 degrees C
 70 degrees F = 21 degrees C
 80 degrees F = 26 degrees C
 90 degrees F = 32 degrees C
 100 degrees F = 37 degrees C

The table's values are in increments of 10 degrees. You can see that you can easily change the starting, ending or increment values of the table that the program produces.

If you wanted your values to be more accurate, you could use floating point values instead:

#include <stdio.h>

int main()
{
 float a;
 a = 0;
 while (a <= 100)
 {
 printf("%6.2f degrees F = %6.2f degrees C\n",
 a, (a - 32.0) * 5.0 / 9.0);
 a = a + 10;
 }
 return 0;
}

You can see that the declaration for a has been changed to a float, and the %f symbol replaces the %d symbol in the printf statement. In addition, the %f symbol has some formatting applied to it: The value will be printed with six digits preceding the decimal point and two digits following the decimal point.

Now let's say that we wanted to modify the program so that the temperature 98.6 is inserted in the table at the proper position. That is, we want the table to increment every 10 degrees, but we also want the table to include an extra line for 98.6 degrees F because that is the normal body temperature for a human being. The following program accomplishes the goal:

#include <stdio.h>

int main()
{
 float a;
 a = 0;
 while (a <= 100)
 {
 if (a > 98.6)
 {
 printf("%6.2f degrees F = %6.2f degrees C\n",
 98.6, (98.6 - 32.0) * 5.0 / 9.0);
 }
 printf("%6.2f degrees F = %6.2f degrees C\n",
 a, (a - 32.0) * 5.0 / 9.0);
 a = a + 10;
 }
 return 0;
}

This program works if the ending value is 100, but if you change the ending value to 200 you will find that the program has a bug. It prints the line for 98.6 degrees too many times. We can fix that problem in several different ways. Here is one way:

#include <stdio.h>

int main()
{
 float a, b;
 a = 0;
 b = -1;
 while (a <= 100)
 {
 if ((a > 98.6) && (b < 98.6))
 {
 printf("%6.2f degrees F = %6.2f degrees C\n",
 98.6, (98.6 - 32.0) * 5.0 / 9.0);
 }
 printf("%6.2f degrees F = %6.2f degrees C\n",
 a, (a - 32.0) * 5.0 / 9.0);
 b = a;
 a = a + 10;
 }
 return 0;
}

C Errors to Avoid

  • Putting = when you mean == in an if or while statement
  • Forgetting to increment the counter inside the while loop - If you forget to increment the counter, you get an infinite loop (the loop never ends).
  • Accidentally putting a ; at the end of a for loop or if statement so that the statement has no effect - For example: for (x=1; x<10; x++); printf("%d\n",x); only prints out one value because the semicolon after the for statement acts as the one line the for loop executes.

Arrays

In this section, we will create a small C program that generates 10 random numbers and sorts them. To do that, we will use a new variable arrangement called an array.

An array lets you declare and work with a collection of values of the same type. For example, you might want to create a collection of five integers. One way to do it would be to declare five integers directly:

int a, b, c, d, e;

This is okay, but what if you needed a thousand integers? An easier way is to declare an array of five integers:

int a[5];

The five separate integers inside this array are accessed by an index. All arrays start at index zero and go to n-1 in C. Thus, int a[5]; contains five elements. For example:

int a[5];

a[0] = 12;
a[1] = 9;
a[2] = 14;
a[3] = 5;
a[4] = 1;

One of the nice things about array indexing is that you can use a loop to manipulate the index. For example, the following code initializes all of the values in the array to 0:

int a[5];
int i;

for (i=0; i<5; i++)
 a[i] = 0;

The following code initializes the values in the array sequentially and then prints them out:

#include <stdio.h>

int main()
{
 int a[5];
 int i;

 for (i=0; i<5; i++)
 a[i] = i;
 for (i=0; i<5; i++)
 printf("a[%d] = %d\n", i, a[i]);
}

Arrays are used all the time in C. To understand a common usage, start an editor and enter the following code:

#include <stdio.h>

#define MAX 10

int a[MAX];
int rand_seed=10;

/* from K&R
 - returns random number between 0 and 32767.*/
int rand()
{
 rand_seed = rand_seed * 1103515245 +12345;
 return (unsigned int)(rand_seed / 65536) % 32768;
}

int main()
{
 int i,t,x,y;

 /* fill array */
 for (i=0; i < MAX; i++)
 {
 a[i]=rand();
 printf("%d\n",a[i]);
 }

 /* more stuff will go here in a minute */

 return 0;
}

This code contains several new concepts. The #define line declares a constant named MAX and sets it to 10. Constant names are traditionally written in all caps to make them obvious in the code. The line int a[MAX]; shows you how to declare an array of integers in C. Note that because of the position of the array's declaration, it is global to the entire program.

The line int rand_seed=10 also declares a global variable, this time named rand_seed, that is initialized to 10 each time the program begins. This value is the starting seed for the random number code that follows. In a real random number generator, the seed should initialize as a random value, such as the system time. Here, the rand function will produce the same values each time you run the program.

The line int rand() is a function declaration. The rand function accepts no parameters and returns an integer value. We will learn more about functions later. The four lines that follow implement the rand function. We will ignore them for now.

The main function is normal. Four local integers are declared, and the array is filled with 10 random values using a for loop. Note that the array a contains 10 individual integers. You point to a specific integer in the array using square brackets. So a[0] refers to the first integer in the array, a[1] refers to the second, and so on. The line starting with /* and ending with */ is called a comment. The compiler completely ignores the line. You can place notes to yourself or other programmers in comments.

Now add the following code in place of the more stuff ... comment:

/* bubble sort the array */
for (x=0; x < MAX-1; x++)
 for (y=0; y < MAX-x-1; y++)
 if (a[y] > a[y+1])
 {
 t=a[y];
 a[y]=a[y+1];
 a[y+1]=t;
 }
/* print sorted array */
printf("--------------------\n");
for (i=0; i < MAX; i++)
printf("%d\n",a[i]);

This code sorts the random values and prints them in sorted order. Each time you run it, you will get the same values. If you would like to change the values that are sorted, change the value of rand_seed each time you run the program.

The only easy way to truly understand what this code is doing is to execute it "by hand." That is, assume MAX is 4 to make it a little more manageable, take out a sheet of paper and pretend you are the computer. Draw the array on your paper and put four random, unsorted values into the array. Execute each line of the sorting section of the code and draw out exactly what happens. You will find that, each time through the inner loop, the larger values in the array are pushed toward the bottom of the array and the smaller values bubble up toward the top.

Try This!

  • Try out different pieces of code to investigate typecasting and precedence. Try out int, char, float, and so on.
  • Create an array of records and write some code to sort that array on one integer field.

C Errors to Avoid

As described in the article, using the / operator with two integers will often produce an unexpected result, so think about it whenever you use it.

More on Arrays

Variable Types

There are three standard variable types in C:

  • Integer: int
  • Floating point: float
  • Character: char

An int is a 4-byte integer value. A float is a 4-byte floating point value. A char is a 1-byte single character (like "a" or "3"). A string is declared as an array of characters.

There are a number of derivative types:

  • double (8-byte floating point value)
  • short (2-byte integer)
  • unsigned short or unsigned int (positive integers, no sign bit)

Operators and Operator Precedence

The operators in C are similar to the operators in most languages:

+ - addition
- - subtraction
/ - division
* - multiplication
% - mod

The / operator performs integer division if both operands are integers, and performs floating point division otherwise. For example:

void main()
{
 float a;
 a=10/3;
 printf("%f\n",a);
}

This code prints out a floating point value since a is declared as type float, but a will be 3.0 because the code performed an integer division.

Operator precedence in C is also similar to that in most other languages. Division and multiplication occur first, then addition and subtraction. The result of the calculation 5+3*4 is 17, not 32, because the * operator has higher precedence than + in C. You can use parentheses to change the normal precedence ordering: (5+3)*4 is 32. The 5+3 is evaluated first because it is in parentheses. We'll get into precedence later -- it becomes somewhat complicated in C once pointers are introduced.

Typecasting

C allows you to perform type conversions on the fly. You do this especially often when using pointers. Typecasting also occurs during the assignment operation for certain types. For example, in the code above, the integer value was automatically converted to a float.

You do typecasting in C by placing the type name in parentheses and putting it in front of the value you want to change. Thus, in the above code, replacing the line a=10/3; with a=(float)10/3; produces 3.33333 as the result because 10 is converted to a floating point value before the division.

Typedef

You declare named, user-defined types in C with the typedef statement. The following example shows a type that appears often in C code:

#define TRUE 1
#define FALSE 0
typedef int boolean;

void main()
{
 boolean b;

 b=FALSE;
 blah blah blah
}

This code allows you to declare Boolean types in C programs.

If you do not like the word "float'' for real numbers, you can say:

typedef float real;

and then later say:

real r1,r2,r3;

You can place typedef statements anywhere in a C program as long as they come prior to their first use in the code.

Structures

Structures in C allow you to group variable into a package. Here's an example:

struct rec
{
 int a,b,c;
 float d,e,f;
};

struct rec r;

As shown here, whenever you want to declare structures of the type rec, you have to say struct rec. This line is very easy to forget, and you get many compiler errors because you absent-mindedly leave out the struct. You can compress the code into the form:

struct rec
{
 int a,b,c;
 float d,e,f;
} r;

where the type declaration for rec and the variable r are declared in the same statement. Or you can create a typedef statement for the structure name. For example, if you do not like saying struct rec r every time you want to declare a record, you can say:

typedef struct rec rec_type;

and then declare records of type rec_type by saying:

rec_type r;

You access fields of structure using a period, for example, r.a=5;.

Arrays

You declare arrays by inserting an array size after a normal declaration, as shown below:

int a[10]; /* array of integers */
char s[100]; /* array of characters
 (a C string) */
float f[20]; /* array of reals */
struct rec r[50]; /* array of records */

Incrementing

Long Way Short Way
i=i+1; i++;
i=i-1; i--;
i=i+3; i += 3;
i=i*j; i *= j;
Category: Education | Views: 1911 | Added by: farrel | Tags: learn c language branching and loop | Rating: 0.0/0
Total comments: 0
Name *:
Email *:
Code *:
Log In
Search
Entries archive

Copyright eduCampus.tk © 2019
Powered by uCoz