C Programming
C Programming
C Programming
Objectives
By the end of this lesson, students should be able to:
INTRODUCTION
C (and its object oriented version, C++) is one of the most widely used third generation
programming languages. Its power and flexibility ensure it is still the leading choice for almost all
areas of application, especially in the software development environment.
Many applications and many Operating systems are written in C or C++, including the compilers
for other programming languages, Unix, DOS and Windows. It continues to adapt to new uses
with new programming languages like Java, C#, Python, PHP, etc which lay the foundation on C
language.
1) Syntax: This is a language structure (or grammar) that allows humans to combine these
C commands into a program that actually does some-thing.
2) Semantics: This is a vocabulary of commands that humans can understand and that can
be converted into machine language, fairly easily, using compiler
A C program is a text file containing a sequence of C commands put together according to the
laws of C grammar. This text file is known as the source file carrying the extension .C
- an editor which is what you use to write your code as you build your .C source file.
- a compiler (& linker) converts your source file into a machine-executable .EXE file that
carries out your real-world commands.
There are tools combining both compiler and editor in one called development environment. We
will use DevC++ IDE (Integrated Development Environment), version 4.4.9.2. It can be
downloaded freely in www.sourceforge.net
The program can be now typed into the editor using the c syntax. Our first program on what we
are going to discover the functioning of a C-program is:
1 #include <stdio.h>
2 int main()
3 {
4 /* my first program in C */
4 printf("This is my first experience in C! \n");
6 return 0;
7 }
To save the program: The file saved is called the source file
File → save as → in the dialog box type the name and choose the type (here the type to choose
is C source code) → save.
Compiling is the process of transforming the source code (the instructions in the text file) into the
object code (instructions the computer’s microprocessor can understand). The linking step is
where the instructions are finally transformed into a program file. (Again, your compiler may do
this step automatically.)
Execute → Compile
After the compilation, if everything is ok, an executable code will be created with the same name
and in a same folder and with the extension .exe. Else the compiler will produce an error message.
In this case debug the program (check the code and correct the error) and recompile the source
code.
Finally, you run the program you have created. Yes, it’s a legitimate program, like any other on
your hard drive.
Execute → Run
1) #include <stdio.h>
The first line of the program #include <stdio.h> is a preprocessor command which is used to
include a library containing functions used in our program, It tells a C compiler to include stdio.h
file before going to actual compilation.
2) Main()
The C program starting point is identified by main(). This informs the computer where the program
actually starts. Two empty parentheses follow the function name. Sometimes, items may be in
these parentheses, which we will cover later.
3) { & }
All functions in C have their contents encased by curly braces. The two braces { and } signify the
begin and the end segments of the program. In general, braces are used throughout C to enclose a
block of statement to be treated as a unit.
4) Printf()
printf(...) is another function available in C which causes the message " This is my first
experience in C!" to be displayed on the screen. For printf to work, the header file “stdio.h” must
be included at the beginning of the program.
5) \n
6) /*… */ or //
They are use to insert comments into a C program. Comments serve for internal documentation
for program structure and functionalities. There are two types of comment: The single line
comment (by using //) and by multiple line command (by using /*….*/)
7) Return 0;
BEWARE
– The success of compilation does not assure in any case the good result of the execution. Errors
can still happen during the execution. This type of error is called runtime error and will be
treated further.
– C is case sensitive (main ≠ Main). All commands in C must be lowercase.
– C has a free-form line structure. Multiple statements can be on the same line. White space is
ignored. Statements can continue over many lines.
– In C program, the semicolon is a statement terminator. That is, each individual statement must
be ended with a semicolon. It indicates the end of one logical entity.
EXERCISES
1) Write a C program that print the following
*
***
*****
2) Write a C-program to print the following sentence :
3) Using an appropriate escape sequence, write a C program that display a sample calendar
month as the following:
-----------------------------------------------------------------
4) Write a C program that prints on the screen the words “Now is the time for all good men
to come to the aid of their country”
– all on one line;
– on three lines;
– on two lines inside a box composed of * characters.
I. KEYWORD
Keywords are reserved words which have standard, predefined meaning in C. They cannot be used
as program-defined identifiers.
II. Identifiers
Identifiers are the names given to various program elements such as constants, variables, function
names and arrays etc. Let us study first the rules to define names or identifiers.
For example, some valid identifiers are: nb1, cons, h456787, tax_rate, _XI, FOR…
DATA TYPE
In the C programming language, data types refer to an extensive system used for declaring
variables or functions of different types. The type of a variable determines how much space
it occupies in storage and how the bit pattern stored is interpreted.
The types in C can be classified as follows:
Basic Types: They are arithmetic types and consists of the two types: (a) integer types and (b) floatingpoint
1
types.
2 Enumerated types: They are again arithmetic types and they are used to define variables that can only be
assigned certain discrete integer values throughout the program.
3 The type void: The type specifier void indicates that no value is available.
4 Derived types: They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e)
Function types.
Integer Types
Following table gives you details about standard integer types with its storage sizes and
value ranges:
Type Storage size Value range
#include <stdio.h>
#include <limits.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
The header file float.h defines macros that allow you to use these values and other details about
the binary representation of real numbers in your programs. Following example will print storage
space taken by a float type and its range values:
#include <stdio.h>
#include <float.h>
int main()
{
printf("Storage size for float : %d \n", sizeof(float));
printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX );
printf("Precision value: %d\n", FLT_DIG );
return 0;
}
C Variables
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in C has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations that
can be applied to the variable.
Variable declaration
A variable declaration provides assurance to the compiler that there is one variable existing with
the given type and name so that compiler proceed for further compilation without needing
complete detail about the variable. A variable definition specifies a data type and contains a list
of one or more variables of that type as follows
The syntax for declaring variables is as follows:
data- type variable_list;
variable_list may consist of one or more identifier names separated by commas. Some valid declarations
are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; both declares and defines the variables i, j and k; which instructs the compiler to
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows:
1. lvalue: An expression that is an lvalue may appear as either the left-hand or right-hand side of
an assignment.
2. rvalue: An expression that is an rvalue may appear on the right- but not left-hand side of an
assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are
rvalues and so may not be assigned and cannot appear on the left-hand side.
Following is a valid statement: int g = 20; But following is not a valid statement and would generate
compile-time error: 10 = 20;
Defining Constants
There are two simple ways in C to define constants:
#include<stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
When the above code is compiled and executed, it produces the following result:
value of area : 50
#include<stdio.h>
int main()
{
const int LENGTH =10;
const int WIDTH =5;
const char NEWLINE ='\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return0;
}
When the above code is compiled and executed, it produces the following result: value of area : 50
Character constants
Character literals are enclosed in single quotes, e.g., 'x' and can be stored in a simple variable of char
type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').
There are certain characters in C when they are preceded by a backslash they will have special meaning
and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape
sequence codes:
\\ \ character \n Newline
\f Form feed
#include<stdio.h>
int main()
{
printf("Hello\tWorld\n\n");
return0;
}
When the above code is compiled and executed, it produces the following result:
Hello World
This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators
one by one.
I. Arithmetic Operators
Following table shows all the arithmetic operators supported by C language. Assume variable A
holds 15 and variable B holds 20, then:
Try the following example to understand all the arithmetic operators available in C programming
language:
#include<stdio.h>
main()
{
int a =21; int b=10; int c ;
c = a + b; printf("Line 1 - Value of c is %d\n", c );
c = a-b; printf("Line 2 - Value of c is %d\n", c );
c = a * b; printf("Line 3 - Value of c is %d\n", c );
c = a / b; printf("Line 4 - Value of c is %d\n", c );
c = a % b; printf("Line 5 - Value of c is %d\n", c );
c = a++; printf("Line 6 - Value of c is %d\n", c );
c = a--; printf("Line 7 - Value of c is %d\n", c );
return 0;
}
When you compile and execute the above program, it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Relational Operators
Following table shows all the relational operators supported by C language. Assume variable A
holds 10 and variable B holds 20, then:
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then:
Try the following example to understand all the logical operators available in C programming
language:
#include<stdio.h>
main()
{
int a =5;int b =20;int c ;
if( a && b )
{
printf("Line 1 - Condition is true\n");
}
if( a || b )
{
When you compile and execute the above program, it produces the following result:
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |, and ^
are as follows:
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011
The Bitwise operators supported by C language are listed in the following table. Assume variable
A holds 60 and variable B holds 13, then:
Binary AND Operator copies a bit to the result if it (A & B) will give 12, which is
&
exists in both operands. 0000 1100
Binary OR Operator copies a bit if it exists in either (A | B) will give 61, which is
|
operand. 0011 1101
Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49, which is
^
operand but not both. 0011 0001
Binary Ones Complement Operator is unary and has (~A ) will give -60, which is
~
the effect of 'flipping' bits. 1100 0011
Try the following example to understand all the bitwise operators available in C programming
language:
#include<stdio.h>
main()
{
unsignedint a =60;/* 60 = 0011 1100 */unsignedint b =13;/* 13 = 0000 1101 */int c =0;
c = a & b;/* 12 = 0000 1100 */ printf("Line 1 - Value of c is %d\n", c);
c = a | b;/* 61 = 0011 1101 */ printf("Line 2 - Value of c is %d\n", c );
c = a ^ b;/* 49 = 0011 0001 */ printf("Line 3 - Value of c is %d\n", c );
c =~a;/*-61 = 1100 0011 */ printf("Line 4 - Value of c is %d\n", c );
c = a <<2;/* 240 = 1111 0000 */ printf("Line 5 - Value of c is %d\n", c );
c = a >>2;/* 15 = 0000 1111 */
When you compile and execute the above program, it produces the following result:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Assignment Operators
Simple assignment operator, Assigns values from right side C = A + B will assign
=
operands to left side operand value of A + B into C
There are few other important operators including sizeof and ? : supported by C Language.
sizeof() Returns the size of an variable. sizeof(a), where a is integer, will return 4.
Returns the address of an &a; will give actual address of the variable.
&
variable.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Try the following example to understand the operator precedence available in C programming
language:
#include<stdio.h>
main()
{
int a =20;int b =10;int c =15;int
d =5;int e;
e =(a + b)* c / d;// ( 30 * 15 ) / 5 printf("Value of (a + b) * c / d is : %d\n", e );
e =((a + b)* c)/ d;// (30 * 15 ) / 5
printf("Value of ((a + b) * c) / d is : %d\n", e );
e =(a + b)*(c / d);// (30) * (15/5)
printf("Value of (a + b) * (c / d) is : %d\n", e );
e = a +(b * c)/ d;// 20 + (150/5)
printf("Value of a + (b * c) / d is : %d\n", e );
return0;
}
When you compile and execute the above program, it produces the following result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
scanf is a function in C which allows the programmer to accept input from a keyboard. It obtains
a value from the user
& is confusing in beginning – for now, just remember to include it with the variable name in scanf
statements.
When executing the program the user responds to the scanf statement by typing in a number, then
pressing the Enter (return) key
2) Formatted output — printf
printf(“The new value of b is %f\n”, b);
The arguments to scanf must be pointers (addresses), hence the need for the & character above.
The following table show what format specifies should be used with what data types:
%c character %u unsigned
%d decimal integer %i integer
%x hexadecimal integer %e or %f or %g floating point number
%o octal integer %s string pointer to char
%ld long integer %lf long double
NB: When reading integers using the “I” conversion character, the data entered may be
preceded by 0 or 0x to indicate that the data is in octal (base 8) or hexadecimal (base16).
3) Characters’ Input/Output
#include <stdio.h>
#include <conio.h>
int main()
{
char me[20];
printf("What is your name?");
scanf("%s",&me);
printf("Darn glad to meet you, %s!\n",me);
getch();
return(0);
}
int main()
{
int c;
c = getchar(); /* read a character and assign to c */
putchar(c); /* print c on the screen */
return 0;
}
getchar and putchar are used for the input and output of single characters respectively.
getchar() returns an int which is either EOF(indicating end-of-file, see later) or the next
character in the standard input stream
EXERCISES
1) Identify keywords and valid identifiers among the following:
3) Given a time in seconds (integer), print to the screen the corresponding time in hours,
minutes and seconds. The output will be formatted like: “XXXX seconds is equivalent to
XX hours, XX minutes and XX seconds”.
4) Write a C code that switches the values of two variables A and B and prints the result on
the screen. How many variables do you need?
5) Write a program that reads in an integer and prints out the given integer in decimal, octal
and hexadecimal formats
6) Write a program that reads in a temperature expressed in Celsius (Centigrade) and displays
the equivalent temperature in degrees Fahrenheit.
7) Write a program to read in a four letter word and print it out backwards.
8) Create a new program that prompts a user for numbers and determines total revenue using
the following formula: Total Revenue = Price * Quantity.
9) Build a new program that prompts a user for data and determines a commission using the
following formula: Commission = Rate * (Sales Price – Cost).
10) a) Given a = 5, b = 1, x = 10, and y = 5, create a program that outputs the result of the
formula f = (a b)(x y) using a single printf() function.
b) Create a program that uses the same formula above to output the result; this time,
however, prompt the user for the values a, b, x, and y. Use appropriate variable names and
naming conventions.
11) Create a program that prompts a user for her name. Store the user’s name using the scanf()
function and return a greeting back to the user using her name.
12) Write a program to read in a three digit number and produce output like
3 hundreds
4 tens
7 units
for an input of 347. There are two ways of doing this. Can you think of both of them? Which do
you think is the better?
Lesson notes on C/C++ programming. By: DZEUGANG Placide
Objectives
At the end of this lesson, student should be able to:
INTRODUCTION
A program is usually not limited to a linear sequence of instruction. In real life, a program usually
needs to change the sequence of execution according to some conditions. In C language, there are
many control structure that are use to handle conditions and the resultant decisions. This lesson
introduces if-else and switch construct.
Decision Making in C
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
C programming language provides following types of decision making statements.
I. The if statement
An if statement consists of a boolean expression followed by one or more statements
1) A simple if statement
Syntax
The syntax of an if statement in C programming language is:
if(boolean_expression)
{
statements
}/* statement(s) will execute if the boolean expression is true */
Lesson notes on C/C++ programming. By: DZEUGANG Placide
If the boolean expression evaluates to true, then the block of code inside the if statement will be
executed. If boolean expression evaluates to false, then the first set of code after the end of the if
statement (after the closing curly brace) will be executed.
Flow Diagram
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null,
then it is assumed as false value.
Example
#include<stdio.h>
int main ()
{
int a =10; /* local variable definition */
When the above code is compiled and executed, it produces the following result:
Syntax
The syntax of an if...else statement in C programming language is:
if(boolean_expression)
statements_if_expression_true;
else
statements_if_expression_false;
If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else
block of code will be executed.
Flow Diagram
Example
#include<stdio.h>
int main ()
{
int a =100; /* local variable definition */
if( a <20) /* check the boolean condition */
{
printf("a is less than 20\n");/* if condition is true then print the following */
Lesson notes on C/C++ programming. By: DZEUGANG Placide
}
else
{
printf("a is not less than 20\n");/* if condition is false then print the following */
}
printf("value of a is : %d\n", a);
return0;
}
When the above code is compiled and executed, it produces the following result:
Marks Grade
>=75 A
<25 F
In this case multiple conditions are to be checked. Marks obtained by a student can only be one of
the ranges. Therefore, if-else-if can be used to implement the following program.
/* Distribution of grade */
main()
float marks;
scanf(“%f”,&marks);
Lesson notes on C/C++ programming. By: DZEUGANG Placide
return 0;
Syntax
The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if...else in the similar way as you have nested if statement.
Example
#include<stdio.h>
int main ()
{
int a =100;int b =200; /* local variable definition */
if( a ==100) /* check the boolean condition */
{
if( b ==200) /* if condition is true then check the following */
{
printf("Value of a is 100 and b is 200\n");
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return0;
}
When the above code is compiled and executed, it produces the following result:
Syntax
The syntax for a switch statement in C programming language is as follows:
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
Flow Diagram
Lesson notes on C/C++ programming. By: DZEUGANG Placide
Example
#include<stdio.h>
int main ()
{
char grade ='B'; /* local variable definition */
switch(grade)
{
case'A':
printf("Excellent!\n");
break;
case'B':
case'C':
printf("Well done\n");
break;
case'D':
printf("You passed\n");
break;
case'F':
printf("Better try again\n");
break;
default:
printf("Invalid grade\n");
}
printf("Your grade is %c\n", grade );
return0;
}
When the above code is compiled and executed, it produces the following result:
Well done
Your grade is B
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated
and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value
becomes the value of the expression.
EXERCISES
Lesson notes on C/C++ programming. By: DZEUGANG Placide
7) Write a C code that returns the sign of a multiplication of A and B without doing the
multiplication.
8) Write a program which consists to say whether a student has passed a test or he has failed,
being given an average. The student has passed if the average is greater than 12.00
#include <stdio.h>
int main()
int i, j;
i = j = 2;
if (i == 1)
if (j == 2)
printf("%d\n", i = i + j);
else
printf("%d\n", i = i - j);
printf("\n%d", i);
return 0;
10) A car increases it velocity from u ms-1 to v ms-1 within t seconds. Write a program to
calculate the acceleration.
Lesson notes on C/C++ programming. By: DZEUGANG Placide
11) Write a program that solve an equation of second degree (in the form ax2 + bx + c = 0).
The program receive the three coefficients a, b and c. (use the function sqrt() in the library
math.h to calculate the square root of a number)
a) Display either the real solution(s) or a message when the equation has no solution in
the set ℝ.
b) When there is not a real solution, display the complex solutions in form of x ± yi
12) A year is a leap year if it is divisible by 4 unless it is a century year (one that ends in 00) in
which case it has to be divisible by 400. Write a program to read in a year and report
whether it is a leap year or not.
15) Develop a simple calculator to accept two floating point numbers from the keyboard. Then
display a menu to a user and let him/her select a mathematical operation to be performed
on those two numbers. Then display the answer. A sample run of your program should be
similar to the following:
Lesson notes on C/C++ programming. By: DZEUGANG Placide
Challenges
16) Build a number guessing game that uses input validation (isdigit() function) to verify that
the user has entered a digit and not a non-digit (letter). Store a random number between 1
and 10 into a variable each time the program is run. Prompt the user to guess a number
between 1 and 10 and alert the user if he was correct or not.
17) Build a Fortune Cookie program that uses either the Chinese Zodiac or astrological signs
to generate a fortune, a prediction, or a horoscope based on the user’s input. More
specifically, the user may need to input her year of birth, month of birth, and day of birth
depending on zodiac or astrological techniques used. With this information, generate a
custom message or fortune. You can use the Internet to find more information on the
Chinese Zodiac or astrology.
18) Create a dice game that uses two six-sided dice. Each time the program runs, use random
numbers to assign values to each die variable. Output a “player wins” message to the user
if the sum of the two dice is 7 or 11. Otherwise output the sum of the two dice and thank
te user for playing.
CONTROL STRUCTURES (LOOPS)
There may be a situation, when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
A loop statement allows us to execute a statement or group of statements multiple times and following
is the general form of a loop statement in most of the programming languages
C programming language provides the following types of loops to handle looping requirements.
for loop in C
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is:
int counter;
for(counter=1;counter<=0;counter++)
return 0;
It is also possible to decrement the counter depending on the requirement, but one has to use
suitable control expression and an initial value.
Exercise:
A program consist to calculate the sum of all the even numbers up to 100
Modify the program above so that it computes the sum of all the odd number up to 100.
while loop in C
A while loop statement in C programming language repeatedly executes a target statement as long as a
given condition is true.
Syntax
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Programmer is responsible for initialization and incrementation. At some point in the body of the
loop, the control expression must be altered in order to allow the loop to finish. Otherwise:
infinite loop.
A for loop can be transformed into a while loop using the following rule:
{ while(expr2)
statement {
} statement
expr3
}
The program above consisting to calculate the sum of all the even numbers up to 100 can be
rewritten using the while loop as follow:
#include<stdio.h>
main()
int i, sum;
sum = 0;
i = 0;
sum += i;
i += 2;
return 0;
do...while loop in C
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C
programming language checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}
while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.
Flow Diagram
Example
#include<stdio.h>
int main ()
{
/* local variable definition */int a
=10;
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 11
value of a: 12 value of a: 13
value of a: 14 value of a: 15
value of a: 16 value of a: 17
value of a: 18 value of a: 19
A common use of the do while statement is input error checking. A simple form is shown here
do {
scanf("%d",&n);
} while (n<=0);
The user will remain in this loop continually being prompted for and entering integers until a
positive one is entered. A sample session using this loop looks like this
nested loops in C
C programming language allows to use one loop inside another loop. Following section shows few
examples to illustrate the concept.
Syntax
The syntax for a nested for loop statement in C is The syntax for a nested while loop statement in C
as follows: programming language is as follows:
The syntax for a nested do...while loop statement in C programming language is as follows:
do{
statement(s);do{
statement(s);}while(
condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For
example, a for loop can be inside a while loop or vice versa.
Example
#include<stdio.h> The output of the program is as follow:
main()
int i,j,n;
scanf("%d", &n);
for(i=1;i<=n;i++)
for(j=1;j<=i;j++)
printf("*");
printf("\n");
return 0:
break statement in C
The break statement in C programming language has the following two usages:
1. When the break statement is encountered inside a loop, the loop is immediately terminated and program
control resumes at the next statement following the loop.
2. It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the
execution of the innermost loop and start executing the next line of code after the block.
Flow Diagram
Example
#include<stdio.h> This is the output of the program:
main()
int n;
for(n=10;n>0;n--)
if(n==5)
printf("\nCountdown aborted");
break;
return 0;
continue statement in C
The continue statement in C programming language works somewhat
like the break statement. Instead of forcing termination, however, continue forces the next iteration of
the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes the program control passes to
the conditional tests.
Flow Diagram
Example
#include<stdio.h>
int main ()
{
int a =10;
do
{
if( a ==15)
{
a = a +1;
continue; /* skip the iteration */
}
printf("value of a: %d\n", a);
a++;
}while( a <20);
return0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 11
value of a: 12 value of a: 13
value of a: 14 value of a: 16
value of a: 17 value of a: 18
value of a: 19
goto statement in C
A goto statement in C programming language provides an unconditional jump from the goto to a labeled
statement in the same function.
NOTE: Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. Any program that uses a goto can be rewritten so that it doesn't need the goto.
Syntax
The syntax for a goto statement in C is as follows:
goto label;
..
. label: statement;
Here label can be any plain text except C keyword and it can be set anywhere in the C program above or
below to goto statement.
Flow Diagram
Example
#include<stdio.h>
int main ()
{
int a =10;
LOOP:
do /* do loop execution */
{
if( a ==15) /* skip the iteration */
{
a = a +1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a <20);
return0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 11
value of a: 12 value of a: 13
value of a: 14 value of a: 16
value of a: 17 value of a: 18
value of a: 19
Int main ()
for(;;)
return0;
When the conditional expression is absent, it is assumed to be true. You may have an initialization and
increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite
loop.
EXERCISES
19) Write a program to compute the sum of all the integers from 1 to 100.
20) Write the program to calculate the factorial of any given factorial number.
21) Write the program to compute the sum of all integers between any given two numbers.
23) Create a counting program that counts backward from 100 to 1in decrements of 10.
24) Create a counting program that prompts the user for three inputs (shown next) that
determine how and what to count. Store the user’s answers in variables. Use the acquired
data to build your counting program with a for loop and display the results to the user.
• Beginning number to start counting from
• Ending number to stop counting at
• Increment number
25) Write a C code that permits the user to specify a number of lines or branches and then
prints on
a) the shell a triangular pyramid consisting of stars (picture 1 below).
b) A picture of a Christmas tree consisting of star (figure 2 below).
Hints: all characters are printed separately and both the number of stars per line and
the number of spaces per line must be calculated. The output will look like:
8) Using a loop, ask the user to enter positive integer numbers. The program will output the
number of values entered, the minimum value, the maximum value and the average of all
numbers. The code will exit once a negative integer is entered.
9) Write a program where the user supplies integer values between 1 and 9 and the program
returns the sum, average and RMS of the values. The program will exit when 0 is entered.
Values outside of the bounds will be discarded.
10) Write a program that returns the number of years until a father will have an age double of its
son’s age.
11) Write the C code that computes xn using the three loop functions (for, while and do-while). We
will consider n to be an integer.
12) Write a program that tests if a positive integer is a prime number using a straightforward
approach. You will assume that your number is smaller than 1000.
13) Write a C-program to display the message “God is love!” 100000 times. The program should
allow users to terminate the execution at any time by pressing any key before it display all the
100000 messages. The C function kbhit() can be used to check for a keystroke. If a key has
been pressed, it returns the value “1” otherwise it returns “0”. The kbhit() function is define
in the header file conio.h
14) a) Write a program to prompt the user for an integer and calculate the sum of all the integers
up to and including the input value. Print out the result.
b) Modify the previous program to use floating point arithmetic to add up the reciprocals of
all the integers up to and including the input value.
c) Further modify the previous program to print out a list of reciprocal sums for every integer
up to and including the input value.
I.e. print out the sum of the reciprocals of the integers up to and including 1, up to and
including 2, up to and including 3 etc., etc.
15) A program consists to the following game: The machine guesses a number between a given
intervals and ask to the student to find it. The max, the min and the number of tries should be
defined as constant values (use #define). For any number guess by the user, the machine should
see whether the number is bigger or smaller than the searched number. The program stop when
the user actually guess the right number, in which case the sentence “Bravo you win in x tries” (x
to be given) is printed, or the maximum number of tries are reached, in which case the sentence
“Sorry exceeded number of tries, you failed” is printed. The output will look like
(Use the rand() function in the library “stdlib.h” to generate a random number.)
C Functions
INTRODUCTION
C and C++ come with a large library of useful functions (the standard ANSI C library plus several C++
classes), but real programming pleasure comes with writing your own functions. This chapter examines
how to define functions, convey information to them, and retrieve information from them. After
reviewing how functions work, this chapter concentrates on how to use functions this chapter touches on
recursion to functions. If you’ve paid your C dues, you’ll find much of this chapter familiar. But don’t be
lulled into a false sense of expertise. Meanwhile, let’s attend to the fundamentals.
I. INTRODUCTIVE EXAMPLE
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
int main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf("sum=%d",sum);
return 0;
}
int add(int a,int b) //function declarator
{
/* Start of function definition. */
int add;
add=a+b;
return add; //return statement of function
/* End of function definition. */
}
We have already been exposed to functions. The main body of a C program, identified by the
keyword main, and enclosed by left and right braces is a function. It is called by the operating
system when the program is loaded, and when terminated, returns to the operating system. We
have also seen examples of library functions which can be used for I/O (stdio.h), like printf and
scanf, mathematical tasks (math.h), and character/string handling (string.h).
– Don’t have to repeat the same block of code many times in your code. Make that code
block a function and call it when needed.
– Function portability: useful functions can be used in a number of programs.
– Supports the top-down technique for devising a program algorithm. Make an outline and
hierarchy of the steps needed to solve your problem and create a function for each step.
– Easy to debug. Get one function working well then move on to the others.
– Easy to modify and expand. Just add more functions to extend program capability
– For a large programming project, you will code only a small fraction of the program.
– Make program self-documenting and readable.
In order to use functions, the programmer must do three things: Declare the function, Define the
function, Use the function in the main code. In the following pages, we examine each of these
steps in detail.
Every function in C programming should be declared before they are used. These type of
declaration are also called function prototype. Function prototype tells the compiler about a
function name and how to call the function. The actual body of the function can be defined
separately..
For the above defined function max(), following is the function declaration:
The function definition is the C code that implements what the function does. Function definitions
have the following syntax
where the return_type in the function header tells the type of the value returned by the
function (default is int)
where the data type variable name list tells what arguments the function needs when it is
called (and what their types are)
where local declarations in the function body are local constants and variables the function
needs for its calculations.
Some functions will not actually return a value or need any arguments. For these functions the
keyword void is used. A function that does not return any value is also called a procedure. Here is
an example:
printf("*************************************************\n");
The purpose of this function is just to display a menu on the screen, then it doesn’t need any
parameter and doesn’t return any value to the main. Here:
A function whose return type is different to void must contain the keyword return enabling to
return a value to the calling program.
When a return is encountered the following events occur: execution of the function is terminated
and control is passed back to the calling program, and the function call evaluates to the value of
the return expression.
The data type of the return expression must match that of the declared return_type for the function.
double absolute(double x)
{
if (x>=0.0)
return x;
V. CALLING FUNCTIONS
To invoke a function, just type its name in your program and be sure to supply arguments (if
necessary). A statement using our factorial program would look like
sum += power(x,i);
write_header(void)
Some points to keep in mind when calling functions (your own or library’s):
– The number of arguments in the function call must match the number of arguments in the
function definition.
– The type of the arguments in the function call must match the type of the arguments in the
function definition.
– The actual arguments in the function call are matched up in-order with the dummy
arguments in the function definition.
– The actual arguments are passed by-value to the function. The dummy arguments in the
function are initialized with the present values of the actual arguments. Any changes made
to the dummy argument in the function will NOTaffect the actual argument in the main
program.
VI. RECURSION
Recursion is the process in which a function repeatedly calls itself to perform calculations. Typical
applications are games and sorting trees and lists. Recursive algorithms are not mandatory,
usually an iterative approach can be found.
int factorial(int n)
{
int result;
if (n<=1)
result=1;
else
result=n*factorial(n-1);
The formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
By default, C programming language uses call by value method to pass arguments. In general, this
means that code within a function cannot alter the arguments used to call the function. Consider the
function swap() definition as follows.
return;
}
Now, let us call the function swap() by passing actual values as in the following example:
#include<stdio.h>
int main ()
{
/* local variable definition */int
a =100;int b =200;
return0;
}
Let us put above code in a single C file, compile and execute it, it will produce the following result:
Which shows that there is no change in the values though they had been changed inside the function.
To pass the value by reference, argument pointers are passed to the functions just like any other value.
So accordingly you need to declare the function parameters as pointer types as in the following function
swap(), which exchanges the values of the two integer variables pointed to by its arguments.
return;
}
Let us call the function swap() by passing values by reference as in the following example:
#include<stdio.h>
return0;
}
Let us put above code in a single C file, compile and execute it, it will produce the following result:
Which shows that there is no change in the values though they had been changed inside the function.
EXERCISES
3- Write a function which take a real number and return its absolute value. Write a program which
use the function
5- Write a C function facto that computes the factorial of a number n (integer). The factorial
function is a typical recursive problem. Rewrite the equation defining the factorial function in
a recursive form. Write the recursive version of the code and call the function facto_rec.
6- Write the function called pow to calculate xn for any real number x and integer n. Rewrite it in
its recursive form and write the associate C function that you will call pow_rec.
𝒙𝒏
7- The Taylor expansion of the exponential function is given by 𝒆𝒙 = ∑∞
𝒏=𝟎 𝒏! . Using the
previous exercises (function facto and pow), write a C functions that calculates the exponential
for integer values of x. Compare its results to the results of the C exponential function defined
in <math.h>.
8- Write a program that repeatedly asks the user to enter pairs of numbers until at least one of the
pair is 0. For each pair, the program should use a function to calculate the harmonic mean of
the numbers. The function should return the answer to main(), which should report the result.
The harmonic mean of the numbers is the inverse of the average of the inverses and can be
calculated as follows: harmonic mean of x and y = 2.0 × x × y / (x + y)
9- Write a function that returns 1 if an integer number is prime, 0 otherwise. Use that function to
write a C program which display the list of prime number below a given integer n.
11- Write a function that takes three arguments: the name of an int array, the array size, and an
int value. Have the function set each element of the array to the int value.
12- Write a program that asks the user to enter up to 10 golf scores, which are to be stored in an
array. You should provide a means for the user to terminate input prior to entering 10 scores.
The program should display all the scores on one line and report the average score. Handle
input, display, and the average calculation with three separate array-processing functions.
13- Write a function that takes three arguments: a pointer to the first element of a range in an array,
a pointer to the element following the end of a range in an array, and an int value. Have the
function set each element of the array to the int value.
14- Write a function that takes a double array name and an array size as arguments and returns the
largest value in that array. Note that this function shouldn’t alter the contents of the array.
a. Write a function that passes a box structure by value and that displays the value of each
member.
b. Write a function that passes the address of a box structure and that sets the volume member to
the product of the other three dimensions.
Write a simple program that uses these two functions.
VII. ARRAY
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one
array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows:
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero
and type can be any valid C data type. For example, to declare a 10element array called balance of type
double, use this statement:
double balance[10];
Now balance is a variable array which is sufficient to hold up-to 10 double numbers.
The number of values between braces { } can not be larger than the number of elements that we declare
for the array between square brackets [ ]. Following is an example to assign a single element of the
array:
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore,
if you write:
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will
be 5th i.e. last element because all arrays have 0 as the index of their first element which is also called
base index. Following is the pictorial representation of the same array we discussed above:
The above statement will take 10th element from the array and assign the value to salary variable.
Following is an example which will use all the above mentioned three concepts viz. declaration,
assignment and accessing arrays:
Multi-dimensional Arrays
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array:
int threedim[5][10][4];
Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-dimensional array. A twodimensional array
is, in essence, a list of one-dimensional arrays. To declare a twodimensional integer array of size x, y you
would write something as follows:
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two dimensional
array can be think as a table which will have x number of rows and y number of columns. A 2-
dimentional array b, which contains three rows and four columns can be shown as below:
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */ };
The nested braces, which indicate the intended row, are optional. The following initialization is
equivalent to previous example:
The above statement will take 4th element from the 3rd row of the array. You can verify it in the above
diagram. Let us check below program where we have used nested loop to handle a two dimensional
array:
#include <stdio.h>
int main ()
{
VIII. STRING
The following declaration and initialization create a string consisting of the word "Hello". To hold the
null character at the end of the array, the size of the character array containing the string is one more
than the number of characters in the word "Hello".
If you follow the rule of array initialization then you can write the above statement as follows:
#include <stdio.h>
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
2) Initializing Strings
Initializing a string can be done in three ways:
a. at declaration,
b. by reading in a value for the string, and
c. by using the strcpy function. Direct initialization using the = operator is invalid. The
following code would produce an error:
char name[34];
name = "Erickson"; /* ILLEGAL */
To read in a value for a string use the %s format identifier: scanf("%s",name);
Note that the address operator &is not needed for inputting a string variable (explained later).
The end-of-string character will automatically be appended during the input process.
3) Copying Strings
The strcpy function is one of a set of built-in string handling functions available for the C
programmer to use. To use these functions be sure to include the string.h header file at the
beginning of your program. The syntax of strcpy is
strcpy(string1,string2);
When this function executes, string2 is copied into string1at the beginning of string1. The previous
contents of string1 are overwritten. In the following code, strcpy is used for string initialization:
#include <string.h>
main ()
{
char job[50];
strcpy(job,"Professor");
printf("You are a %s \n",job);
return 0;
… … …
#include <stdio.h>
#include <string.h>
int main ()
{
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );
/* concatenates str1 and str2 */
strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf("strlen(str1) : %d\n", len );
return 0;
}
Function Operation
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 character
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
Example: The following program give an overview on the use of some of those functions
#include<ctype.h>
#include<stdio.h>
#include<stdlib.h>
main()
IX. POINTER
Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic
memory allocation, cannot be performed without using pointers. So it becomes necessary to learn
pointers to become a perfect C programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its address defined
which can be accessed using ampersand (&) operator, which denotes an address in memory.
Consider the following example, which will print the address of the variables defined:
#include <stdio.h>
int main ()
{
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the
pointer variable. The asterisk * you used to declare a pointer is the same asterisk that you use for
multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer.
Following are the valid pointer declaration:
#include <stdio.h>
main()
{
int a=1,b=78,*ip;
ip=&a;
b=*ip; /* equivalent to b=a */
printf("The value of b is %d\n",b);
return 0;
}
Note that b ends up with the value of a but it is done indirectly; by using a pointer to a
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
return 0;
}
When the above code is compiled and executed, it produces result something as follows:
NULL Pointers in C
It is always a good practice to assign a NULL value to a pointer variable in case you do not have exact
address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is
called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the
following program:
#include <stdio.h>
int main () {
int *ptr = NULL;
When the above code is compiled and executed, it produces the following result:
On most of the operating systems, programs are not permitted to access memory at address 0 because
that memory is reserved by the operating system. However, the memory address 0 has special
significance; it signals that the pointer is not intended to point to an accessible memory location. But by
convention, if a pointer contains the null (zero) value, it is assumed to point to nothing.
“Call-by-Reference” Arguments
We learned earlier that if a variable in the main program is used as an actual argument in a
function call, its value won’t be changed no matter what is done to the corresponding dummy
argument in the function.
What if we would like the function to change the main variable’s contents?
The classic example of “call-by-reference” is a swap function designed to exchange the values of
two variables in the main program. Here is a swapping program
#include <stdio.h>
void swap1(int p,int q);
void swap2(int *p,int *q);
main()
{
int i=3,j=9;
printf("before the 2 swaps, i=%d
j=%d\n",i,j);
swap1(i,j);
printf("\nAfter swap1, i=%d j=%d\n",i,j);
swap2(&i,&j);
printf("\nAfter swap2, i=%d j=%d\n",i,j);
We have actually seen this fact before: when using scanf to input a character string variable
called name the statement looked like
Illustration
a[5]=56;
*(a+5)=56;
Here is the layout in memory:
a 133268 a[0]
a+1 133272 a[1]
a+2 133276 a[2]
a+3 133280 a[3]
- Other way
int a[100],i,*p,sum=0;
for(i=0; i<100; ++i)
sum += *(a+i);
- Another way
int a[100],i,*p,sum=0;
for(p=a; p<&a[100]; ++p)
sum += *p;
EXERCISES
1- Write a program which reads in 10 numbers and then prints them out in the reverse order to
that which they were entered in.
2- Write code that reads a list of numbers from the keyboard, store the numbers in an array, and
then:
a) print out the array in reverse order
b) calculate the average of the numbers
c) print the index of the numbers that are below the average.
3- Given a two-dimensional square array of integers, with size N * N, called numTable, write
code to:
a) Initialize the array by command-line inputs
b) Calculate the statistics of the average, the minimum, and the maximum of the array
c) Calculate the sum on both diagonals.
4- Consider an array X of length 25. Use the function rand() to initialized randomly the array.
Write a program that returns the position and value of the minimum.
6- Consider 2 three-dimensional vectors X and Y whose components are specified by the user
and stored in 1D arrays. Write the C code that calculates if the two vectors are orthogonal.
9- Build a program that uses a single-dimension array to store 10 numbers input by a user. After
inputting the numbers, the user should see a menu with two options to sort and print the 10
numbers in ascending or descending order.
12- Write a program that will output the characters of a string backwards. For example, given the
string “computer”, the program will produce “retupmoc”.
13- Consider X and Y, two sorted arrays of integers. Write a C code that concatenates the two
tables into one table Z (sorted) which contains the elements of X and Y.
14- Write a small C program that prints on the screen in uppercase a text supplied by the user. The
string will not be more than 80 characters in size.
15- Given a string as input, write a function that counts the numbers, the lower case, upper case
and special characters.
16- Using the integer representation of a character, write a function that replaces all the lower case
characters in a string by upper case characters.
18- Define two integer arrays, each 10 elements long, called array1 and array2. Using a loop, put
some kind of nonsense data in each and add them term for term into another 10 element array
named arrays. Finally, print all results in a table with an index number, for example
1- 2 + 10 = 12
2- 4 + 20 = 24
3- 6 + 30 = 36 etc.
20- Create a program that allows a user to select one of the following four menu options:
• Enter New Integer Value
• Print Pointer Address
• Print Integer Address
• Print Integer Value
For this program you will need to create two variables: one integer data type and one pointer.
Using indirection, assign any new integer value entered by the user through an appropriate
pointer.
21- Build a program that uses an array of strings to store the following names: “Florida”,
“Oregon”; “California”, “Georgia” Using the preceding array of strings, write your own
sort() function to display each state’s name in alphabetical order using the strcmp() function.
22- Define a character array and use strcpy to copy a string into it. Print the string out by using a
loop with a pointer to print out one character at a time. Initialize the pointer to the first
element and use the double plus sign to increment the pointer. Use a separate integer variable
to count the characters to print. Modify the program to print out the string backwards by
pointing to the end and using a decrementing pointer.
I. STRUCTURE
• Author
• Subject
• Book ID
To define a structure, you must use the struct statement. The struct statement defines a new data type,
with more than one member for your program. The format of the struct statement is this:
The structure tag is optional and each member definition is a normal variable definition, such as int i; or
float f; or any other valid variable definition. At the end of the structure's definition, before the final
semicolon, you can specify one or more structure variables but it is optional. Here is the way you would
declare the Book structure:
struct Books
{
char title[50]; char
author[50]; char subject[100];
int book_id;
} book;
The above is a declaration of a data type called student. It is not a variable declaration, but a type
declaration.
The keyword struct declares a structure to hold the details of four data fields,
You can declare a structure type and variables simultaneously. Consider the following declaration:
Struct book_record
{
char title[20];
char author[15];
int nb;
float price;
} book1, book2, book3;
The above declaration will create a struct book_record called book1 with a title “Quick
Mastery”, the author “Bennett CHAH”, 145 exemplars at 3500 frs.
I.4- Example
#include<stdio.h>
#include<stdlib.h>
main()
struct book_record
{
char title[20];
char author[15];
int nb;
float price;
};
struct book_record
{
main()
{
int i,n;
printf("\nEnter the number of book to record: ");
scanf("%d",&n);
struct book_record library[100];
for (i=0;i<n;i++)
{
library[i]=book_func();
}
printbook(library[i],n);
system("pause");
}
II- ENUMERATION
enum data types are data items whose values may be any member of a symbolically declared set
of values. A typical declaration would be.
enum days {Mon, Tues, Weds, Thurs, Fri, Sat, Sun};
III- UNION
Unions and Structures are identical in all ways, except for one very important aspect. Only one
element in the union may have a value set at any given time. Everything we have shown you for
structures will work for unions, except for setting more than one of its members at a time. For
example, the following code declares a union data type called intfloat and a union variable called
proteus:
union intfloat
{
floatf;
inti;
};
union intfloat proteus;
Once a union variable has been declared, the amount of memory reserved is just enough to be able
to represent the largest member. (Unlike a structure where memory is reserved for all members).
After Statement 1, data stored in proteus is an integer the float member is full of junk.
After Statement 2, the data stored in proteus is a float, and the integer value is meaningless
IV- TYPEDEF
It is possible to create new names for existing types with typedef . This is frequently used to give
shorter or less complicated names for types, making programming safer and hopefully easier.
The use of typedef is a simple macro-like facility for declaring new names for data types,
including user-defined data types. Typical examples are shown below :-
typedef long BIGINT;
typedef double REAL;
typedef struct point
{
double x;
double y;
} POINT;
Given the above declarations, it would be possible to write the following declarations:
POINT a,b,c;
REAL a1,a2;
V- FILES
The C programmer can also read data directly from files and write directly to files. To work with
files, the following steps must be taken:
FILE *fp;
fp = fopen(“filename”, “mode”);
“r+” the existing file is opened to the beginning for both reading and writing.
“w+” same as w except both for reading and writing.
“a+” same as a except both for reading and writing.
The following useful table lists the different actions and requirements of the different modes for
opening a file:
Opening a file for reading requires that the file already exist. If it does not exist, the file pointer
will be set to NULL and can be checked by the program.
fscanf(fp,"%f %d",&x,&m);
When a file is opened for writing, it will be created if it does not already exist and it will be reset
if it does, resulting in the deletion of any data already there. Using the w indicates that the file is
assumed to be a text file.
The Standard I/O Library provides similar routines for file I/O to those used for standard I/O.
The routine getc(fp) is similar to getchar() and putc(c,fp) is similar to putchar(c).
Thus the statement c = getc(fp); reads the next character from the file referenced by fp and
the statement putc(c,fp); writes the character c into file referenced by fp.
Another useful function for file I/O is feof() which tests for the end-of-file condition. feof takes
one argument -- the FILE pointer -- and returns a nonzero integer value (TRUE) if an attempt has
been made to read past the end of a file. It returns zero (FALSE) otherwise. A sample use:
EXERCISES
Write a main program to use these functions. A menu should be displayed to enable the user choosing
the operation he wants to perform
27- Write a simple database program that will store students’ information such as name, age, mark and
grade. The following instructions should be followed:
- An array of structure should be used to store information of a maximum of 20 students
- The number of students to record and the information should be entered by the user
- The grade should be assigned by a function according to the following table
mark grade
>= 80 A
<80 and >=60 B
<60 and >=40 C
<40 F
The write codes to perform the following
a) Calculate the mark average of all the student
b) Determine the first and the last student
c) Display the students who have passed knowing that a student has passed if he has at least 60/100
d) Given a student name display his details if the name exist in the database
28- Let’s consider the following code fragment. It show how a program might check if a file could be
opened appropriately. The function exit() is a special function which terminates your program
immediately.
fp = fopen (filename, “r”) ;
if ( fp == NULL)
{
printf(“Cannot open %s for reading \n”, filename );
exit(1) ; /*Terminate program: Commit suicide !!*/
}
a) Modify the code so that the a valid name of file should be entered before the execution of
the program continue
b) Modify the above code fragment to allow the user 3 chances to enter a valid filename. If
a valid file name is not entered after 3 chances, terminate the program.
29- Write a program to count the number of lines and characters in a file.
Note: Each line of input from a file or keyboard will be terminated by the newline character
‘\n’. Thus by counting newlines we know how many lines there are in our input.
31- Write a file copy program which copies the file “prog.c” to “prog.old”
Outline solution:
The step: “Read characters .... and write ..” may be refined to:
read character from prog.c
while not end of file do
begin
write character to prog.old
read next character from prog.c
end
32- The following simple structure declarations might be found in a graphics environment.
struct point
{
double x;
double y;
34- By using the structure point defined in exercise 4, consider the following structure
struct line
{
struct point start;
struct point end;
};
Using the structure above, write a code to determine if to lines are
a) Parallel
b) Perpendicular
35- Redo exercise 5 using a file to store the database. A menu should be prompted to the user to
choose the operation to do
a) Display the detail of the database
b) Add a record to the database
c) Give the number of records of the database
d) Calculate the mark average of all the student