Anda di halaman 1dari 7

ELE5PRA Laboratory 1: Introduction to C programming

The   aim   of   this   lab   is   to   introduce   you   to   the   C   programming   language   and   to   develop   your 
programming skills. At the end of this lab, you should:
1. Become familiar with the C syntax and develop basic programming skills  such as: data 
types, flow of control, loops, printf function and scanf function.
2. Familiarize your self with Cygwin and the GNU C compiler

Compiling and Running C Code
C was originally written to implement the Unix operating system in a portable form. For this reason 
we will be using Cygwin, a Linux terminal emulator for windows to compile and execute our code. 
Follow the following instruction to create, compile and run your first C program:
 
Create the following folder structure on your H:\ drive:
H:\ELE5PRA\clab1\

Navigate to clab1 folder, create a new file and rename it to: 
hello.c

Open hello.c with any text editor and type in the following code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main()
{
printf("Hello World!\n");
return 1;
}

Save hello.c and open up Cygwin. In Cygwin, navigate to H:\ELE5PRA\clab1\ using the following 
commands:
cd .. to move up a directory 
cd dir_name to move into a directory called dir_name
ls to list the files and folders in your current directory

So, to navigate to your working directory type in the following command:
cd  H:\ELE5PRA\clab1

To compile your code, simply type in:
gcc   hello.c   ­o   hello.exe

This command will compile the program hello.c and create an executable file called hello.exe

To execute your program type:
./hello.exe
Make sure that the program compiles and runs. If not, read your compiler errors then try to fix the 
faults by editing your code. Good luck!  

Variables and Data Types
Compiler languages require us to make a list of names and types of all variables which are going to 
be used in a program and provide information about where they are going to be used. This is called 
declaring variables. It serves two purposes: firstly, it provides the compiler with a definitive list of 
the variables, enabling it to cross check for errors, and secondly, it informs the compiler how much 
space must be reserved for each variable when the program is run.

In a broad sense, a data type defines a set of values and the allowable operations on those values. 
Assigning a data type to a variable in C, is in a way, equivalent to mathematically defining a set of  
numbers that a variable may take. For example, we could say:   x  Z , which defines  x  as an 
integer value (..., ­3, ­2, ­1, 0, 1, 2, 3, ...). In C we could say: int x;, which again defines  x  as an 
integer, however, in this case x can only represent a limited rang of integers as values are represented 
by a finite number of bits. The C language supports four numerical data types: char, int, float and 
double, which define 'sets' of integers and real numbers of varying range and/or precision (see the 
following table for further details). 
The C language also allows us to 'modify' the range of the standard data types by specifying a list of 
meaningfully modifiers. The short and long modifier may allow shorter or longer memory blocks 
to be allocated to the variable, allowing the variable to represent a smaller/larger range of signed or 
unsigned numbers. The signed and unsigned modifiers specifies if one of the bits in the memory 
allocated to the variable will be used as a sign bit. If the sign modifiers  are not specified the  
compiler will assume a signed modifier. 
The syntax for declaring variables is: <modifiers> <type> <name>.

The printf() function
The print­formatted function (printf) is a versatile function for printing text. It is provided by the  
standard input/output library (stdio.h). The simplest way to use printf is to print out a literal string:

printf("..Some character string..");

To print variables, we can use a 'control sequence' inside the quotes and list the variables after the 
string. These values will be inserted into the string instead of the control sequence. For example, to 
print out an integer, the control sequence %d is used:

int num=100;
printf("number = %d", num);

In this example the value of num will be printed instead of the place holder '%d'. The 'd' specifies 
that we wish to display the number as a decimal integer.
Printf supports the following control sequence characters.

Character Description
%d signed decimal integer
%u unsigned decimal integer
%x hexadecimal integer
%o octal integer
%s string
%c single character
%f fixed decimal floating point
%e scientific notation floating point 
%g use f or e, whichever is shorter 

Flow of Control
Statements in a program are normally executed in a sequence. However, most programs require 
alteration of the normal sequential flow of control. In this section we will focus on methods to 
control the flow of a program using various conditional statements. In the English language we may  
use words such as if, else, in case and while to define alternative action to be taken depending on a  
condition or a logical expression. For example we may say:  if  raining, stay home and watch TV, 
otherwise walk the dog. In this example, the logical expression is the state of the rain and we will  
take alternative action if rain is true or false.

if and if­else statement
In C the if and if­else statements provide alternative action to be taken depending on the value of a 
logical expression. The general format of an if statement is:

if(expression_1) if(expression_1) if(expression_1)


{ { {
statement_1; statement_1; statement_1;
} } }
else else if(expression_2)
{ {
statement_2; statement_2;
} }
else if(expression_3)
...
else
{
statement_n;
}

