Docsity

C Programming: Branching and Looping, Libraries, and Strings, Study notes of C programming

Partial preview of the text

Download C Programming: Branching and Looping, Libraries, and Strings and more Study notes C programming in PDF only on Docsity!

The Basics of C Programming

Marshall Brain

Last updated: October 30, 2013

Contents

  • 1 C programming
    • What is C?
    • The simplest C program, I
    • Spacing and indentation
    • Compilation and run
    • The simplest C program, II
    • Variables
  • 2 Input and output
    • printf
    • scanf
    • Programming exercise
  • 3 Branching and looping
    • if statement
    • Boolean expressions
    • Boolean: = vs ==
    • while loop
    • do-while loop
    • for loop
    • Looping: an example CONTENTS CONTENTS
    • Programming exercise
  • 4 Arrays
    • Programming exercise
  • 5 Variable Types
    • Typecasting
    • Typedef
  • 6 Operators
    • Operator precedence, I
    • Incrementing
    • Programming exercise
  • 7 Functions
    • Programming exercise
    • Function prototypes
  • 8 Structures
  • 9 Libraries
    • Making a library
    • Compiling and running
  • 10 Makefiles
  • 11 Pointers
    • Pointers: why?
    • Pointer Basics
    • Pointers: RAM Adresses CONTENTS CONTENTS
    • Pointing to the Same Addres
    • Pointers: Common Bugs
      • Bug #1 - Uninitialized pointers
      • Bug #2 - Invalid Pointer References
      • Bug #3 - Zero Pointer Reference
    • Pointers: Function Parameters
  • 12 Dynamic Data Structures
    • The Heap
    • Malloc and Free
  • 13 Advanced Pointers
    • Pointer Types
    • Pointers to Structures
    • Pointers to Arrays
    • Arrays of Pointers
    • Structures Containing Pointers
    • Pointers to Pointers
    • Pointers to Structures Containing Pointers
    • Linking
    • A Linked Stack Example
    • Programming exercise
    • Using Pointers with Arrays
  • 14 Strings
    • Special Note on String Constants
    • Special Note on Using Strings with malloc
    • Programming exercise
  • 15 Operator Precedence, II CONTENTS CONTENTS
  • 16 Command Line Arguments
  • 17 Text files
    • Text files: opening
    • Text files: reading
    • Main function return values
  • 18 Binary Files
  • 19 Further reading
  • Index

WHAT IS C? CHAPTER 1. C PROGRAMMING

What is C?

C is a computer programming language. That means that you can use C to create lists of instructions for a computer to follow. C is one of thousands of program- ming languages currently in use. C has been around for several decades and has won widespread acceptance because it gives programmers maximum control and efficiency. C is an easy language to learn. It is a bit more cryptic in its style than some other languages, but you get beyond that fairly quickly. C is what is called a compiled language. This means that once you write your C program, you must run it through a C compiler to turn your program into an exe- cutable that the computer can run (execute). The C program is the human-readable form, while the executable that comes out of the compiler is the machine-readable and executable form. What this means is that to write and run a C program, you must have access to a C compiler.

We will start at the beginning with an extremely simple C program and build up from there. I will assume that you are using the Linux command line and gcc as your environment for these examples; if you are not, all of the code will still work fine – you will simply need to understand and use whatever compiler you have available.

The simplest C program, I

Let’s start with the simplest possible C program and use it both to understand the basics of C and the C compilation process. Type the following program into a standard text editor. Then save the program to a file named samp.c. If you leave off .c, you will probably get some sort of error when you compile it, so make sure you remember the .c. Also, make sure that your editor does not automatically append some extra characters (such as .txt) to the name of the file. Here’s the first program:

i n c l u d e < s t d i o. h>

i n t main ( v o i d ) {

CHAPTER 1. C PROGRAMMING SPACING AND INDENTATION

p r i n t f ( " T h i s i s o u t p u t from my f i r s t p ro g ram! \ n " ) ; r e t u r n 0 ; }

