C Progamming Topic1&2 hnd1
C Progamming Topic1&2 hnd1
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.
Objectives
Contents
I. WHAT IS A C/C++ PROGRAMMING LANGUAGE? ........................................... 1
II. C & C++: SIMILARITIES AND DIFFERENCES ................................................ 2
III. WHAT DO WE NEED? ........................................................................................... 2
IV. MY FIRST C-PROGRAM ....................................................................................... 2
V. UNDERSTANDING OF THE PROGRAM STRUCTURE ..................................... 3
EXERCISE 1 ........................................................................................................................ 4
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
C++, as the name suggests is a superset of C. As a matter of fact, C++ compitler can run most
of C code while C cannot run C++ code. Here are some basic differences between C++ & 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.
Source language Machine language
int a=10; 10111101110101
{ 11000001101111
a = a+4; Compiler 10111110001001
Prinf(“a = %d”, a); 10111000011100
………. ……….
There are tools combining both compiler and editor in one called development environment.
We will use DevC++ IDE (Integrated Development Environment), version 5.5.3. It can be
downloaded freely in www.sourceforge.net
We are going in this paragraph to show different steps to handle a C-program from the
edition to the execution
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 */
5 printf("This is my first experience in C! ");
6 return 0;
7 }
3) Save the program
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.
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(s)) and compile
the source code again.
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
An interesting part of the text string is \n. Together, the backslash (\) and n characters make up
an escape sequence. This particular escape sequence (\n) tells the program to add a new line.
Other example of escape sequence are: \t (Moves the cursor to the next tab), \r(Moves the
cursor to the beginning of the current line), \\( Inserts a backslash), \”( Inserts a double quote),
\’(Inserts a single quote).
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;
return 0; terminates main() function and returns the value 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 in 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.
For example, following are two different statements:
EXERCISE 1
*
***
*****
Exercise 1.2: Write a C-program to print the following sentence:
Exercise 1.3: Using an appropriate escape sequence, write a C program that display a sample
calendar month as the following: [See Activity 1.2]
-----------------------------------------------------------------
Sun Mon Tue Wed Thu Fri Sat
----------------------------------------------------------------
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Exercise 1.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.
TOPIC 2
Contents
I. KEYWORD ................................................................................................................... 6
II. IDENTIFIERS ........................................................................................................... 7
III. DATA TYPE .............................................................................................................. 7
IV. C VARIABLES.......................................................................................................... 9
V. C CONSTANTS AND LITERALS........................................................................ 10
VI. INPUT AND OUTPUT ........................................................................................... 13
EXERCICE 2 ...................................................................................................................... 14
I. KEYWORD
[See Activity 2.1]
Keywords are reserved words which have standard, predefined meaning in C. They cannot be used
as program-defined identifiers.
For example, some invalid identifiers are shown below: [See Activity 2.1]
Following table gives you details about standard integer types with its storage sizes and
value ranges:
Type Storage size Value range
Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
Int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
Short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
Long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
To get the exact size of a type or a variable on a particular platform, you can use the
sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes.
Following is an example to get the size of int type on any machine:
#include <stdio.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
Following table gives you details about standard floating-point types with storage sizes and
value ranges and their precision:
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;
}
IV. C VARIABLES
IV.1 Definition of a variable
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.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in previous chapter, there will be the following
basic variable types:
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:
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;
#include<stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
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
#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 executed, it produces the following result: value of area : 50
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:
Escape Escape
Meaning Meaning
sequence sequence
\\ \ character \n Newline
\' ' character \r Carriage return
\" " character \t Horizontal tab
\? ? character \v Vertical tab
\a Alert or bell \ooo Octal number of one to three digits
\b Backspace \xhh . . . Hexadecimal number of one or more digits
\f Form feed
scanf is a function in C which allows the programmer to accept input from a keyboard. It obtains
a value from the user
When executing the program the user responds to the scanf statement by typing in a number, then
pressing the Enter (return) key
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).
#include <stdio.h>
int main()
{
char me[20];
printf("What is your name?");
scanf("%s",&me);
printf("I arn glad to meet you, %s!\n",me,);
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
putchar(c) puts the character c on the standard output stream.
EXERCICE 2
Exercise 2.1: Identify keywords and valid identifiers among the following: