0% found this document useful (0 votes)
11 views

1 ICS 2175 Lecture 3 Programming in C To Use2

SUMMARY

Uploaded by

sandraakinyi307
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

1 ICS 2175 Lecture 3 Programming in C To Use2

SUMMARY

Uploaded by

sandraakinyi307
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

ICS 2175: Programming

Introduction to C programming
Language
Introduction to C

 C is a general-purpose, structured programming language.

 Its instructions consist of terms that resemble algebraic


instructions, augmented by certain English keywords e.g. if,
else, for, do, while etc.

 In this respect C resembles other high level structured


programming languages e.g. Pascal and Fortran.
Introduction to C

 C also contains certain additional features that allow it to be


used at a lower level thus bridging the gap between machine
language and conventional high level languages.

 This flexibility allows C to be used for systems programming


as well as applications programming.
A C Program
 Every C program consists of one or more modules called
functions.

 One of the functions must be called main.

 The program will always begin by executing the main


function, which may call other functions.

 Any other function must be defined separately either ahead or


after the main function.
A C Program
 Each Function Contains:

1. A function heading – consists of the function name,


followed by an optional list of arguments.

2. Argument declarations – Argument types (if the function


has arguments)

3. Body – What the function should do. Enclosed in a pair of


braces({ }). – The body contains expression detailing what
the function should do.
Basic Structure of C Programs
 C programs are essentially constructed in the following manner,
as a number of well defined sections.
/* HEADER SECTION – Contains name, author, revision
number*/
/* INCLUDE SECTION - contains #include statements
*/
/* CONSTANTS AND TYPES SECTION - contains types and
#defines */
/* GLOBAL VARIABLES SECTION - any global variables
declared here */
/* FUNCTIONS SECTION - user defined functions
*/
/* main() SECTION */
int main()
{
}
Basic Structure of C Programs …
 Adhering to a well-defined structured layout will make
your programs

1. Easy to read
2. Easy to modify
3. Consistent in format
4. Self documenting
Example:
A C program to output a greeting
#include<stdio.h>/*enables us to use
functions defined elsewhere */
void main()
{ printf(“hello world”); //printf is an
output function
}//end

 The include statement enables us to use functions defined


elsewhere e.g. printf. We use the include statement to specify
the file in which they are defined
 Note that every C program statement ends with a semicolon
Basic Data Types
 Data types refer to the different kinds of data that can be used in
a program.
 There several data types differing in the number of bytes in
memory (i.e. space in memory) used to hold data of a specific
type.

 The basic data types include:


Integers – a common range for integer storage is 2 bytes, which
gives the range 32768 to +32767. Bigger integers can be stored
by representing integers with more bytes.

 Bigger integers can be stored using the long data type.


Basic Data Types

 float – The number of bytes used can vary from 4 to 8 but


usually four bytes are used. Used for representing real numbers
(have decimal places).

 Real numbers can be represented using double data types which


allow for greater precision.

 Char (characters) – Stored in memory by using 7-bit binary


codes. E.g. A is coded as 65, a as 97, ‘1’ as 49 in the ASCII
(American Standard Code for information interchange)
representation.
Variables

 A variable is an identifier used to represent some specified type


of information within a designated portion of the program.

 In its simplest form, a variable is an identifier that is used to


represent a single data item e.g. a numerical quantity or a
character constant.

 The data item must be assigned to the variable at some point in


the program.
Variables

 The data item can then be accessed later in the program simply
by referring to the variable name.

 A given variable can be assigned different data items at various


places within the program.

 Thus the information represented by a variable can change at


various places during the execution of the program but the data
type represented by the variable cannot change.
Variable Declarations
 Involves stating the type of data a variable will hold within the
program.
Basic Input/output
 To read data from the keyboard and print (display) information
on the screen one uses the printf and scanf functions in C.
 Printf and scanf are defined in stdio.h. They are used for basic
input and output. printf is used like in the program above. It
can take several parameters (arguments).
printf
The Syntax of the printf function is as shown below:
printf(Control string, arg1,arg2,…,argn);

