Share this:
C PROGRAMMING
AN INTRODUCTION TO C PROGRAMMING
It is one of the most used programing language in software development area. At the beginning, C was designed and developed for the development of UNIX operating system. Today C has been widely used to develop many types of application software such as basic calculator word processor games, operating system etc.
Editing in C language
It is one of the most used programing language in software development area. At the beginning, C was designed and developed for the development of UNIX operating system. Today C has been widely used to develop many types of application software such as basic calculator word processor games, operating system etc.
Editing in C language
- Editing is a process of writing the C source code. programmers write C source code using editor program. widely used editing programs are Linux, platform via and Emacs.
On windows platform, we can use Notepad as editor program but most use software package for C such as C++ builder, DOS C++. This software provides complete programming environment forwriting, managing, compiling, debugging and testing C source code. This is known as Integrated Development Environment (IDE)
Compiling in C language
The C source code has to be translated into machine language code. Machine language is a language which are in the form of binary numbers that a computer understand. The process of code translation is called compiling. During compilation process, the compiler can detect any syntax error.
Execution
The execution stage is where you can run the program to check whether it produce the desired output.This stage can be a testing stage where you can check if you get the desired output.
C program layout
Basically, a C program consists of two sections
1. Pre- processor directives
2. Main function
A simple C program
The following program is written in the C programming language which can display the word “program in C is easy”
#include
main()
{
printf(“Programming in C is easy.n”);
}
Sample Program Output
Programming in C is easy.
_
A NOTE ABOUT C PROGRAM
In C, lowercase and uppercase characters are very important! All commands in C must be lowercase. The C programs starting point is identified by the word
In C, lowercase and uppercase characters are very important! All commands in C must be lowercase. The C programs starting point is identified by the word
main()
#include
is to allow the use of the printf statement to provide program output. Text to be displayed by printf() must be enclosed in double quotes. The program has only one statement
printf(“Programming in C is easy.n”);
printf() is actually a function (procedure) in C that is used for printing variables and text. Where text appears in double quotes “”, it is printed without modification. There are some exceptions however. This has to do with the and % characters. These characters are modifiers, and for the present the followed by the n character represents a newline character. Thus the program prints
Programming in C is easy.
and the cursor is set to the beginning of the next line. As we shall see later on, what follows the character will determine what is printed, ie, a tab, clear screen, clear line etc. Another important thing to remember is that all C statements are terminated by a semi-colon
Summary of major points so far
- program execution begins at main()
- keywords are written in lower-case
- statements are terminated with a semi-colon
- text strings are enclosed in double quotes
- C is case sensitive, use lower-case and try not to capitalise variable names
- n means position the cursor on the beginning of the next line
- printf() can be used to display text to the screen
- the curly braces {} define the beginning and end of a program block
DATA TYPES AND CONSTANTS
The four basic data types are
The four basic data types are
- INTEGER
These are whole numbers, both positive and negative. Unsigned integers (positive values only) are supported. In addition, there are short and long integers.
The keyword used to define integers is,
int
An example of an integer value is 32. An example of
declaring an integer variable called sum is,
declaring an integer variable called sum is,
int sum;
sum = 20;
- FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The keyword used to define float variables is,
∙
∙ float
An example of a float value is 34.12. An example of declaring a float variable called money is,
float money;
money = 0.12;
- DOUBLE
These are exponetional numbers, both positive and negative. The keyword used to define double variables is,
∙
∙ double
An example of a double value is 3.0E2. An example of declaring a double variable called big is,
double big;
big = 312E+7;
- CHARACTER
- These are single characters. The keyword used to define character variables is,
∙
∙ char
An example of a character value is the letter A. An example of declaring a character variable called letter is,
char letter;
letter = ‘A’;
Note the assignment of the character A to the variable letter is done by enclosing the value in single quotes. Remember the golden rule: Single character – Use single quotes.
Sample program illustrating each data type
#include < stdio.h >
main()
{
int sum;
float money;
char letter;
double pi;
sum = 10; /* assign integer value */
money = 2.21; /* assign float value */
letter = ‘A’; /* assign character value */
pi = 2.01E6; /* assign a double value */
printf(“value of sum = %dn”, sum );
printf(“value of money = %fn”, money );
printf(“value of letter = %cn”, letter );
printf(“value of pi = %en”, pi );
}
Sample program output
value of sum = 10
value of money = 2.210000
value of letter = A
value of pi = 2.010000e+06
PREPROCESSOR STATEMENTS
The define statement is used to make programs more readable. Consider the following examples,
The define statement is used to make programs more readable. Consider the following examples,
#define TRUE 1 /* Don’t use a semi-colon , # must be first character on line */
#define FALSE 0
#define NULL 0
#define AND &
#define OR |
#define EQUALS ==
game_over = TRUE;
while( list_pointer != NULL )
…………….
Note that preprocessor statements begin with a # symbol, and are NOT terminated by a semi-colon. Traditionally, preprocessor statements are listed at the beginning of the source file.
Preprocessor statements are handled by the compiler (or preprocessor) before the program is actually compiled. All # statements are processed first, and the symbols (like TRUE) which occur in the C program are replaced by their value (like 1). Once this substitution has taken place by the preprocessor, the program is then compiled.
In general, preprocessor constants are written in UPPERCASE.
Class Exercise C4
Use pre-processor statements to replace the following constants
Use pre-processor statements to replace the following constants
0.312
W
37
Answer
#define smallvalue 0.312
#define letter ‘W’
#define smallint 37
LITERAL SUBSTITUTION OF SYMBOLIC CONSTANTS USING #define
Lets now examine a few examples of using these symbolic constants in our programs. Consider the following program which defines a constant called TAX_RATE.
Lets now examine a few examples of using these symbolic constants in our programs. Consider the following program which defines a constant called TAX_RATE.
#include
#define TAX_RATE 0.10
main()
{
float balance;
float tax;
balance = 72.10;
tax = balance * TAX_RATE;
printf(“The tax on %.2f is %.2fn”, balance, tax );
}
The pre-processor first replaces all symbolic constants before the program is compiled, so after preprocessing the file (and before its compiled), it now looks like,
#include
#define TAX_RATE 0.10
main()
{
float balance;
float tax;
balance = 72.10;
tax = balance * 0.10;
printf(“The tax on %.2f is %.2fn”, balance, tax );
}
YOU CANNOT ASSIGN VALUES TO THE SYMBOLIC CONSTANTS
Considering the above program as an example, look at the changes we have made below. We have added a statement which tries to change the TAX_RATE to a new value.
Considering the above program as an example, look at the changes we have made below. We have added a statement which tries to change the TAX_RATE to a new value.
#include
#define TAX_RATE 0.10
main()
{
float balance;
float tax;
balance = 72.10;
TAX_RATE = 0.15;
tax = balance * TAX_RATE;
printf(“The tax on %.2f is %.2fn”, balance, tax );
}
This is illegal. You cannot re-assign a new value to a symbolic constant.
- ITS LITERAL SUBSTITUTION, SO BEWARE OF ERRORS
As shown above, the preprocessor performs literal substitution of symbolic constants. Lets modify the previous program slightly, and introduce an error to highlight a problem.
#include
#define TAX_RATE 0.10;
main()
{
float balance;
float tax;
balance = 72.10;
tax = (balance * TAX_RATE )+ 10.02;
printf(“The tax on %.2f is %.2fn”, balance, tax );
}
In this case, the error that has been introduced is that the #define is terminated with a semi-colon. The preprocessor performs the substitution and the offending line (which is flagged as an error by the compiler) looks like
tax = (balance * 0.10; )+ 10.02;
However, you do not see the output of the preprocessor. If you are using TURBO C, you will only see
tax = (balance * TAX_RATE )+ 10.02;
flagged as an error, and this actually looks okay (but its not! after substitution takes place).
MAKING PROGRAMS EASY TO MAINTAIN BY USING #define
The whole point of using #define in your programs is to make them easier to read and modify. Considering the above programs as examples, what changes would you need to make if the TAX_RATE was changed to 20%.
The whole point of using #define in your programs is to make them easier to read and modify. Considering the above programs as examples, what changes would you need to make if the TAX_RATE was changed to 20%.
Obviously, the answer is once, where the #define statement which declares the symbolic constant and its value occurs. You would change it to read
#define TAX_RATE = 0.20
Without the use of symbolic constants, you would hard code the value 0.20 in your program, and this might occur several times (or tens of times).
This would make changes difficult, because you would need to search and replace every occurrence in the program. However, as the programs get larger, what would happen if you actually used the value 0.20 in a calculation that had nothing to do with the TAX_RATE!
SUMMARY OF #define
- allow the use of symbolic constants in programs
- in general, symbols are written in uppercase
- are not terminated with a semi-colon
- generally occur at the beginning of the file
- each occurrence of the symbol is replaced by its value
- makes programs readable and easy to maintain
PREPROCESSOR STATEMENTS
The define statement is used to make programs more readable. Consider the following examples,
The define statement is used to make programs more readable. Consider the following examples,
#define TRUE 1 /* Don’t use a semi-colon , # must be first character on line */
#define FALSE 0
#define NULL 0
#define AND &
#define OR |
#define EQUALS ==
game_over = TRUE;
while( list_pointer != NULL )
…………….
Note that preprocessor statements begin with a # symbol, and are NOT terminated by a semi-colon. Traditionally, preprocessor statements are listed at the beginning of the source file.
Preprocessor statements are handled by the compiler (or preprocessor) before the program is actually compiled. All # statements are processed first, and the symbols (like TRUE) which occur in the C program are replaced by their value (like 1). Once this substitution has taken place by the preprocessor, the program is then compiled.
In general, preprocessor constants are written in UPPERCASE.
Class Exercise C4
Use pre-processor statements to replace the following constants
Use pre-processor statements to replace the following constants
0.312
W
37
CLASS EXERCISE C4
Use pre-processor statements to replace the following constants
Use pre-processor statements to replace the following constants
0.312
W
37
#define smallvalue 0.312
#define letter ‘W’
#define smallint 37
LITERAL SUBSTITUTION OF SYMBOLIC CONSTANTS USING #define
Lets now examine a few examples of using these symbolic constants in our programs. Consider the following program which defines a constant called TAX_RATE.
Lets now examine a few examples of using these symbolic constants in our programs. Consider the following program which defines a constant called TAX_RATE.
#include
#define TAX_RATE 0.10
main()
{
float balance;
float tax;
balance = 72.10;
tax = balance * TAX_RATE;
printf(“The tax on %.2f is %.2fn”, balance, tax );
}
The pre-processor first replaces all symbolic constants before the program is compiled, so after preprocessing the file (and before its compiled), it now looks like,
#include
#define TAX_RATE 0.10
main()
{
float balance;
float tax;
balance = 72.10;
tax = balance * 0.10;
printf(“The tax on %.2f is %.2fn”, balance, tax );
}
YOU CANNOT ASSIGN VALUES TO THE SYMBOLIC CONSTANTS
Considering the above program as an example, look at the changes we have made below. We have added a statement which tries to change the TAX_RATE to a new value.
Considering the above program as an example, look at the changes we have made below. We have added a statement which tries to change the TAX_RATE to a new value.
#include
#define TAX_RATE 0.10
main()
{
float balance;
float tax;
balance = 72.10;
TAX_RATE = 0.15;
tax = balance * TAX_RATE;
printf(“The tax on %.2f is %.2fn”, balance, tax );
}
This is illegal. You cannot re-assign a new value to a symbolic constant.
ITS LITERAL SUBSTITUTION, SO BEWARE OF ERRORS
As shown above, the preprocessor performs literal substitution of symbolic constants. Lets modify the previous program slightly, and introduce an error to highlight a problem.
As shown above, the preprocessor performs literal substitution of symbolic constants. Lets modify the previous program slightly, and introduce an error to highlight a problem.
#include
#define TAX_RATE 0.10;
main()
{
float balance;
float tax;
balance = 72.10;
tax = (balance * TAX_RATE )+ 10.02;
printf(“The tax on %.2f is %.2fn”, balance, tax );
}
In this case, the error that has been introduced is that the #define is terminated with a semi-colon. The preprocessor performs the substitution and the offending line (which is flagged as an error by the compiler) looks like
tax = (balance * 0.10; )+ 10.02;
However, you do not see the output of the preprocessor. If you are using TURBO C, you will only see
tax = (balance * TAX_RATE )+ 10.02;
flagged as an error, and this actually looks okay (but its not! after substitution takes place).
MAKING PROGRAMS EASY TO MAINTAIN BY USING #define
The whole point of using #define in your programs is to make them easier to read and modify. Considering the above programs as examples, what changes would you need to make if the TAX_RATE was changed to 20%.
The whole point of using #define in your programs is to make them easier to read and modify. Considering the above programs as examples, what changes would you need to make if the TAX_RATE was changed to 20%.
Obviously, the answer is once, where the #define statement which declares the symbolic constant and its value occurs. You would change it to read
#define TAX_RATE = 0.20
Without the use of symbolic constants, you would hard code the value 0.20 in your program, and this might occur several times (or tens of times).
This would make changes difficult, because you would need to search and replace every occurrence in the program. However, as the programs get larger, what would happen if you actually used the value 0.20 in a calculation that had nothing to do with the TAX_RATE!
SUMMARY OF #define
- allow the use of symbolic constants in programs
- in general, symbols are written in uppercase
- are not terminated with a semi-colon
- generally occur at the beginning of the file
- each occurrence of the symbol is replaced by its value
- makes programs readable and easy to maintain
HEADER FILES
Header files contain definitions of functions and variables which can be incorporated into any C program by using the pre-processor #include statement. Standard header files are provided with each compiler, and cover a range of areas, string handling, mathematical, data conversion, printing and reading of variables.
Header files contain definitions of functions and variables which can be incorporated into any C program by using the pre-processor #include statement. Standard header files are provided with each compiler, and cover a range of areas, string handling, mathematical, data conversion, printing and reading of variables.
To use any of the standard functions, the appropriate header file should be included. This is done at the beginning of the C source file. For example, to use the function printf() in a program, the line
#include
should be at the beginning of the source file, because the definition for printf() is found in the file stdio.h All header files have the extension .h and generally reside in the /include subdirectory.
#include
#include “mydecls.h”
The use of angle brackets <> informs the compiler to search the compilers include directory for the specified file. The use of the double quotes “” around the filename inform the compiler to search in the current directory for the specified file.
Practice Exercise 1: Defining Variables
1. Declare an integer called sum
2. Declare a character called letter
3. Define a constant called TRUE which has a value of 1
4. Declare a variable called money which can be used to hold currency
5. Declare a variable called arctan which will hold scientific notation values (+e)
6. Declare an integer variable called total and initialise it to zero.
7. Declare a variable called loop, which can hold an integer value.
8. Define a constant called GST with a value of .125
Answers to Practice Exercise 1: Defining Variables
1. Declare an integer called sum
int sum;
2. Declare a character called letter
char letter;
3. Define a constant called TRUE which has a value of 1
#define TRUE 1
4. Declare a variable called money which can be used to hold currency
float money;
5. Declare a variable called arctan which will hold scientific notation values (+e)
double arctan;
6. Declare an integer variable called total and initialise it to zero.
int total;
total = 0;
7. Declare a variable called loop, which can hold an integer value.
int loop;
8. Define a constant called GST with a value of .125
#define GST 0.125
ARITHMETIC OPERATORS
The symbols of the arithmetic operators are:-
The symbols of the arithmetic operators are:-
Operation | Operator | Comment | Value of sum after | |
Multiply | * | sum = sum * 2; | 4 | 8 |
Divide | / | sum = sum / 2; | 4 | 2 |
Addition | + | sum = sum + 2; | 4 | 6 |
Subtraction | – | sum = sum -2; | 4 | 2 |
Increment | ++ | ++sum; | 4 | 5 |
Decrement | — | –sum; | 4 | |
Modulus | % | sum = sum % 3; | 4 | 1 |
The following code fragment adds the variables loop and count together, leaving the result in the variable sum
sum = loop + count;
Note: If the modulus % sign is needed to be displayed as part of a text string, use two, ie %%
#include
main()
{
int sum = 50;
float modulus;
modulus = sum % 10;
printf(“The %% of %d by 10 is %fn”, sum, modulus);
}
Sample Program Output
The % of 50 by 10 is 0.000000
CLASS EXERCISE C5
What does the following change do to the printed output of the previous program?
What does the following change do to the printed output of the previous program?
printf(“The %% of %d by 10 is %.2fn”, sum, modulus);
ANSWERS: CLASS EXERCISE C5
#include
main()
{
int sum = 50;
float modulus;
modulus = sum % 10;
printf(“The %% of %d by 10 is %.2fn”, sum, modulus);
}
The % of 50 by 10 is 0.00
_
Practice Exercise 2: Assignments
1. Assign the value of the variable number1 to the variable total
2. Assign the sum of the two variables loop_count and petrol_cost to the variable sum
3. Divide the variable total by the value 10 and leave the result in the variable discount
4. Assign the character W to the char variable letter
5. Assign the result of dividing the integer variable sum by 3 into the float variable costing. Use type casting to ensure that the remainder is also held by the float variable.
Answers: Practise Exercise 2: Assignments
1. Assign the value of the variable number1 to the variable total
total = number1;
2. Assign the sum of the two variables loop_count and petrol_cost to the variable sum
sum = loop_count + petrol_cost;
3. Divide the variable total by the value 10 and leave the result in the variable discount
discount = total / 10;
4. Assign the character W to the char variable letter
letter = ‘W’;
5. Assign the result of dividing the integer variable sum by 3 into the float variable costing. Use type casting to ensure that the remainder is also held by the float variable.
costing = (float) sum / 3;
PRE/POST INCREMENT/DECREMENT OPERATORS
PRE means do the operation first followed by any assignment operation , POST means do the operation after any assignment operation. Consider the following statements
PRE means do the operation first followed by any assignment operation , POST means do the operation after any assignment operation. Consider the following statements
++count; /* PRE Increment, means add one to count */
count++; /* POST Increment, means add one to count */
In the above example, because the value of count is not assigned to any variable, the effects of the PRE/POST operation are not clearly visible.
Lets examine what happens when we use the operator along with an assignment operation. Consider the following program,
#include
main()
{
int count = 0, loop;
loop = ++count; /* same as count = count + 1; loop = count; */
printf(“loop = %d, count = %dn”, loop, count);
loop = count++; /* same as loop = count; count = count + 1; */
printf(“loop = %d, count = %dn”, loop, count);
}
Sample Program Output
loop = 1, count = 1
loop = 1; count = 2
If the operator precedes (is on the left hand side) of the variable, the operation is performed first, so the statement
loop = ++count;
really means increment count first, then assign the new value of count to loop.
Which way do you write it?
Where the increment/decrement operation is used to adjust the value of a variable, and is not involved in an assignment operation, which should you use,
Where the increment/decrement operation is used to adjust the value of a variable, and is not involved in an assignment operation, which should you use,
++loop_count;
or
loop_count++;
The answer is, it really does not matter. It does seem that there is a preference amongst C programmers to use the post form.
Something to watch out for
Whilst we are on the subject, do not get into the habit of using a space(s) between the variable name and the pre/post operator.
Whilst we are on the subject, do not get into the habit of using a space(s) between the variable name and the pre/post operator.
loop_count ++;
Try to be explicit in binding the operator tightly by leaving no gap.
GOOD FORM
Perhaps we should say programming style or readability. The most common complaints we would have about beginning C programmers can be summarized as,
Perhaps we should say programming style or readability. The most common complaints we would have about beginning C programmers can be summarized as,
- they have poor layout
- their programs are hard to read
Your programs will be quicker to write and easier to debug if you get into the habit of actually formatting the layout correctly as you write it.
For instance, look at the program below
#include
main()
{
int sum,loop,kettle,job;
char Whoknows;
sum=9;
loop=7;
whoKnows=’A’;
printf(“Whoknows=%c,kettle=%dn”,whoknows,kettle);
}
It is our contention that the program is hard to read, and because of this, will be difficult to debug for errors by an inexperienced programmer. It also contains a few deliberate mistakes!
Okay then, lets rewrite
the program using good form.
the program using good form.
#include
main()
{
int sum, loop, kettle = 0, job;
char whoknows;
sum = 9;
loop = 7;
whoknows = ‘A’;
printf( “Whoknows = %c, kettle = %dn”, whoknows, kettle );
}
We have also corrected the mistakes. The major differences are
- the { and } braces directly line up underneath each other
This allows us to check indent levels and ensure that statements belong to the correct block of code. This becomes vital as programs become more complex
- spaces are inserted for readability
We as humans write sentences using spaces between words. This helps our comprehension of what we read (if you don’t believe me, try reading the following sentence. Wish I had a dollar for every time I made a mistake. The insertion of spaces will also help us identify mistakes quicker. - good
indentation
Indent levels (tab stops) are clearly used to block statements, here we clearly see and identify functions, and the statements which belong to each { } program body. - initialization of variables
The first example prints out the value of kettle, a variable that has no initial value. This is corrected in the second example.
C Programming
- KEYBOARD INPUT
There is a function in C which allows the programmer to accept input from a keyboard. The following program illustrates the use of this function, - #include
- main() /* program which introduces keyboard input */
- {
- int number
- printf(“Type in a number n”);
- scanf(“%d”, &number);
- printf(“The number you typed was %dn”, number);
- }
- Sample Program Output
- Type in a number
- 23
- The number you typed was 23
- An integer called number is defined. A prompt to enter in a number is then printed using the statement
- printf(“Type in a number n:”);
- The scanf routine, which accepts the response, has two arguments. The first (“%d”) specifies what type of data type is expected (ie char, int, or float). List of formatters for scanf() found here.
- The second argument (&number) specifies the variable into which the typed response will be placed. In this case the response will be placed into the memory location associated with the variable number.
- This explains the special significance of the & character (which means the address of).
- Sample program illustrating use of scanf() to read integers, characters and floats
- #include < stdio.h >
- main()
- {
- int sum;
- char letter;
- float money;
- printf(“Please enter an integer value “);
- scanf(“%d”, &sum );
- printf(“Please enter a character “);
- /* the leading space before the %c ignores space characters in the input */
- scanf(” %c”, &letter );
- printf(“Please enter a float variable “);
- scanf(“%f”, &money );
- printf(“nThe variables you entered weren”);
- printf(“value of sum = %dn”, sum );
- printf(“value of letter = %cn”, letter );
- printf(“value of money = %fn”, money );
- }
- Sample Program Output
- Please enter an integer value
- 34
- Please enter a character
- W
- Please enter a float variable
- 32.3
- The variables you entered were
- value of sum = 34
- value of letter = W
- value of money = 32.300000
- This program illustrates several important points.
- the c language provides no error checking for user input. The user is expected to enter the correct data type. For instance, if a user entered a character when an integer value was expected, the program may enter an infinite loop or abort abnormally.
- It’s up to the programmer to validate data for correct type and range of values.
Practise Exercise 3: printf() and scanf()
1. Use a printf statement to print out the value of the integer variable sum
2. Use a printf statement to print out the text string “Welcome”, followed by a newline.
3. Use a printf statement to print out the character variable letter
4. Use a printf statement to print out the float variable discount
5. Use a printf statement to print out the float variable dump using two decimal places
6. Use a scanf statement to read a decimal value from the keyboard, into the integer variable sum
7. Use a scanf statement to read a float variable into the variable discount_rate
8. Use a scanf statement to read a single character from the keyboard into the variable operator. Skip leading blanks, tabs and newline characters.
Answers: Practise Exercise 3: printf() and scanf()
1. Use a printf statement to print out the value of the integer variable sum
printf(“%d”, sum);
2. Use a printf statement to print out the text string “Welcome”, followed by a newline.
printf(“Welcomen”);
3. Use a printf statement to print out the character variable letter
printf(”
%c”, letter);
%c”, letter);
4. Use a printf statement to print out the float variable discount
printf(“%f”, discount);
5. Use a printf statement to print out the float variable dump using two decimal places
printf(“%.2f”, dump);
6. Use a scanf statement to read a decimal value from the keyboard, into the integer variable sum
scanf(“%d”, &sum);
7. Use a scanf statement to read a float variable into the variable discount_rate
scanf(“%f”, &discount_rate);
8. Use a scanf statement to read a single character from the keyboard into the variable operator. Skip leading blanks, tabs and newline characters.
scanf(” %c”, &operator);
THE RELATIONAL OPERATORS
These allow the comparision of two or more variables.
These allow the comparision of two or more variables.
Operator | Meaning |
== | equal to |
!= | not equal |
< | less than |
<= | less than or equal to |
> | greater than |
>= | greater than or equal to |
In the next few screens, these will be used in for loops and if statements.
The operator
<>
may be legal in Pascal, but is illegal in C.
ITERATION, FOR LOOPS
The basic format of the for statement is,
The basic format of the for statement is,
for( start condition; continue condition; re-evaulation )
program statement;
/* sample program using a for statement */
#include
main() /* Program introduces the for statement, counts to ten */
{
int count;
for( count = 1; count <= 10; count = count + 1 )
printf(“%d “, count );
printf(“n”);
}
Sample Program Output
1 2 3 4 5 6 7 8 9 10
The program declares an integer variable count. The first part of the for statement
for( count = 1;
initialises the value of count to 1. The for loop continues whilst the condition
count <= 10;
evaluates as TRUE. As the variable count has just been initialised to 1, this condition is TRUE and so the program statement
printf(“%d “, count );
is executed, which prints the value of count to the screen, followed by a space character.
Next, the remaining statement of the for is executed
count = count + 1 );
which adds one to the current value of count. Control now passes back to the conditional test,
count <= 10;
which evaluates as true, so the program statement
printf(“%d “, count );
is executed. Count is incremented again, the condition re-evaluated etc, until count reaches a value of 11.
When this occurs, the conditional test
count <= 10;
evaluates as FALSE, and the for loop terminates, and program control passes to the statement
printf(“n”);
which prints a newline, and then the program terminates, as there are no more statements left to execute.
/* sample program using a for statement */
#include
main()
{
int n, t_number;
t_number = 0;
for( n = 1; n <= 200; n = n + 1 )
t_number = t_number + n;
printf(“The 200th triangular_number is %dn”, t_number);
}
Sample Program Output
The 200th triangular_number is 20100
The above program uses a for loop to calculate the s
um of the numbers from 1 to 200 inclusive (said to be the triangular number).
um of the numbers from 1 to 200 inclusive (said to be the triangular number).
The following diagram shows the order of processing each part of a for
An example of using a for loop to print out characters
#include
main()
{
char letter;
for( letter = ‘A’; letter <= 'E'; letter = letter + 1 ) {
printf(“%c “, letter);
}
}
Sample Program Output
A B C D E
An example of using a for loop to count numbers, using two initialisations
#include
main()
{
int total, loop;
for( total = 0, loop = 1; loop <= 10; loop = loop + 1 ){
total = total + loop;
}
printf(“Total = %dn”, total );
}
Sample Program Output
Total = 55
In the above example, the variable total is initialised to 0 as the first part of the for loop. The two statements,
for( total = 0, loop = 1;
are part of the initialisation. This illustrates that more than one statement is allowed, as long as they are separated by commas.
Graphical Animation of for loop
To demonstrate the operation of the for statement, lets consider a series of animations.
To demonstrate the operation of the for statement, lets consider a series of animations.
The code we will be using is
#include
main() {
int x, y, z;
x = 2;
y = 2;
z = 3;
for( x = 1; x <= 6; x = x + 1 ) {
printf(“%d”, y );
y = y + 1;
}
printf(“n%d”, z );
}
Sample Program Output
2 3 4 5 6 7
3
The following diagram shows the initial state of the program, after the initialization of the variables x, y, and z.
On entry to the for statement, the first expression is executed, which in our example assigns the value 1 to x. This can be seen in the graphic shown below (Note: see the Variable Values: section)
The next part of the for is executed, which tests the value of the loop variable x against the constant 6.
It can be seen from the variable window that x has a current value of 1, so the test is successful, and program flow branches to execute the statements of the for body, which prints out the value of y, then adds 1 to y. You can see the program output and the state of the variables shown in the graphic below.
After executing the statements of the for body, execution returns to the last part of the for statement. Here, the value of x is incremented by 1. This is seen by the value of x changing to 2.
Next, the condition of the for variable is tested again. It continues because the value of it (2) is less than 6, so the body of the loop is executed again.
Execution continues till the value of x reaches 7. Lets now jump ahead in the animation to see this. Here, the condition test will fail, and the for statement finishes, passing control to the statement which follows.
EXERCISE C6
Rewrite the previous program by calculating the 200th triangular number, and make the program shorter (if possible).
Rewrite the previous program by calculating the 200th triangular number, and make the program shorter (if possible).
CLASS EXERCISE C7
What is the difference between the two statements,
What is the difference between the two statements,
a == 2
a = 2
CLASS EXERCISE C8
Change the printf line of the a
bove program to the following,
Change the printf line of the a
bove program to the following,
printf(” %2d %2dn”,n,t_number);
What does the inclusion of the 2 in the %d statements achieve?
EXERCISE C9
Create a C program which calculates the triangular number of the users request, read from the keyboard using scanf(). A triangular number is the sum of the preceding numbers, so the triangular number 7 has a value of
Create a C program which calculates the triangular number of the users request, read from the keyboard using scanf(). A triangular number is the sum of the preceding numbers, so the triangular number 7 has a value of
7 + 6 + 5 + 4 + 3 + 2 + 1
Answer: EXERCISE C6
#include
main()
{
int n = 1, t_number = 0;
for( n <= 200; n++ )
t_number = t_number + n;
printf(“The 200th triangular_number is %dn”, t_number);
}
Answer: CLASS EXERCISE C7
a == 2 equality test
a = 2 assignment
Answer: CLASS EXERCISE C8
The inclusion of the 2 in the %d statements achieves a field width of two places, and prints a leading 0 where the value is less than 10.
The inclusion of the 2 in the %d statements achieves a field width of two places, and prints a leading 0 where the value is less than 10.
Answer: EXERCISE C9
#include
main()
{
int n = 1, t_number = 0, input;
printf(“Enter a numbern”);
scanf(“%d”, &input);
for( n <= input; n++ )
t_number = t_number + n;
printf(“The triangular_number of %d is %dn”, input, t_number);
}
Practice Exercise 4: for loops
1. Write a for loop to print out the values 1 to 10 on separate lines.
2. Write a for loop which will produce the following output (hint: use two nested for loops)
1
22
333
4444
55555
3. Write a for loop which sums all values between 10 and 100 into a variable called total. Assume that total has NOT been initialized to zero.
4. Write a for loop to print out the character set from A-Z.
PRACTISE EXERCISE 4
for loops
1. Write a for loop to print out the values 1 to 10 on separate lines.
for( loop = 1; loop <= 10; loop = loop + 1 )
printf(“%dn”, loop)
2. Write a for loop which will produce the following output (hint: use two nested for loops)
1
22
333
4444
55555
for( loop = 1; loop <= 5; loop = loop + 1 )
{
for( count = 1; count <= loop; count = count + 1 )
printf(“%d”, loop );
printf(“n”);
}
3. Write a for loop which sums all values between 10 and 100 into a variable called total. Assume that total has NOT been initialized to zero.
for( loop = 10, total = 0; loop <= 100; loop = loop + 1 )
total = total + loop;
4. Write a for loop to print out the character set from A-Z.
for( ch = ‘A’; ch <= 'Z'; ch = ch + 1 )
printf(“%c”, ch );
printf(“n”);
THE WHILE STATEMENT
The while provides a mechanism for repeating C statements whilst a condition is true. Its format is,
The while provides a mechanism for repeating C statements whilst a condition is true. Its format is,
while( condition )
program statement;
Somewhere within the body of the while loop a statement must alter the value of the condition to allow the loop to finish.
/* Sample program including while */
#include
main()
{
int loop = 0;
while( loop <= 10 ) {
printf(“%dn”, loop);
++loop;
}
}
Sample Program Output
0
1
…
10
The above program uses a while loop to repeat the statements
printf(“%dn”, loop);
++loop;
whilst the value of the variable loop is less than or equal to 10.
Note how the variable upon which the while is dependent is initialised prior to the while statement (in this case the previous line), and also that the value of the variable is altered within the loop, so that eventually the conditional test will succeed and the while loop will terminate.
This program is functionally equivalent to the earlier for program which counted to ten.
THE DO WHILE STATEMENT
The do { } while statement allows a loop to continue whilst a condition evaluates as TRUE (non-zero). The loop is executed as least once.
The do { } while statement allows a loop to continue whilst a condition evaluates as TRUE (non-zero). The loop is executed as least once.
/* Demonstration of DO…WHILE */
#include
main()
{
int value, r_digit;
printf(“Enter the number to be reversed.n”);
scanf(“%d”, &value);
do {
r_digit = value % 10;
printf(“%d”, r_digit);
value = value / 10;
} while( value != 0 );
printf(“n”);
}
The above program reverses a number that is entered by the user. It does this by using the modulus % operator to extract the right most digit into the variable r_digit. The original number is then divided by 10, and the operation repeated whilst the number is not equal to 0.
It is our contention that this programming construct is improper and should be avoided. It has potential problems, and you should be aware of these.
One such problem is deemed to be lack of control. Considering the above program code portion,
do {
r_digit = value % 10;
printf(“%d”, r_digit);
value = value / 10;
} while( value != 0 );
there is NO choice whether to execute the loop. Entry to the loop is automatic, as you only get a choice to continue.
Another problem is that the loop is always executed at least once. This is a by-product of the lack of control. This means its possible to enter a do { } while loop with invalid data.
Beginner programmers can easily get into a whole heap of trouble, so our advice is to avoid its use. This is the only time that you will encounter it in this course. Its easy to avoid the use of this construct by replacing it with the following algorithms,
initialise loop control variable
while( loop control variable is valid ) {
process data
adjust control variable if necessary
}
Okay, lets now rewrite the above example to remove the do { } while construct.
/* rewritten code to remove construct */
#include
main()
{
int value, r_digit;
value = 0;
while( value <= 0 ) {
printf(“Enter the number to be reversed.n”);
scanf(“%d”, &value);
if( value <= 0 )
printf(“The number must be positiven”);
}
while( value != 0 )
{
r_digit = value % 10;
printf(“%d”, r_digit);
value = value / 10;
}
printf(“n”);
}
Sample Program Output
Enter the number to be reversed.
-43
The number must be positive
Enter the number to be reversed.
423
324
SELECTION (IF STATEMENTS)
The if statements allows branching (decision making) depending upon the value or state of variables. This allows statements to be executed or skipped, depending upon decisions. The basic format is,
if( expression )
program statement;
Example;
if( students < 65 )
++student_count;
In the above example, the variable student_count is incremented by one only if the value of the integer variable students is less than 65.
The following program uses an if statement to validate the users input to be in the range 1-10.
#include
main()
{
int number
int valid = 0;
while( valid == 0 ) {
printf(“Enter a number between 1 and 10 –>”);
scanf(“%d”, &number);
/* assume number is valid */
valid = 1;
if( number < 1 ) {
printf(“Number is below 1. Please re-entern”);
valid = 0;
}
if( number > 10 ) {
printf(“Number is above 10. Please re-entern”);
valid = 0;
}
}
printf(“The number is %dn”, number );
}
Sample Program Output
Enter a number between 1 and 10 –> -78
Number is below 1. Please re-enter
Enter a number between 1 and 10 –> 4
The number is 4
EXERCISE C10
Write a C program that allows the user to enter in 5 grades, ie, marks between 0 – 100. The program must calculate the average mark, and state the number of marks less than 65.
Write a C program that allows the user to enter in 5 grades, ie, marks between 0 – 100. The program must calculate the average mark, and state the number of marks less than 65.
Consider the following program which determines whether a character entered from the keyboard is within the range A to Z.
#include
main()
{
char letter;
printf(“Enter a character –>”);
scanf(” %c”, &letter );
if( letter >= ‘A’ ) {
if( letter <= 'Z' )
printf(“The character is within A to Zn”);
}
}
Sample Program Output
Enter a character –> C
The character is within A to Z
The program does not print any output if the character entered is not within the range A to Z. This can be addressed on the following pages with the if else construct.
Please note use of the leading space in the statement (before %c)
scanf(” %c”, &letter );
This enables the skipping of leading TABS, Spaces, (collectively called whitespaces) and the ENTER KEY. If the leading space was not used, then the first entered character would be used, and scanf would not ignore the whitespace characters.
COMPARING float types FOR EQUALITY
Because of the way in which float types are stored, it makes it very difficult to compare float types for equality. Avoid trying to compare float variables for equality, or you may encounter unpredictable results.
Because of the way in which float types are stored, it makes it very difficult to compare float types for equality. Avoid trying to compare float variables for equality, or you may encounter unpredictable results.
if else
The general format for these are,
The general format for these are,
if( condition 1 )
statement1;
else if( condition 2 )
statement2;
else if( condition 3 )
statement3;
else
statement4;
The else clause allows action to be taken where the condition evaluates as false (zero).
The following program uses an if else statement to validate the users input to be in the range 1-10.
#include
main()
{
int number
int valid = 0;
while( valid == 0 ) {
printf(“Enter a number between 1 and 10 –>”);
scanf(“%d”, &number);
if( number < 1 ) {
printf(“Number is below 1. Please re-entern”);
valid = 0;
}
else if( number > 10 ) {
printf(“Number is above 10. Please re-entern”);
valid = 0;
}
else
valid = 1;
}
printf(“The number is %dn”, number );
}
Sample Program Output
Enter a number between 1 and 10 –> 12
Number is above 10. Please re-enter
Enter a number between 1 and 10 –> 5
The number is 5
This program is slightly different from the previous example in that an else clause is used to set the variable valid to 1. In this program, the logic should be easier to follow.
/* Illustates nested if else and multiple arguments to the scanf function. */
#include
main()
{
int invalid_operator = 0;
char operator;
float number1, number2, result
printf(“Enter two numbers and an operator in the formatn”);
printf(” number1 operator number2n”);
scanf(“%f %c %f”, &number1, &operator, &number2);
if(operator == ‘*’)
result = number1 * number2;
else if(operator == ‘/’)
result = number1 / number2;
else if(operator == ‘+’)
result = number1 + number2;
else if(operator == ‘-‘)
result = number1 – number2;
else
invalid_operator = 1;
if( invalid_operator != 1 )
printf(“%f %c %f is %fn”, number1, operator, number2, result );
else
printf(“Invalid operator.n”);
}
Sample Program Output
Enter two numbers and an operator in the format
number1 operator number2
23.2 + 12
23.2 + 12 is 35.2
The above program acts as a simple calculator.
Practice Exercise 5: while loops and if else
1. Use a while loop to print the integer values 1 to 10 on the screen
12345678910
2. Use a nested while loop to reproduce the following output
1
22
333
4444
55555
3. Use an if statement to compare the value of an integer called sum against the value 65, and if it is less, print the text string “Sorry, try again”.
4. If total is equal to the variable good_guess, print the value of total, else print the value of good_guess.
Answers: Practice Exercise 5: while loops and if else
1. Use a while loop to print the integer values 1 to 10 on the screen
12345678910
#include
main()
{
int loop;
loop = 1;
while( loop <= 10 ) {
printf(“%d”, loop);
loop++;
}
printf(“n”);
}
2. Use a nested while loop to reproduce the following output
1
22
333
4444
55555
#include
main()
{
int loop;
int count;
loop = 1;
while( loop <= 5 ) {
count = 1;
while( count <= loop ) {
printf(“%d”, count);
count++;
}
loop++;
}
printf(“n”);
}
3. Use an if statement to compare the value of an integer called sum against the value 65, and if it is less, print the text string “Sorry, try again”.
if( sum < 65 )
printf(“Sorry, try again.n”);
4. If total is equal to the variable good_guess, print the value of total, else print the value of good_guess.
if( total == good_guess )
printf(“%dn”, total );
else
printf(“%dn”, good_guess );
COMPOUND RELATIONALS ( AND, NOT, OR, EOR )
Combining more than one condition
These allow the testing of more than one condition as part of selection statements. The symbols are
These allow the testing of more than one condition as part of selection statements. The symbols are
LOGICAL AND &&
Logical and requires all conditions to evaluate as TRUE (non-zero).
LOGICAL OR ||
Logical or will be executed if any ONE of the conditions is TRUE (non-zero).
LOGICAL NOT !
logical not negates (changes from TRUE to FALSE, vsvs) a condition.
LOGICAL EOR ^
Logical eor will be excuted if either condition is TRUE, but NOT if they are all true.
The following program uses an if statement with logical OR to validate the users input to be in the range 1-10.
#include
main()
{
int number
int valid = 0;
while( valid == 0 ) {
printf(“Enter a number between 1 and 10 –>”);
scanf(“%d”, &number);
if( (number < 1 ) || (number > 10) ){
printf(“Number is outside range 1-10. Please re-entern”);
valid = 0;
}
else
valid = 1;
}
printf(“The number is %dn”, number );
}
Sample Program Output
Enter a number between 1 and 10 –> 56
Number is outside range 1-10. Please re-enter
Enter a number between 1 and 10 –> 6
The number is 6
This program is slightly different from the previous example in that a LOGICAL OR eliminates one of the else clauses.
COMPOUND RELATIONALS ( AND, NOT, OR, EOR )
NEGATION
#include
main()
{
int flag = 0;
if( ! flag ) {
printf(“The flag is not set.n”);
flag = ! flag;
}
printf(“The value of flag is %dn”, flag);
}
Sample Program Output
The flag is not set.
The value of flag is 1
The program tests to see if flag is not (!) set; equal to zero. It then prints the appropriate message, changes the state of flag flag becomes equal to not flag equal to 1. Finally the value of flag is printed.
COMPOUND RELATIONALS ( AND, NOT, OR, EOR )
Range checking using Compound Relational
Consider where a value is to be inputted from the user, and checked for validity to be within a certain range, lets say between the integer values 1 and 100.
Consider where a value is to be inputted from the user, and checked for validity to be within a certain range, lets say between the integer values 1 and 100.
#include
main()
{
int number
int valid = 0;
while( valid == 0 ) {
printf(“Enter a number between 1 and 100”);
scanf(“%d”, &number );
if( (number < 1) || (number > 100) )
printf(“Number is outside legal rangen”);
else
valid = 1;
}
printf(“Number is %dn”, number );
}
Sample Program Output
Enter a number between 1 and 100
203
Number is outside legal range
Enter a number between 1 and 100
-2
Number is outside legal range
Enter a number between 1 and 100
37
Number is 37
The program uses valid, as a flag to indicate whether the inputted data is within the required range of allowable values. The while loop continues whilst valid is 0.
The statement
if( (number < 1) || (number > 100) )
checks to see if the number entered by the user is within the valid range, and if so, will set the value of valid to 1, allowing the while loop to exit.
Now consider writing a program which validates a character to be within the range A-Z, in other words alphabetic.
#include
main()
{
char ch;
int valid = 0;
while( valid == 0 ) {
printf(“Enter a character A-Z”);
scanf(” %c”, &ch );
if( (ch >= ‘A’) && (ch <= 'Z') )
valid = 1;
else
printf(“Character is outside legal rangen”);
}
printf(“Character is %cn”, ch );
}
Sample Program Output
Enter a character A-Z
a
Character is outside legal range
Enter a character A-Z
0
Character is outside legal range
Enter a character A-Z
R
Character is R
In this instance, the AND is used because we want validity between a range, that is all values between a low and high limit. In the previous case, we used an OR statement to test to see if it was outside or below the lower limit or above the higher limit.
witch() case:
The switch case statement is a better way of writing a program when a series of if elses occurs. The general format for this is,
The switch case statement is a better way of writing a program when a series of if elses occurs. The general format for this is,
switch ( expression ) {
case value1:
program statement;
program statement;
……
break;
case valuen:
program statement;
…….
break;
default:
…….
…….
break;
}
The keyword break must be included at the end of each case statement. The default clause is optional, and is executed if the cases are not met. The right brace at the end signifies the end of the case selections.
Rules for switch statements
values for ‘case’ must be integer or character constants
the order of the ‘case’ statements is unimportant
the default clause may occur first (convention places it last)
you cannot use expressions or ranges
#include
main()
{
int menu, numb1, numb2, total;
printf(“enter in two numbers –>”);
scanf(“%d %d”, &numb1, &numb2 );
printf(“enter in choicen”);
printf(“1=additionn”);
printf(“2=subtractionn”);
scanf(“%d”, &menu );
switch( menu ) {
case 1: total = numb1 + numb2; break;
case 2: total = numb1 – numb2; break;
default: printf(“Invalid option selectedn”);
}
if( menu == 1 )
printf(“%d plus %d is %dn”, numb1, numb2, total );
else if( menu == 2 )
printf(“%d minus %d is %dn”, numb1, numb2, total );
}
Sample Program Output
enter in two numbers –> 37 23
enter in choice
1=addition
2=subtraction
2
37 minus 23 is 14
The above program uses a switch statement to validate and select upon the users input choice, simulating a simple menu of choices.
EXERCISE C11
Rewrite the previous program, which accepted two numbers and an operator, using the switch case statement
Rewrite the previous program, which accepted two numbers and an operator, using the switch case statement
THE switch case STATEMENT
EXERCISE C11
Rewrite the previous program, which accepted two numbers and an operator, using the switch case statement.
Rewrite the previous program, which accepted two numbers and an operator, using the switch case statement.
/* Illustates nested if else and multiple arguments to the scanf function. */
#include
main()
{
int invalid_operator = 0;
char operator;
float number1, number2, result
printf(“Enter two numbers and an operator in the formatn”);
printf(” number1 operator number2n”);
scanf(“%f %c %f”, &number1, &operator, &number2);
if(operator == ‘*’)
result = number1 * number2;
else if(operator == ‘/’)
result = number1 / number2;
else if(operator == ‘+’)
result = number1 + number2;
else if(operator == ‘-‘)
result = number1 – number2;
else
invalid_operator = 1;
if( invalid_operator != 1 )
printf(“%f %c %f is %fn”, number1, operator, number2, result );
else
printf(“Invalid operator.n”);
}
Solution
/* Illustates switch */
#include
main()
{
int invalid_operator = 0;
char operator;
float number1, number2, result
printf(“Enter two numbers and an operator in the formatn”);
printf(” number1 operator number2n”);
scanf(“%f %c %f”, &number1, &operator, &number2);
switch( operator ) {
case ‘*’ : result = number1 * number2; break;
case ‘/’ : result = number1 / number2; break;
case ‘+’ : result = number1 + number2; break;
case ‘-‘ : result = number1 – number2; break;
default : invalid_operator = 1;
}
switch( invalid_operator ) {
case 1 : printf(“Invalid operator.n”); break;
default : printf(“%f %c %f is %fn”, number1, operator, number2, result );
}
}
Practice Exercise 6
Compound Relational and switch
1. if sum is equal to 10 and total is less than 20, print the text string “incorrect.”.
2. if flag is 1 or letter is not an ‘X’, then assign the value 0 to exit_flag, else set exit_flag to 1.
3. rewrite the following statements using a switch statement
if( letter == ‘X’ )
sum = 0;
else if ( letter == ‘Z’ )
valid_flag = 1;
else if( letter == ‘A’ )
sum = 1;
else
printf(“Unknown letter –>%cn”, letter );
Answers: Practice Exercise 6
Compound Relational and switch
1. if sum is equal to 10 and total is less than 20, print the text string “incorrect.”.
if( (sum == 10) && (total < 20) )
printf(“incorrect.n”);
2. if flag is 1 or letter is not an ‘X’, then assign the value 0 to exit_flag, else set exit_flag to 1.
if( (flag == 1) || (letter != ‘X’) )
exit_flag = 0;
else
exit_flag = 1;
3. rewrite the following statements using a switch statement
if( letter == ‘X’ )
sum = 0;
else if ( letter == ‘Z’ )
valid_flag = 1;
else if( letter == ‘A’ )
sum = 1;
else
printf(“Unknown letter –>%cn”, letter );
switch( letter ) {
case ‘X’ : sum = 0; break;
case ‘Z’ : valid_flag = 1; break;
case ‘A’ : sum = 1; break;
default : printf(“Unknown letter –>%cn”, letter );
}
ACCEPTING SINGLE CHARACTERS FROM THE KEYBOARD
getchar
The following program illustrates this,
The following program illustrates this,
#include
main()
{
int i;
int ch;
for( i = 1; i<= 5; ++i ) {
ch = getchar();
putchar(ch);
}
}
Sample Program Output
AACCddEEtt
The program reads five characters (one for each iteration of the for loop) from the keyboard. Note that getchar() gets a single character from the keyboard, and putchar() writes a single character (in this case, ch) to the console screen.
The file ctype.h provides routines for manipulating characters.
BUILT IN FUNCTIONS FOR STRING HANDLING
string.h
You may want to look at the section on arrays first!. The following macros are built into the file string.h
You may want to look at the section on arrays first!. The following macros are built into the file string.h
strcat Appends a string
strchr Finds first occurrence of a given character
strcmp Compares two strings
strcmpi Compares two strings, non-case sensitive
strcpy Copies one string to another
strlen Finds length of a string
strlwr Converts a string to lowercase
strncat Appends n characters of string
strncmp Compares n characters of two strings
strncpy Copies n characters of one string to another
strnset Sets n characters of string to a given character
strrchr Finds last occurrence of given character in string
strrev Reverses string
strset Sets all characters of string to a given character
strspn Finds first substring from given character set in string
strupr Converts string to uppercase
To convert a string to uppercase
#include
#include
main()
{
char name[80]; /* declare an array of characters 0-79 */
printf(“Enter in a name in lowercasen”);
scanf( “%s”, name );
strupr( name );
printf(“The name is uppercase is %s”, name );
}
Sample Program Output
Enter in a name in lowercase
samuel
The name in uppercase is SAMUEL
BUILT IN FUNCTIONS FOR CHARACTER HANDLING
The following character handling functions are defined in ctype.h
The following character handling functions are defined in ctype.h
isalnum Tests for alphanumeric character
isalpha Tests for alphabetic character
isascii Tests for ASCII character
iscntrl Tests for control character
isdigit Tests for 0 to 9
isgraph Tests for printable character
islower Tests for lowercase
isprint Tests for printable character
ispunct Tests for punctuation character
isspace Tests for space character
isupper Tests for uppercase character
isxdigit Tests for hexadecimal
toascii Converts character to ascii code
tolower Converts character to lowercase
toupper Converts character to uppercase
To convert a string array to uppercase a character at a time using toupper()
#include
#include
main()
{
char name[80];
int loop;
printf(“Enter in a name in lowercasen”);
scanf( “%s”, name );
for( loop = 0; name[loop] != 0; loop++ )
name[loop] = toupper( name[loop] );
printf(“The name is uppercase is %s”, name );
}
Sample Program Output
Enter in a name in lowercase
samuel
The name in uppercase is SAMUEL
Validation Of User Input In C
Basic Rules
- Don’t pass invalid data onwards.
- Validate data at input time.
- Always give the user meaningful feedback
- Tell the user what you expect to read as inpu
/* example one, a simple continue statement */
#include
#include
main()
{
int valid_input; /* when 1, data is valid and loop is exited */
char user_input; /* handles user input, single character menu choice */
valid_input = 0;
while( valid_input == 0 ) {
printf(“Continue (Y/N)?n”);
scanf(” %c”, &user_input );
user_input = toupper( user_input );
if((user_input == ‘Y’) || (user_input == ‘N’) ) valid_input = 1;
else printf(“