0% found this document useful (0 votes)
108 views15 pages

C Progamming Topic1&2 hnd1

The document provides an introduction to getting started with C programming. It discusses [1] what C and C++ programming languages are, [2] the similarities and differences between C and C++, and [3] what is needed to write a C program including an editor, compiler, and executable file. It then provides a sample "Hello World" C program as an example and explains the key parts of a basic C program structure. Finally, it includes some exercises for readers to practice writing simple C programs.

Uploaded by

Lapa Etienne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views15 pages

C Progamming Topic1&2 hnd1

The document provides an introduction to getting started with C programming. It discusses [1] what C and C++ programming languages are, [2] the similarities and differences between C and C++, and [3] what is needed to write a C program including an editor, compiler, and executable file. It then provides a sample "Hello World" C program as an example and explains the key parts of a basic C program structure. Finally, it includes some exercises for readers to practice writing simple C programs.

Uploaded by

Lapa Etienne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

TOPIC 1

GETTING STARTED WITH C PROGRAMMING

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

At the end of this lesson, student should be able to:

- Describe the structure of a C-program


- write, compile and execute a simple C-program using the command “printf” and
escape sequences, and containing comments

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

I. WHAT IS A C/C++ PROGRAMMING LANGUAGE?

The C/C++ language consists of two basic elements:

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
II. C & C++: SIMILARITIES AND DIFFERENCES

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...

1. C follows the procedural programming paradigm while C++ is a multi-paradigm


language (procedural as well as object oriented)
2. In case of C, the data is not secured while the data is secured(hidden) in C++( due to
specific OOP features like Data Hiding which are not present in C).
3. The standard input & output functions differ in the two languages (C uses scanf &
printf while C++ uses cin>> & cout<< as their respective input & output functions)

III. WHAT DO WE NEED?

To write a program, you need two specialized computer programs.

- 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

IV. MY FIRST C-PROGRAM


[See Activity 1.1]

We are going in this paragraph to show different steps to handle a C-program from the
edition to the execution

1) Launch the development environment (Here Dev C++)


To launch the Dev C++ environment, the process is :
Start button → All program → Bloodshed Dev-C++ → Dev C++
2) Open the text editor and type the program
To open a text editor in a Dev-C++ environment:
File → New → Source file

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.

4) Compile and link the program


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.)

To compile the program: 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(s)) and compile
the source code again.

5) Execute the program


Finally, you run the program you have created. Yes, it’s a legitimate program, like any other
on your hard drive.

To execute the program: Execute → Run

V. UNDERSTANDING OF THE PROGRAM STRUCTURE

Let’s understand various parts of our above program

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:

printf("Hello, World! \n"); return 0;

EXERCISE 1

Exercise 1.1: Write a C program that print the following

*
***
*****
Exercise 1.2: Write a C-program to print the following sentence:

The character \ name’s “backslash”

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

C CONSTANTS AND VARIABLES

A C program consists of various tokens and a token is either a keyword, an identifier,


a constant, a string literal, or a symbol.

Objectives: at the end of this topic, student should be able to

- Identify C language keywords


- Identify and define a variable or a constant
- Use formatted input/output (scanf and printf) and escape sequence

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.

auto default float register struct volatile


break do for return switch while
case double goto short typedef _packed
char else if signed union printf
const enum int sizeof unsigned scanf
continue extern long static void FILE
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.

Identifiers are defined according to the following rules:

- It consists of letters and digits.


- First character must be an alphabet or underscore.
- Both upper and lower cases are allowed. Same text of different case is not equivalent, for
example: TEXT is not same as text.
- Except the special character underscore ( _ ), no other special symbols can be used.
For example, some valid identifiers are: nb1, cons, h456787, tax_rate, _XI, FOR…

For example, some invalid identifiers are shown below: [See Activity 2.1]

 123 First character to be alphabet.


 “X.” Not allowed.
 order-no Hyphen not allowed.
 error flag Blankspace allowed.
 auto keyword
Note: Generally all keywords are in lower case although uppercase of same names can be used as
identifiers.

III. 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:

S.N. Types and Description


Basic Types: They are arithmetic types and consists of the two types: (a) integer types and
1
(b) floatingpoint 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.
III.1 Integer Types

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;
}

III.2 Floating- Point Types

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:

IV.2 Variable declaration [See Activity 2.4]

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:

data-type variable_name = value;

Some examples are:

int d = 3, f = 5; // declaration of d and f.


int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

IV.3 Lvalues and Rvalues in C


There are two kinds of expressions in C:

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;

V. C CONSTANTS AND LITERALS


[See Activity 2.3]

V.1 Defining Constants

There are two simple ways in C to define constants:


1. Using #define preprocessor.
2. Using const keyword.

a) The #define Preprocessor


Following is the form to use #define preprocessor to define a constant:

#define: identifier value

Following example explains it in detail:

#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

b) The const Keyword


You can use const prefix to declare constants with a specific type as follows:

const type variable = value;

Following example explains it in detail:

#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

Note that it is a good programming practice to define constants in CAPITALS.

V.2 Character constants


[See Activity 1.3]
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:

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

Following is the example to show few escape sequence characters:


#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
VI. INPUT AND OUTPUT
VI.1 Formatted input — scanf

Let’s consider the following statement: scanf(“%f”, &a);

scanf is a function in C which allows the programmer to accept input from a keyboard. It obtains
a value from the user

This scanf statement has two arguments

- %f - indicates data should be a floating number


- &a - location in memory to store variable
& 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

VI.2 Formatted output — printf


[See Activity 2.5]
printf(“The new value of b is %f\n”, b);

In the program statement above:

“The new value of b is %f\n” is the control string


b is the variable to be printed

scanf and printf use the same conversion characters as .

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).

VI.3 Characters’ Input/Output

#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:

hello function day-of-the-week student_1 max_value “what” 1_student int union

You might also like