The control string refers to a string that contains the


formatting information (how the output should be arranged
and the type of data in the output) and arg1…argn represent
the individual data items to be output.
Basic Input/output …
scanf
 used to read data entered at the keyboard.
 Its syntax is similar to that of printf
scanf(Control string, arg1,arg2,…,argn);
 The control string contains required formatting information
(the format of the data that should be entered).
 arg1…argn are the variables where the entered information will
be stored.
 Each of the variable identifier is usually preceded by an
ampersand e.g. &agr1.
 This gives the address in memory of the variable. The data
entered is stored at that memory location.
Basic Input/output …
Comments
 These are statements within the program that are ignored by the
compiler.
 The programmer uses comments to explain what the purpose of
a statement or group of statements in the program does.
 A comment line is started with two forward slashes (//).
 Everything that comes after the comment indicators in the line
will be ignored.
 Some times the comment can span several lines. In this case,
they should be enclosed as shown below:
/* comments
..comments */
What Comments Are Used For

 documentation of variables and their usage

 explaining difficult sections of code

 describes the program, author, date, modification changes,


revisions etc

 Copyrighting
Character Data types

• You declare a variable to be of character data type by using the


char keyword.
• A variable of this type is used to store only a single character.
• getchar function is used to read a single character from the
keyboard.

• The putchar function is used to output a single character on the


screen.
Example : Character input/output
#include <stdio.h>
void main()
{
char initial;
printf("Enter the first character of your sir name :");
initial=getchar();
printf("The first character of your sir name is::");
putchar(initial);
putchar('\n');
}
• In the example above, the forward slash precedes special
characters.
• ‘\n’ for instances represents an end of line character i.e. end of
line character is output so any other output will be written on a
new (next) line.
Arrays
 An array is another kind of variable that is used extensively in C.
 An array is an identifier that refers to a collection of data items
that all have the same name.
 The data items must be of the same type (e.g. all integers or all
characters).
 The individual array elements are distinguished from one
another by the value that is assigned to a subscript.

Figure 1: A representation of an array with 5


character elements. Each element can be accesse
by a combination of the arrayName and its
position in the array (subscript)
Declaring an array
 When you declare an array variable, you state the type of its
elements and its size.
Strings
 Data types are represented by an array of characters.
 Used to store data such as names.
 The last character stored in a string array is the nul character (‘\
0’)
 The use of string data types will be illustrated by the following
example.
String Example
#include<stdio.h>
void main()
{
char name[30]; //this states that a name
will be an array of 30 characters. They
could be less
//now we can enter the name then print it
out
printf(“enter your first name ::”);
scanf(“%s”,name);
printf(“You have indicated that your first
name is : %s”,name);
String Example …
 In the example above, scanf reads up to the first white space
character.
 The %s modifier ensures that scanf adds a nul character as
the last character in the array
 You can direct scanf to read all characters of a specific type.
If it finds a character which is not of the specified type, it
stops reading and returns what has been read so far.
 This is useful for instance when you enter to enter both the
first name and surname which are separated by white spaces
and one needs to read them together.
 The characters scanf should read are included in square
brackets e.g. [a-z] means continue reading as long as the
characters are alphabetic(lowercase) for both uppercase and
lowercase use [a-zA-Z].
String Example …

 You can use the character ^(circumflex) to negate the meaning


of the characters in the square brackets.

 [^1-9] means read every character except a digit. When scanf


comes across a digit, it stops reading and return what it as read
so far.
Mathematical Operators
Operator Name /Function Description

The result of addition of two integers is an integer. The


+ Addition result of addition of a float and an integer is a float. A
float plus a float results in a float

The result of subtraction of two integers is an integer.


- Subtraction The result of subtraction of a float and an integer is a
float. A float minus a float results in a float

Multiplication of two integers results in an integer. The


* Multiplication result of multiplication of a float and an integer is a
float. A float times a float results in a float

Division of two integers results in an integer. Any


/ Division remainder is lost. The result of division of a float and
an integer is a float. A float divided by a float results in
a float
Acts on integers. Returns the remainder of an integer
% modulus
division
Logical Operators
Operator Meaning

== Equal to

> Grater than

>= Greater than or equal to

< Less than

<= Less than or equal to

!= Not equal to

&& Logical and

|| Logical or
Control Structures
 These are statements used to control the sequence in which
instructions of a program are executed.
A. Selection Statements
 A realistic C program may require that a logical test be carried
out at some point within the program.
 One of several actions will then be carried out depending on the
outcome of the test.
 This is known as branching.
 This may be done using several control structure included in C.
1. The if–else statement
 Used to carryout a logical test then take one of two possible
actions. The else part of the statement is optional. Thus, in its
most general form it is written: if (expression) statement.
The if–else statement can also take the following form:
if(expression1)
statement1
else if(expression2)
statement2
else if(expression3)
statement3

else if(expression n)
statement n
else
statement n+1
2. The Switch statement
 The switch statement is another selection statement provided in
C.
 It causes a group of statements to be chosen from one of several
groups. The selection is based on one of several values of an
expression

 It has the following form:


switch (expression) statement.
NB: expression should evaluate into an integer value.
The Switch statement
switch(expression)
{
case expression 1:
statement(s)
break;
case expression 2:
statement(s);
break;
.
.
.
case expression n:
statement(s)
break;
default:
statement(s);
break;
}//end switch
B. Looping / Repetition
 In writing a computer program, it is often necessary to
repeat a part of a program a number of times.

 One of the ways of achieving this would be to write out that


part of the program as many times as it was needed.

 This, however, is a very impractical method since it would


produce a very lengthy computer program and the number
of times that part of the program should be repeated might
not known in advance.

 In this section, we introduce 3 methods for running a part of


a program repeatedly also known as looping.
1. The While Statement
 The while statement is used to carryout looping operations in
which a group of statements is executed repeatedly until some
condition as been satisfied.
 The general form of the while statement is:
While (logical expression) statement
 The statement will be executed repeatedly while the logical
expression is true.
Example: The following program prints the digits 0 – 9 using a
while loop.
#include <stdio.h>
void main()
{
int digit =0;
while (digit<=9)
{
printf(“%d ”,digit);
digit=digit+1;
}
}
Exercise: Write a program using a loop that gets the sum of the
first 20 integers i.e. the sum if 1 – 20.
2. The Do while loop
 This looping statement is similar to the while statement
except that the statement is executed at least once.
 If you look closely at the while statement above you’ll see
that there is a possibility that the statement will not be
executed if the expression is false the first time the program
tries to enter the loop.

 The general form of the do while statement is:


do statement while(expression)
 Using the do while statement, the above program can be
written as shown below:
#include <stdio.h>
void main()
{
int digit =0;
do
{
printf(“%d ”,digit);
digit=digit+1;
} while (digit<=9);
}//end main
The Do while loop
 We can write a program to read all the input from the
keyboard using the getchar() function until we encounter an
end of line function.

 We store each of the characters we read in an array.

 After we get to the end of line we will output the string we


have read using printf:

 NB: We have to put a null character as the last character of


the string
3. The for statement
 This statement includes an expression that specifies an initial
value for an index, another statement that specifies whether
or not the loop is continued and another statement that
allows the index to be modified at the end of each pass.

 The general form of the for statement is shown below:


3. The for statement
for (expression 1; expression 2; expression 3) statement

 Expression 1 is used to initialize some variable;

 Expression 2 is used to represents a logical expression


related to the parameter in expression one. Expression 2
must be true for the loop to continue.

 Expression 3 makes a change to the variable in expression 1.


This change is what will eventually make expression 2 to be
false to end the loop.
We can rewrite the program to print digits 0–9 using a for
loop.
#include <stdio.h>
void main()
{ for(int index=0;index<=9; index++)
{ printf(“%d ”,index);
} //end for
}//end main

Notice that the statement index++. This is equivalent/short form


for index=index+1.

Exercise: write the same program using a for loop but now the
digits should be written from 9 to 0. Thus the index should be
decreasing i.e. should be initialized to 9.

You might also like