Spacing and indentation

When you enter this program, position #include so that the pound sign is in col- umn 1 (the far left side). Otherwise, the spacing and indentation can be any way you like it. On some Linux systems, you will find a program called indent, which will format code for you. The spacing and indentation shown above is a good example to follow.

Compilation and run

When executed, this program instructs the computer to print out the line “This is output from my first program!” – then the program quits. You can’t get much simpler than that!

To compile this code on a Linux machine, type

g cc samp. c −o samp

This line invokes the C compiler called gcc, asks it to compile samp.c and asks it to place the executable file it creates under the name samp. To run the program, type

. / samp

You should see the output “This is output from my first program!” when you run the program.

If you mistype the program, it either will not compile or it will not run. If the program does not compile or does not run correctly, edit it again and see where you went wrong in your typing. Fix the error and try again.

CHAPTER 1. C PROGRAMMING VARIABLES

Variables

As a programmer, you will frequently want your program to “remember” a value. For example, if your program requests a value from the user, or if it calculates a value, you will want to remember it somewhere so you can use it later. The way your program remembers things is by using variables. For example:

i n t b ;

This line says, “I want to create a space called b that is able to hold one integer value.” A variable has a name (in this case, b) and a type (in this case, int, an integer). You can store a value in b by saying something like:

b = 5 ;

You can use the value in b by saying something like:

p r i n t f ("%d " , b ) ;

In C, there are several standard types for variables:

  • int - integer (whole number) values
  • float - floating point values
  • char - single character values (such as “m” or “Z”)

We will see examples of these other types as we go along.

VARIABLES CHAPTER 1. C PROGRAMMING

PRINTF CHAPTER 2. INPUT AND OUTPUT

Here is an explanation of the different lines in this program:

  • The line int a, b, c; declares three integer variables named a, b and c. Inte- ger variables hold whole numbers.
  • The next line initializes the variable named a to the value 5.
  • The next line sets b to 7.
  • The next line adds a and b and “assigns” the result to c. The computer adds the value in a (5) to the value in b (7) to form the result 12, and then places that new value (12) into the variable c. The variable c is assigned the value 12. For this reason, the = in this line is called “the assignment operator.”
  • The printf statement then prints the line “5 + 7 = 12.” The %d placeholders in the printf statement act as placeholders for values. There are three %d placeholders, and at the end of the printf line there are the three variable names: a, b and c. C matches up the first %d with a and substitutes 5 there. It matches the second %d with b and substitutes 7. It matches the third %d with c and substitutes 12. Then it prints the completed line to the screen: 5 + 7 = 12. The +, the = and the spacing are a part of the format line and get embedded automatically between the %d operators as specified by the programmer.

Let’s look at some variations to understand printf completely. Here is the simplest printf statement:

p r i n t f ( " H e l l o " ) ;

This call to printf has a format string that tells printf to send the word “Hello” to standard out. Contrast it with this:

p r i n t f ( " H e l l o \ n " ) ;

CHAPTER 2. INPUT AND OUTPUT PRINTF

The difference between the two is that the second version sends the word “Hello” followed by a carriage return to standard out. The following line shows how to output the value of a variable using printf.

p r i n t f ("%d " , b ) ;

The %d is a placeholder that will be replaced by the value of the variable b when the printf statement is executed. Often, you will want to embed the value within some other words. One way to accomplish that is like this:

p r i n t f ( " The t e m p e r a t u r e i s " ) ; p r i n t f ("%d " , b ) ; p r i n t f ( " d e g r e e s \ n " ) ;

An easier way is to say this:

p r i n t f ( " The t e m p e r a t u r e i s %d d e g r e e s \ n " , b ) ;

You can also use multiple %d placeholders in one printf statement:

p r i n t f ("%d + %d = %d \ n " , a , b , c ) ;

