C Basics
C Basics
Before we embark on a brief tour of C's basic syntax and structure we offer
a brief history of C and consider the characteristics of the C language.
Many High level languages, like PASCAL, are highly disciplined and
structured.
However beware -- C is much more flexible and free-wheeling. This
freedom gives C much more power that experienced users can
employ. The above example below (mystery.c) illustrates how bad things
could really get.
History of C
The milestones in C's development as a language are listed below:
Characteristics of C
We briefly list some of C's characteristics that define the language and also
have lead to its popularity as a programming language. Naturally we will be
studying many of these aspects throughout the course.
Small size
Extensive use of function calls
Loose typing -- unlike PASCAL
Structured language
Low level (BitWise) programming readily available
Pointer implementation - extensive use of pointers for memory, array,
structures and functions.
C has now become a widely used professional language for various reasons.
Its main drawback is that it has poor error detection which can make it off
putting to the beginner. However diligence in this matter can pay off
handsomely since having learned the rules of C we can break them. Not
many languages allow this. This if done properly and carefully leads to the
power of C programming.
#include <stdio.h>
main(t,_,a)
char *a;
{return!0<t?t<3?main(-79,-13,a+main(-87,1-_,
main(-86, 0, a+1 )+a)):1,t<_?main(t+1, _, a ):3,main ( -94, -27+t, a
)&&t == 2 ?_<13 ?main ( 2, _+1, "%s %d %d\n" ):9:16:t<0?t<-72?main(_,
t,"@n'+,#'/*{}w+/w#cdnr/+,{}r/*de}+,/*{*+,/w{%+,/w#q#n+,/#{l,+,/n{n+\
,/+#n+,/#;#q#n+,/+k#;*+,/'r :'d*'3,}{w+K w'K:'+}e#';dq#'l q#'+d'K#!/\
+k#;q#'r}eKK#}w'r}eKK{nl]'/#;#q#n'){)#}w'){){nl]'/+#n';d}rw' i;# ){n\
l]!/n{n#'; r{#w'r nc{nl]'/#{l,+'K {rw' iK{;[{nl]'/w#q#\
n'wk nw' iwk{KK{nl]!/w{%'l##w#' i; :{nl]'/*{q#'ld;r'}{nlwb!/*de}'c \
;;{nl'-{}rw]'/+,}##'*}#nc,',#nw]'/+kd'+e}+;\
#'rdq#w! nr'/ ') }+}{rl#'{n' ')# }'+}##(!!/")
:t<-50?_==*a ?putchar(a[31]):main(-65,_,a+1):main((*a == '/')+t,_,a\
+1 ):0<t?main ( 2, 2 , "%s"):*a=='/'||main(0,main(-61,*a, "!ek;dc \
i@bK'(q)-[w]*%n+r3#l,{}:\nuwloca-O;m .vpbks,fxntdCeghiry"),a+1);}
It will compile and run and produce meaningful output. Try this program out.
Try to compile and run it yourself. Alternatively you may run it from here and
see the output.
Clearly nobody ever writes code like or at least should never. This piece of
code actually one an international Obfuscated C Code Contest
http://reality.sgi.com/csp/iocc The standard for C programs was originally the
features set by Brian Kernighan. In order to make the language more
internationally acceptable, an international standard was developed, ANSI C
(American National Standards Institute).
C Program Structure
A C program basically has the following form:
Preprocessor Commands
Type definitions
Function prototypes -- declare function types and variables passed to
function.
Variables
Functions
C Statements
/* Sample program */
main()
{
}
NOTE:
.
.1
..2
...3
Variables
C has the following simple data types:
On UNIX systems all ints are long ints unless specified as short int explicitly.
NOTE: There is NO Boolean type in C -- you should use char, int or (better) unsigned char.
Unsigned can be used with all char and int types.
short number,sum;
int bignumber,bigsum;
char letter;
main()
{
It is also possible to pre-initialise global variables using the = operator for assignment.
For example:-
float sum=0.0;
int bigsum=0;
char letter=`A';
main()
{
float sum;
int bigsum;
char letter;
main()
{
sum=0.0;
bigsum=0;
letter=`A';
a=b=c=d=3;
a=3;
b=3;
c=3;
d=3;
This kind of assignment is only possible if all the variable types in the statement are the
same.
You can define your own types use typedef. This will have greater relevance later in the
course when we learn how to create more complex data structures.
As an example of a simple use let us consider how we may define two new types real and
letter. These new types can then be used in the same way as the pre-defined C types:
Variables declared:
real sum=0.0;
letter nextletter;
%c -- characters
%d -- integers
%f -- floats
NOTE: Format statement enclosed in ``...'', variables follow after. Make sure order of format
and variable data types match up.
scanf() is the function for inputting values to a data structure: Its format is similar to printf:
NOTE: & before variables. Please accept this for now and remember to include it. It is to do
with pointers which we will meet later (Section 17.4.1).
Constants
ANSI C allows you to declare constants. When you declare a constant it is a bit like a
variable declaration except the value cannot be changed.
int const a = 1;
const int a =2;
Note:
You can declare the const before or after the type. Choose one an stick to it.
It is usual to initialise a const with a value as it cannot get a value any other way.
The preprocessor #define is another more flexible (see Preprocessor Chapters) method to
define constants in a program.
You frequently see const declaration in function parameters. This says simply that the
function is not going to change the value of the parameter.
The following function definition used concepts we have not met (see chapters on functions,
strings, pointers, and standard libraries) but for completenes of this section it is is included
here:
The second argiment string is a C string that will not be altered by the string copying
standard library function.
Arithmetic Operations
As well as the standard arithmetic operators (+ - * /) found in most languages, C provides
some more operators. There are some notable differences with other languages, such as
Pascal.
Increment ++, Decrement -- which are more efficient than their long hand equivalents, for
example:-- x++ is faster than x=x+1.
The ++ and -- operators can be either in post-fixed or pre-fixed. With pre-fixed the value is
computed before the expression is evaluated whereas with post-fixed the value is computed
after the expression is evaluated.
int x,y,w;
main()
{
x=((++z)-(w--)) % 100;
int x,y,w;
main()
{
z++;
x=(z-w) % 100;
w--;
So make sure you do this. The correct (for division) answer to the above is x = 3.0 / 2 or x=
3 / 2.0 or (better) x = 3.0 / 2.0.
and x = x*(y + 2) as x *= y + 2.
Comparison Operators
To test for equality is ==
if ( i = j ) .....
This is a perfectly LEGAL C statement (syntactically speaking) which copies the value in "j"
into "i", and delivers this value, which will then be interpreted as TRUE if j is non-zero. This is
called assignment by value -- a key feature of C.
Other operators < (less than) , > (grater than), <= (less than or equals), >= (greater than
or equals) are as usual.
Logical Operators
Logical operators are usually used with conditional statements which we shall meet in the
next Chapter.
Beware & and | have a different meaning for bitwise AND and OR ( more on this later in
Chapter 12).
Order of Precedence
It is necessary to be careful of the meaning of such expressions as a + b * c
(a + b) * c
or
a + (b * c)
All operators have a priority, and high priority operators are evaluated before lower priority
ones. Operators of the same priority are evaluated from left to right, so that
a-b-c
is evaluated as
(a-b)-c
From high priority to low priority the order for all C operators (we have not met all of them
yet) is:
( ) [ ] -> .
! - * & sizeof cast ++ -
(these are right->left)
*/%
+-
< <= >= >
== !=
&
|
&&
||
?: (right->left)
= += -= (right->left)
, (comma)
Thus
is interpreted as
( a < 10 ) && ( ( 2 * b ) < c )
and
a=
b=
spokes / spokes_per_wheel
+ spares;
as
a=
(b=
( spokes / spokes_per_wheel )
+ spares
);
Exercises
Write C programs to perform the following tasks.
Exercise 12270
Input two numbers and work out their sum, average and sum of the squares of the numbers.
Exercise 12271
Input and output your name, address and age to an appropriate structure.
Exercise 12272
Write a program that works out the largest and smallest values from a set of 10 inputted
numbers.
Exercise 12273
Write a program to read a "float" representing a number of degrees Celsius, and print as a
"float" the equivalent temperature in degrees Fahrenheit. Print your results in a form such
as
Exercise 12274
Write a program to print several lines (such as your name and address). You may use either
several printf instructions, each with a newline character in it, or one printf with several
newlines in the string.
Exercise 12275
Write a program to read a positive integer at least equal to 3, and print out all possible
permutations of three positive integers less or equal to than this value.
Exercise 12276
Write a program to read a number of units of length (a float) and print out the area of a
circle of that radius. Assume that the value of pi is 3.14159 (an appropriate declaration will
be given you by ceilidh - select setup).
Your output should take the form: The area of a circle of radius ... units is .... units.
If you want to be clever, and have looked ahead in the notes, print the message Error:
Negative values not permitted. if the input value is negative.
Exercise 12277
Given as input a floating (real) number of centimeters, print out the equivalent number of
feet (integer) and inches (floating, 1 decimal), with the inches given to an accuracy of one
decimal place.
Exercise 12278
Given as input an integer number of seconds, print as output the equivalent time in hours,
minutes and seconds. Recommended output format is something like
Exercise 12279
The first integer value represents a time of day on a 24 hour clock, so that 1245 represents
quarter to one mid-day, for example.
The second integer represents a time duration in a similar way, so that 345 represents three
hours and 45 minutes.
This duration is to be added to the first time, and the result printed out in the same notation,
in this case 1630 which is the time 3 hours and 45 minutes after 12.45.
Typical output might be Start time is 1415. Duration is 50. End time is 1505.
You saw above that puts function is used to put a whole sentence
on the screen; but are there functions that will put characters on
the screen/take characters: Yes and next is a table of what they are
and what they do. Read them and the examples that follow.
Now we will look into a function called scanf().This lets you input
from the kewyboard and for that input to be taken by the program
and processed.Once again it is important to tell scanf() what type of
data is being scanned.
main() {
int count;
puts("Please enter a number: ");
scanf("%d", &count);
printf("The number is %d",count);
}
example-4
main()
{
puts("hello there");
puts("what is your name?")
pause()
puts("It is nice to meet you")
}
pause();
{
int move_on;
printf("press entere to continue");
move_on=getchar();
return(0);
}
C has many functions that comes with it. See your compiler manual
to see what you have.Now we are going to look at conditions in c
programming:>> the if command and do command.
example-5
main()
{
float cost,tax,luxury,total;
luxury=0.0;
printf("Enter the cost of the item: ");
scanf("%f", &cost);
tax=cost*0.06;
if(cost>40000.0)
luxury=cost*0.005;
total=cost+tax+luxury;
printf("the total cost is %0.2f",total);
}
example-6
if(cost >40000)
{
luxury=cost*0.005;
printf("The luxury tax is %.2f",luxury);
}
else
{
puts("There is no luxury tax for the items");
luxury=0.0;
}
do
{
instruction;
instruction
}
while(condition);
for(initial=value;condition;increment)
instruction;
example-7
main()
{
int row,column;
puts("\t\tMY Handy multipication table");
for(row=1;tow<=10;row++)
{
for(column=1;column<=10;column++)
printf("%6d", row*column);
putchar('\n');
}
}
example-8
main()
{
int temp;
float celsius;
char repeat;
do
{
printf("Input a temperature:");
scanf("%d", &temp);
celsius=(5.0/9.0)*(temp-32);
printf(%d degrees F is %6.2f degrees celsius\n",temp, celsius);
printf(("do you have another temperature?");
repeat=getchar();
putchar('\n');
}
while(repeat=='y'|| repeat=='y');
}
What is a flag?
example-9
main()
{
int temp;
float celsius;
char repeat;
char flag;
do
{
flag='n";
do
{
if(flag=='n')
printf("Input a valid temperature :");
else
printf("input a valid temperature,stupid:");
scanf("%d",&temp);
flag='y';
}
while (temp<0||temp >100);
celsius=(5.0/9.0)*(temp-32);
printf("%d degrees F is %6.2f degrees celsius\n",temp,celsius);
printf("Do you have another temperature?");
repeat=getchar();
putchar('\n');
}
while (repeat=='y' || repeat=='Y");
}
The break command ends the loop in which it is placed just as if the
while condition, or the condition in a for loop becomes false.
int temp[5]={45,56,12,98,12};
temp[0]=45....temp[4]=12
main()
{
int temps[31];
int index,total;
float average,celsius;
total=0.0;
for(index=0;index<31;index++)
{
printf("enter temperature #%d:",index);
scanf("%d",&temps[index]);
}
for(index=0;index<31;index++)
total+=temps[index];
average=total/31.0
printf("average is:%f\n\n", average);
puts9"fahrenheit\tcelsius\n");
for(index=0;index<31;index++)
{
celsius=(5.0/9.0)*(temps[index]-32);
printf("%d\t\t%6.2f\n",temps[index],celsius);
}
}
Now I am going to show you how to pass an array. When you pass
an array you are actually passing the address of the array.
example-10
#define count 31
main()
{
int temps[count];
int index;
float celsius;
for(index=0; index< count;index++)
{
celsius=(5.0/9.0)*(heat[index]-32);
printf("%d\t\t%6.2f\n",heat[index],celsius);
}
}
Now we are in the fourth hour of our tutorial.We are now going to
look at 1)comparing strings 2)determining string lengths. 3)
combining strings 4)structures.
Comparing 2 strings:>> In c it is not possible to directly
compare two strings so a statement like if (string1==string2) is not
valid.
if(strcmp(name1,name2)==0)
puts("The names are the same");
else
puts("The names are not the same.");
gets(name);
count=strlen(name);
printf("the string %s has %d characters",name,count);
Example-11
strcpy(name,"Adam");
strcpy(name1,"and eve");
strcat(name,name1);
puts(name);
The assumption being that adam and eve are two values of the
variables name1 and name2. The end result is the combination of
the 2 names.
example-12
struct cd
{
char name[20];
char description[40];
char category[12];
float cost;
int number;
};
main()
Notice how the main function comes after the definition of the
structure. In the example above the cd was a cd disk and I was
writing the definition of a cd collection program.
Now in the fifth hour I will show you how to output your data onto a
disk.After all what is the use of the program if you can't save output
to a disk.
The link between your program, the file and the computer is
established with the fopen() function using the syntax shown below:
pointer=fopen("FILENAME","mode");
FILE*cdfile;
cdfile=fopen("CD>DAT","w");
If you will be reading from the file above use "r" instead "w" in the
second sentence.
The eof statement means end of file and this is included in the
stdio.h header file which was declared at the start of the example.
The stdio.h header file is one of many that comes with your
compiler. So check your compiler specifics for other header files
which will help perform other functions.
Now that you went through this tutorial you should be in a position
to write simple programs and save it to a disk so you can give it
your friends or even your boss. In no way the depth of c can be done
in 5 hours but the nut and bolts can be learned that fast.Wher e you
go from there depends upon your ambitions and hard work.