An if statement allows a statement to be executed provided that the logical expression preceding the 
statement is true. A program will sequentially test the logical expressions of a chain of if statements 
until it locates one that is true. If none are found to be true the program will execute the else clause, 
if it exists. In C, any non­zero value is considered to represent true and any zero value is considered 
to represent false.

A speedy and neat alternative to the if statement is the conditional statement:

x = (a==b) ? 1 : 2;

The conditional statement may only be used when the value of one variable depends on one 
condition. In the above example the variable x will equal to 1 if a is equal to b otherwise, x will 
equal to 2. 

The switch statement is a neat alternative to the if­elseif­... ­else clause and may only be used if 
one variable determines the flow of control. The general format of the switch statement is as 
follows:
switch( selector )
{
case label1: statement1;
break;
case label2: statement2;
break;
...
case labeln: statementn;
break;
default: statementd; // optional;
break;
}

The switch allows the flow of control to jump to a label that is equal to the selector variable. If none 
of the labels match the selector variable the switch statement will jump to the default statement if it 
exists. The break at the end of each case statement is used to exit the switch. If the break is omitted 
the program will continue to execute the remaining case statements until it reaches a break. 

while(), do­while() and for() loops
Loops   are   essential   in   any   programming   language.   Loops   allow   a   statement   to   be   repeatedly 
executed while a logical expression is true. The following is a general format of the loops supported 
in C:
while(expre) do for(state_1; expre; state_3)
{ { {
state; state; state_2;
} } }
while(expre);

A loop will continue to execute the statement inside the{} brackets while the expression is TRUE. 
In the case of the  while  and  do­while  loops, the statement is typically designed to affects some 
variable in the expression so that the loop would eventual break. 
Generally, a loop can be completely defined by three control statements: initializer, expression and 
an iterator. The  for loop allows us to define these three control statements in a compact and neat 
way.   In the example above, Statement_1 is used to initialize variables that will be use inside the  
loop, the expression is used to break from the loop if the logic returns  false  ans    Statement_3 is 
generally used to iterate some variable that will be used to test the logical expression.
The following example shows how a sequence of 0­9 can be printed using the three types of loops.
// while loop example
int i=0;
while(i<10)
{
printf("%d ", i++);
}
printf("\n");

// do­while loop example
i=0;
do
{
printf("%d ", i++);
}
while(i<10)

// for loop example
for(i=0; i<10; ++i)
{
printf("%d ", i);
}
QUESTIONS:
1. Fill in the missing fields in the table  below. You may write a programs to confirm your 
results. To assist you in this task you may use the sizeof(data_type) function. This function 
takes the name of a data type as its argument and returns the number of bytes occupied by 
this data type. For example you may want to use something like:
printf("%d ", sizeof(name_of_your_data_type_goes_here));

TYPE BYTES RANGE


char 1 ­128 to +127
unsigned char
short int ­32,768 to 32,767
unsigned short int 2
int
unsigned int
long int
float ≈±3.4∗10±38
double ≈±1.7∗10±308
long double ≈±1.1∗10
±4932

These  figures   may vary  depending  on the  compiler  and processor  being  used. To find  out  the 
number of bytes allocated to a data type we can use the sizeof(data_type) function, which returns 
the number of bytes required to store the type data_type in memory. 
[2 mark]

2. Copy the following code into the body of your main function and execute.  Explain and 
justify the result.
int x = 15000;
short int y;
y = 3*x;
printf("%d ", y);
[2 mark]

3. Write a program that prints the following pattern USING LOOPS.
-----------
*---------*
**-------**
***-----***
****---****
*****-*****
***********
[2 marks]
4. Write a program to that will print the value of a unsigned integer  n  in binary. The output 
should look something like this:

The number 632459207 is equal to


00100101101100101000111111000111 in binary.
[2 mark]

5. Write a program that will approximate the square root of any positive floating point number.  
You may use the following procedure:
i. Initialize a positive floating point number of your choice and store it in n.
ii. Get your program to calculate a very poor estimate for the square root of n and store your 
result in e. It does not matter how good this estimate is, as long as it is greater than 0.
iii. improve on your guess by using the following: g = 0.5*(e + n/e)
iv. repeat step iii. ten times
v. print the value of e

Set n to 53 and change your code so that it repeats step ii 1, 2, 3, 4 and 5 times. Comment on 
the accuracy of the results.
[2 mark]

Lab Report
In your lab report, you must include commented code for each question and a brief explanation of 
what your program does.  The report is due on the following dates at 2pm:
Group Lab Date Report Due Date
A April 4 April 18
B April 6 April 20
C April 7 April 21

LATE SUBMISSION OR PLAGIARISM WILL NOT BE ACCEPTED!

Andrew Martchenko, April 2011

Anda mungkin juga menyukai