In the printf statement, it is extremely important that the number of operators in the format string corresponds exactly with the number and type of the variables following it. For example, if the format string contains three %d operators, then it must be followed by exactly three parameters and they must have the same types in the same order as those specified by the operators.

You can print all of the normal C types with printf by using different placeholders:

  • int (integer values) uses %d

CHAPTER 2. INPUT AND OUTPUT SCANF

The scanf function allows you to accept input from standard in, which for us is generally the keyboard. The scanf function can do a lot of different things, but it is generally unreliable unless used in the simplest ways. It is unreliable because it does not handle human errors very well. But for simple programs it is good enough and easy-to-use.

The simplest application of scanf looks like this:

s c a n f ("%d " , &b ) ;

The program will read in an integer value that the user enters on the keyboard (%d is for integers, as is printf, so b must be declared as an int) and place that value into b.

The scanf function uses the same placeholders as printf:

  • int uses %d
  • float uses %f
  • char uses %c
  • character strings (discussed later) use %s

You must put & in front of the variable used in scanf. The reason why will become clear once you learn about pointers. It is easy to forget the & sign, and when you forget it your program will almost always crash when you run it.

In general, it is best to use scanf as shown here – to read a single value from the keyboard. Use multiple calls to scanf to read multiple values. In any real program, you will use the gets or fgets functions instead to read text a line at a time. Then you will “parse” the line to read its values. The reason that you do that is so you can detect errors in the input and handle them as you see fit.

The printf and scanf functions will take a bit of practice to be completely under- stood, but once mastered they are extremely useful.

PROGRAMMING EXERCISE CHAPTER 2. INPUT AND OUTPUT

Programming exercise

  1. Modify the following program so that it accepts three values instead of two and adds all three together:

i n c l u d e < s t d i o. h>

i n t main ( v o i d ) { i n t a , b , c ; p r i n t f ( " E n t e r t h e f i r s t v a l u e : " ) ; s c a n f ("%d " , &a ) ; p r i n t f ( " E n t e r t h e s e c o n d v a l u e : " ) ; s c a n f ("%d " , &b ) ; c = a + b ; p r i n t f ("%d + %d = %d \ n " , a , b , c ) ; r e t u r n 0 ; }

  1. Try deleting or adding random characters or words in one of the previous programs and watch how the compiler reacts to these errors. For example, delete the b variable in the first line of the above program and see what the compiler does when you forget to declare a variable. Delete a semicolon and see what happens. Leave out one of the braces. Remove one of the parentheses next to the main function. Make each error by itself and then run the program through the compiler to see what happens. By simulating errors like these, you can learn about different compiler errors, and that will make your typos easier to find when you make them for real.

BOOLEAN EXPRESSIONS CHAPTER 3. BRANCHING AND LOOPING

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:

i n c l u d e < s t d i o. h>

i n t main ( v o i d ) { i n t b ; p r i n t f ( " E n t e r a v a l u e : " ) ; s c a n f ("%d " , &b ) ; i f ( b < 0 ) { p r i n t f ( " The v a l u e i s n e g a t i v e \ n " ) ; } e l s e i f ( b == 0 ) { p r i n t f ( " The v a l u e i s z e r o \ n " ) ; } e l s e { p r i n t f ( " The v a l u e i s p o s i t i v e \ n " ) ; } r e t u r n 0 ; }

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

Boolean expressions

Here is a more complicated Boolean expression:

CHAPTER 3. BRANCHING AND LOOPING BOOLEAN: = VS ==

i f ( ( x == y ) && ( j > k ) ) { z = 1 ; } e l s e { q = 1 0 ; }

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:

e q u a l i t y == l e s s t h a n < G r e a t e r t h a n > <= <= >= >= i n e q u a l i t y != and && o r | | n o t!

= vs == in boolean expressions

The == sign is a problem in C because every now and then you may forget and type just = in a Boolean expression. This is an easy mistake to make, but to the compiler there is a very important difference. C will accept either = and == in a