0% found this document useful (0 votes)
77 views54 pages

COM 400 - Computer Programming II - Introduction To C

The document provides an introduction to the C programming language. It discusses the basic structure of C programs including functions, data types, variables, input/output functions and arrays. It also covers character data types, strings and comments.

Uploaded by

Stella
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
77 views54 pages

COM 400 - Computer Programming II - Introduction To C

The document provides an introduction to the C programming language. It discusses the basic structure of C programs including functions, data types, variables, input/output functions and arrays. It also covers character data types, strings and comments.

Uploaded by

Stella
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

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.
 Example: To add Two numbers
#include <stdio.h>
void main()
{
int num1, num2, num3=0; //declare variables
//assign a value to the variables
num1=50;
num2=60;
num3=num1+num2;
printf(“\n%d”,num3);
}//end
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
Basic Input/output …

Example:
The following example is used to illustrate the use of the input output
functions. We add Two numbers by allowing the user to enter them
on the keyboard, we then calculate the result and output it to the
user.
#include <stdio.h>
void main()
{
/*declare variables to hold the two numbers to be
added and the answer (integers)*/
int num1,num2,sum;
// Ask the user to input the two number – use printf
printf(“Enter the First Number:”);
scanf(“%d”,&num1);
printf(“\nEnter the second number:”);
scanf(“%d”,&num2);
//add the two numbers
sum=num1+num2 ;
//output the sum.
printf(“\n%d+%d=%d”,num1,num2,sum);
}//end
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 accessed
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.
Example
#include<stdio.h>
void main()
{
int ageArray[5]; // an array to store the ages (in
years) of five children
//to enter the values of the elements of the array
ageArray[0]=10;
ageArray[1]=11;
ageArray[2]=9;
ageArray[3]=8;
ageArray[4]=12;
//now print the ages of the children
printf("The first child's age is %d
years.\n",ageArray[0]);
printf("The second child's age is %d
years. \n",ageArray[1]);
printf("The third child's age is %d
years. \n",ageArray[2]);
printf("The fourth child's age is %d
years. \n",ageArray[3]);
printf("The fifth child's age is %d
years. \n",ageArray[4]);
}//End Main
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);
} //end
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.
Another String Example …

 The following example reads both the first name and


surname together
#include<stdio.h>
void main()
{
char name[50]; /*this states that a name will be an
array of 50 characters. They could be less*/
/*now we can enter the name then print it out*/
printf("enter your names ::");
scanf("%[^\n]s",name); /*scanf continues
reading until it comes across an end of line
character. It returns what it has read so
far*/
printf("You have indicated that your names
are : %s\n",name);
} //end
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.
1. The if–else statement
 Example: The following example asks the user to enter the
total marks of the student. The program then prints proceed if
the marks are greater than 40.
#include <stdio.h>
void main()
{
float marks;
printf(“Enter the student’s marks::”);
scanf(“%f”,&marks);
if (marks>40)
{
printf(“Proceed”);
}//end if
} //end main
The other form of the if–else statement includes the else
statement. Its form is: if (expression) statement1 else statement 2.
The Example above can be written to output the statement rewind
if the marks is less than 40.
#include <stdio.h>
void main()
{
float marks;
printf(“Enter the student’s marks::”);
scanf(“%f”,&marks);
if (marks>=40)
{
printf(“Proceed”);
}
else
{
printf(“Rewind”);
}
} //end main
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
Example: We can have a program that allocates the grade
depending on the students score in an exam: 70 and above is A,
60-69 is B, 50-59 is, 40-49 is D and below 40 is F (for fail)
#include<stdio.h>
void main()
{ float marks=0;
printf(“Enter the student’s marks::”);
scanf(“%f”,&marks);
if (marks>=70)
{
printf(“The grade is an A”);
}
else if (marks>=60 && marks <=69)
{
printf(“The grade is a B”);
}
else if (marks>=50 && marks <=59)
{
printf(“The grade is a C”);
}
else if (marks>=40 && marks <=49)
{
printf(“The grade is a D”);
}
else
{
printf(“The grade is an F”);
}
}//end main
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.
 A further elaboration of the switch statement is shown next.
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
Example: The following program prints the name of an input
number if it’s a digit. If it’s not it informs the user that the number
is not a digit.
#include <stdio.h>
void main()
{
int number ;
printf(“Enter a digit::”);
scanf(“%d”,&number);
switch(number)
{
case 0:
printf(“The digit is called ZERO”);
break;
case 1:
printf(“The digit is called ONE”);
break;
case 2:
printf(“The digit is called TWO”);
break;
case 3:
printf(“The digit is called THREE”);
break;
case 4:
printf(“The digit is called FOUR”);
break;
case 5:
printf(“The digit is called FIVE”);
break;
case 6:
printf(“The digit is called SIX”);
break;
case 7:
printf(“The digit is called SEVEN”);
break;
case 8:
printf(“The digit is called EIGHT”);
break;
case 9:
printf(“The digit is called NINE”);
break;
default:
printf(“The number you have entered is not a
digit”);
}//end switch
}//end main
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
#include <stdio.h>
void main()
{
char c ; /* we will store the characters we
read here.*/
char my_string[100]; /* we will store the
characters we read in this array*/
int counter ;/*This will help us to keep
track of the point in the array where
we are */
printf("Enter your string of characters and
terminate by pressing enter ");
counter=0;
do
{
c=getchar();
my_string[counter]=c;
counter=counter+1;
}while (c!='\n'); /* we continue reading
while the character we read is not an end
of line character*/
my_string[counter]='\0'; /* put a string
terminating character at the end of the
string (null character)*/
printf("%s",my_string);
}//end main
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