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

2 Programming

Uploaded by

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

2 Programming

Uploaded by

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

Programming

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

1
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.
 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
2
the function should do.
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 a
predefined 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 the predefined functions we use are defined
 Note that every C program statement ends with a semicolon (;)
3
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 4 bytes, which
gives the range  2,147,483,648 to +2,147,483,647. Bigger
integers can be stored by representing integers with more bytes.
 Bigger integers can be stored using the long data type.
 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. 4
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.
 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.
5
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;/* declaring the
variables*/
//assign a value to the variables
num1=50;
num2=60;
num3=num1+num2;
printf(“\n%d”,num3);
}//end 6
Constants
 These are identifiers whose values never change during the course
of the execution of the program
#include <stdio.h>
#define INCR 10
void main()
{
const MULT=5;
int num1=20;
//assign a value to the variables
printf(“\n%d”,num1+INCR);
printf(“\n%d”,num1*MULT);
}//end

7
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. 8
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. &arg1.
 This gives the address in memory of the variable. The data
entered is stored at that memory location.
9
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 */
10
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

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

12
#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 13
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()
{
14
}
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

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

16
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');
17
}
In the example above, the forward slash precedes special
characters. ‘\n’ for instances represents an end of line
character i.e. and end of line character is output so any other
output will be written on a new (next) line.

18
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) 19
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;
20
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

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

22
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 23
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
24
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

25
#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);
26
} //end

You might also like