C Programming Language2020
C Programming Language2020
Faculty of Engineering
Bosaaso, Somalia
Computer Programming
Using C
IT instructor
Title Page
1.4: Introduction To C
II. C Fundamentals
2.5: Arithmetic
Objectives
➢ A Computer Programmer :-
▪ is a person who translates the task you want a computer to do
▪ into a form that a computer can understand
1. Sequences Of Instructions:
Here the program flows from one step to the next in strict sequence
2. Selection:
Here the program reaches a decision point and if the result of the test is true
then the program performs the instructions in Path 1, and if false it performs
the actions in Path 2. This is also known as a Conditional Construction because
the flow of the program is dependent on the result of the test condition.
3. Loops:
In this construct the program steps are repeated continuously until some test,
condition is reached, at which point control then flows past the loop into the
next piece of program logic.
Top-down Development
For convenience these common actions are placed in a module, which is a kind
of mini-program which can be executed from within the main program. Other
names for such a module are Procedure or Function Modular design is
connected directly to top-down development, as the steps or subtasks which
the programmer breaks up the program solution into, will actually format the
future modules of the program. Good modular design also aids in the reading
and understanding of the program.
Common Features Of All Programs
Along with these structured programs a few more features are needed to make
them useful:
• Data because programs are written to process data so you must have a
good understanding of the nature and structure of Data
• Operations (add, subtract, compare etc.
• Input/Output capability (e.g. to display results)
This step (often overlooked) involves the careful reading and re-reading of the
problem until the programmer understands completely what is required. To
help with this initial analysis
2. Outline The Solution (Analysis)
Once the problem has been defined, the programmer may decide to break the
problem up into smaller tasks or steps and several solutions may be
considered.
The solution outline often takes the shape of a hierarchy or structure chart.
Using the solution outline developed in step 2, the programmer then expands
this into
It is only after all design considerations have been met that a programmer
should actually start to code the program. In preceding analysis it may have
been necessary to consider which language should be used, as each has its
own peculiarities (advantages and disadvantages).
This step uses a program compiler and test data to test the code for both
syntax and
logic errors. If the program is well designed then the usual time-wasting
frustration and despair often associated with program testing are reduced to a
minimum. This step will often need to be done several times until the
programmer is satisfied that the program is running as required,
Program documentation should not be just listed as the last step in the
development process, as it is an ongoing task from the initial definition of the
problem to the final test results. Documentation also involves maintenance -
the changes that are made to a program, often by another programmer,
during the life of that program. The better a program has been documented
and the logic understood, the easier it is for another to make changes.
Programming technique
Some general useful programming techniques are pseudo code and algorithm,
flowcharts
Solution:
Pseudocode: Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”
M1=80 80
START
M2=30 + 30
M3=40 + 40
Input
M1,M2,M3,M4 M4=30 + 30 /4
= 45 FAIL
GRADE=(M1+M2+M3+M4)/4
N If
Y
GRADE<50
PRINT PRINT
“PASS” “FAIL”
STOP
Example 3: Write an algorithm and draw a flowchart to convert the length in
feet to centimeter.
Print LCM
Flowchart:
START
Input
Lft
Lcm = Lft x 30
Lcm
STOP
Example 3: Write an algorithm and draw a flowchart that will read the two
sides of a rectangle and calculate its area.
Print A
Step 2: A=L x W
Step 3: Print A
Flowchart: START
Input
W, L
A=LxW
STOP
1.3: Types Of Programming Languages
1. Machine Languages
2. Assembly Languages
3. High-level Languages
1. Machine Languages
Any computer can directly understand only its own machine language. Machine
Language is the "natural language" of a computer and as such is defined by its
hardware design. Machine language is often referred to as Object Code or
Binary Languages.
3. High-level languages
.NET, Visual C++ .NET and C#) and Java are among the most widely used
high-level programming languages.
2. The Different part of the program connects with each other by parameter
passing & using operating system.
9. add new data in program user should be ensure that function allows it.
11. The popular. Example for pop languages are : Pascal, Fortran and C
3. Data & functions of each individual object act like a single unit.
7. Data hiding possible in OOP which prevent illegal access of function from
outside of it. This is one of the best advantages of OOP also.
9. More data or functions can be added with program if necessary. For this
purpose full program need not to be change.
Early History Of C
C Standards
Program written in c are very efficient and fast. This is due to its variety
of data types and powerful operators.
C Standard Library
C programs consist of pieces called functions. You can program each piece that
you
may need to form a C program. However, most C programmers take
advantage of the rich collections of existing functions called the C Standard
Library. Thus, there are really two parts to learning the C, The first is learning
the C language itself; the second is learning how to use the functions in the C
Standard Library.
C++ compiler supports both C & C++ program and if you want to learn C++,
you don‟t need to change your compiler.
In phase 2, the programmer gives the command to compile the program.( Alt
+ F9 to
Phase 4: Linking
A linker links the object code with the code for the missing functions to
produce an executable image (with no missing pieces). If the program
compiles and links correctly, an executable image is produced.
Phase 5: Loading
Phase 6: Execution
Finally, the computer, under the control of its CPU, executes the program one
instruction at a time.
NOTE:
Programs do not always work on the first try. Each of the preceding phases
can fail because of various errors; This would cause the C program to display
an error message. If this occurs, you would have to return to the edit phase,
make the necessary corrections and proceed through the remaining phases
again to determine that the corrections fix the problem(s).
Chapter 2:
C Fundamentals
Objectives
Outline
2.5: Arithmetic
This simple program that prints a line of text We consider each line in detail.
Example 1
The very first line #include<stdio.h> (standard input / output header file)
tells the compiler to include a header file “stdio.h” in the program. Header file
contains information and declaration used by the compiler when compiling
standard input/output library functions. Here we are using printf() from stdio.h
header file.
The next line is void main() which is the beginning of the program. Every
program must have a main() because program starts execution from this
function. But what does the keyword void means before the main(). This
means that main function will not return any value to the compiler, The
parentheses following main() indicate that no parameters or arguments are
passed on to this function; The left brace, {,must begin the body of every
function. A corresponding right brace }, must end each function's body.
Our first C Program was a successful one, so for now let us try to modify or
change some of the contents of our program
Example:
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
printf("Welcome to C. ");
getch();
Output
The top two lines include two header files “stdio.h” and “conio.h” respectively.
The “stdio.h” header file contains “printf()” and “conio.h” file
(CONsoleInputOutput)contains “clrscr()” and “getch()”. The “clrscr()” clears
the output screen means any output shown by previously run program will be
erased and that why we always put them at the beginning. Next is three
“printf()” statements which will print three different messages. The “getch()”
waits for a keyboard input and if we press any key on keyboard the program
exits. So we don‟t need to press Alt + F5 to see the output as we did in above
program.
Example:
#include <stdio.h>
#include<conio.h>
void main()
printf(“welcome \n To \n C \n \t Language”) ;
getch() ;
The one printf can print several lines by using new line character
The characters of the right operand normally print exactly as they appear
between the double quotes. Notice, however, that the characters \n are not
printed on the screen. The backslash (\) is called an escape character
Escape Description
sequence
\n New line. Position the screen cursor to the
beginning of the next line.
\t Horizontal tab. Move the screen cursor to the
next tab stop.
\a Alert. Sound the system bell.
\\ Backslash. Used to print a backslash character.
\' Single quote. Use to print a single quote
character.
\" Double quote. Used to print a double quote
character
2.3: Variables, Data Types And Constants
Before we use a variable in C we must declare it. We must identify what kind
of information will be stored in it. This is called defining a variable .Variables
must be declared at the start of any block of code, but most are found at the
start of each function. A variable must be defined to be one of the legal C data
types . When a variable is defined it is not automatically initialized, it is the
responsibility of the programmer to initialize this to a start value.
Variable Names
All variable definitions must include two things variable name and its data
type.Some rules to be followed in naming a variable in C are
a. It must start with an alphabet and can contain letter, underscores and
digits. Both uppercase and lowercase letters can be used.
c. Certain keywords like int, float, struct, if, while cannot be used as variable
names.
d. The variable names should not be very long and one should refer to the
documentation of the C compiler to know the limitation. Generally the first
eight 8 characters of a variable name are significant
Note:
II. The variable names should be meaningful and denote what the variable
stores. As far as possible
Data Types in C Language
1. Integer types:
Integers are whole numbers with a range of values, range of values are machine
dependent. Generally an integer occupies 2 bytes memory space and its value
range
C has three classes of integer storage namely short int, int and long int. All three
data types have signed and unsigned forms.
int num1;
20*/
#include<stdio.h>
void main()
int i = 20;
Output:
This is my integer: 20
The float data type is used to store fractional numbers (real numbers) with 6 digits
of precision. Floating point numbers are denoted by the keyword float. When the
accuracy of the floating point number is insufficient, we can use the double to
define the number. The double is same as float but with longer precision and takes
double space (8 bytes) than float. To extend the precision further we can use long
double which occupies 10 bytes of memory space.
float num1;
double num2;
#include <stdio.h>
void main()
Float f = 3.1415;
Output
3. Character Type:
Character type variable can hold a single character. As there are singed and
unsigned
int (either short or long), in the same way there are signed and unsigned chars;
both occupy 1 byte each, but having different ranges. Unsigned characters have
values between 0 and 255, signed characters have values from –128 to 127.
char ch = „a;
Example: a, b, g, S, j. z
'd' */
#include <stdio.h>
void main()
char c;
c = 'd';
Output
This is my character: d
Example
#include<stdio.h>
#include<conio.h>
main()
char itemname[15];
int units;
float price,total;
clrscr();
Output
Enter Item price: (user input) Enter the units: (user input)
Void Type: The void type has no values therefore we cannot declare it as
variable as
The void data type is usually used with function to specify its type. Like in our
first C
program we declared “main ()” as void type because it does not return any
value.
This type of instruction are used to reading the data and used to display the
results, You can print all of the normal C types with printf by using different
placeholders:
26
Scanf
The scanf function allows you to accept input from standard in, which for us is
generally the keyboard.
scanf("%d", &b);
The program will read in an integer value that the user enters on the keyboard
(%d is for integers, as is printf, so b must be declared as an int) and place that
value into b.
In the above example a, b are variables. At the run time we have to store
some values in to that variables. a, b are integer variables.
Note
You MUST put & in front of the variable used in scanf. when you forget it your
27
2.4: Another C Program: Adding Integers
#include<conio.h>
main()
/* variable declarations*/
/*Accepting input from the user*/ printf( “ enter first number \n”) ;
scanf(“%d”,&number1) ;
printf(“sum is %d\n”,sum);
getch() ;
28
Constant:
A user using a program having constants cannot change the constants when
the program is executing
There are three ways for defining a constant in C. First method is by using
#define statements.
#define TRUE 1
#define FALSE 0
#define PI 3.1415
29
Here, the compiler will throw an error whenever the variable PI declared as a
constant is assigned a new value
The third method is by using enumerated data type. This data type is initiated
by the keyword enum, immediately after the keyword enum is the name of the
variable, followed by a list of values enclosed in curly braces. This defines a set
of constants. Hence eliminates the usage of multiple #define statements
#include<stdio.h>
#define TRUE 1
#define FALSE 0
#define PI 3.1415
void main()
}
30
Keyword:
Keyword is having special meaning. We have to use this one for special
31
Operators in C
The plus sign (+) is used to add two values, the minus sign (-) to subtract one
value from another, the asterisk(*) to multiply two values, the division (/) to
divide a value and the modulus (%) to obtain the reminder of integer division.
These are known as binary operators since they operate on two values or
variables. Table 2.4 summarizes the C arithmetic operators.
32
Note:
Example
#include <stdio.h>
main()
int var1 = 10; int var2 = 2; int var3 = 35; int var4 = 8; int result;
33
Rules of Operator Precedence
the following rules of operator precedence, which are generally the same as
those followed in algebra:
((a+b)+c)
34
Precedence Of Arithmetic Operators.
35
Example:
#include<stdio.h>
main()
int x,y,z;
z=x-y;
36
//Program that shows how to multiply 2 numbers.//
#include<stdio.h>
main()
int p,q,r;
scanf("%d%d",&p,&q);
r=p*q;
#include<stdio.h>
main()
float a,b,c;
37
clrscr();
printf("Enter a, b values\n");
scanf("%f%f",&a,&b);
c=a/b;
/* Modulus operator */
#include <stdio.h>
main()
z = x % y;
38
2.6: Equality and Relational Operators
They all have the same precedence. Just below them in precedence are the
equality operators:
== !=
Note:
A simple relational expression contains only one relational operator and takes the
following form. exp1 relational operator exp2
39
Relational operators in C are in Table
Relational Operators
Equality Or Sample C Meaning Of C
> > x>y x is greater than
Condition Condition
Relational Operator y
< < x<y x is less than y
>= x >= y x is greater than
or equal to y
<= x <= y x is less than or
equal to y
Equality Operators
= == x == y x is equal to y
!= x != y x is not equal to
y
40
Logical Operators
C has the following logical operators; they compare or evaluate logical and
relational
expressions.
Symbol Name
&& Logical
|| Logical OR
AND```````````
! Logical NOT
operators simultaneously. If both the expressions to the left and to the right of
the logical operator is true then the whole compound expression is true.
Example
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole
expression is true only if both expressions are true i.e., if a is greater than b
and x is equal to 10.
41
Logical OR (||)
Example
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them
are true. It evaluates to true if a is less than either m or n and when a is less
than both m and n.
The logical not operator takes single expression and evaluates to true if the
For example
! (x >= y) the NOT expression evaluates to true only if the value of x is neither
42
Example
#include <stdio.h>
int main()
printf( "enter two integers, and I will tell you \n") ; printf("the relationships
they satisfy:\n "); scanf("%d%d", &num1,&num2);
if(num1==num2)
else if(num1!=num2)
else if(num1<num2 )
else
if (num1>num2)
if(num1 <=num2)
else
if (num1 >=num2)
return 0 ;
44
Chapter Three:
Objectives:
Outline:
If Statement
To conditionally execute statements, you can use the if for three forms :
2- if...else statement.
If (expression)
{
s1 ;
s2 ;
....
Example:
#include <stdio.h>
main()
int age;
scanf("%d",&age);
if(age >=15)
}
Example:
/* One way selection -To enter a number and print that if that is more than
100*/
#include<stdio.h>
#include<conio.h>
main()
int no;
clrscr();
scanf("%d",&no);
if(no>100)
getch();
else
Example:
#include <stdio.h>
void main()
{
int i = 5;
if(i > 0)
{
printf(" i > 0. \n");
}
else
{
printf(" i < 0. \n");
}
}
Example:
#include <stdio.h>
main()
int age ;
scanf("%d",&age);
if(age >=15)
else
}
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int no1,no2;
clrscr();
printf("Enter the two numbers :"); scanf("%d%d",&no1,&no2); if(no1>no2)
printf("%d is the greatest",no1);
else
printf("%d is the greatest",no2);
getch();
}
Example:
#include<stdio.h>
#include<conio.h>
main()
int no;
clrscr();
scanf("%d",&no);
if(no>0)
else
getch();
}
Example:
#include<stdio.h>
#include<conio.h>
main()
char al;
clrscr();
scanf("%c",&al);
else
getch();
}
3.3: Nested If Selection
Example:
Example:
#include<stdio.h>
main()
int sno,sub1,sub2,sub3,total;
char name[10];
float avg;
avg=total/3;
printf("\n");
else
}
Example:
#include<stdio.h>
#include<conio.h>
main()
int no1,no2,no3;
clrscr();
else
}
getch();
Example:
#include <stdio.h>
int main(void)
int number = 0;
scanf("%d",&number);
if (number > 5)
if (number < 6)
return 0;
}
3.4: Multiple Selections Using Switch
Syntax:
switch(variable)
Example:
#include<stdio.h>
main()
int no;
scanf("%d", &no);
switch(no)
case 1:
printf("\n The color is RED...");
break;
case 2:
break;
case 3:
break;
case 4:
break;
default:
}
Chapter Four:
Objectives:
Outline:
4.4: Assignments
Looping Control Structure:
1. While
2. Do-While
3. For
Syntax:
statement ;
}
Increment/Decrement Arithmetic Operator:
Example :
i =9;
i++;
i =9+1;
i = 10;
Example:
i =9;
i--;
i =9-1;
i = 8;
Example:
#include<stdio.h>
#include<conio.h>
main ()
clrscr();
i++; /* incremrnt */
getch();
}
Example:
#include<stdio.h>
#include<conio.h>
main()
int i=1;
clrscr();
while(i<=100)
printf("%d\t",i);
i++;
getch();
}
Example:
//Program that shows how to print 1-100 even numbers using while
loop//
#include<stdio.h>
main()
int i=2;
while(i<=100)
printf(“%d\n”, i);
i=i+2;
Example:
#include<stdio.h>
main()
int i=20;
while(i>=1)
printf(“%d\n”, i);
i=i-2;
Example:
#include<stdio.h>
#include<conio.h>
main()
int no,i=1;
clrscr();
scanf("%d",&no);
while(i<no)
getch();
}
4.2: Do-While Statement:
In while loop first it checks the condition then it prints the value. But in do-
while first it prints the value and it checks the condition.
Syntax:
do
statements;
increment / decrement
while(expression);
Example:
#include<stdio.h>
main()
{
int i=1;
do
{
printf("%d\n", i);
i++;
}
While (i<=100);
}
Example:
#include<stdio.h>
#include<conio.h>
main()
int i=1;
clrscr();
do
printf("%d\t",i);
i++;
while(i<=100);
getch();
}
4.3: For Statement
Syntax
For = keyword
Examples:
#include<stdio.h>
main()
int counter=1 ;
Return 0 ;
}
Examples:
#include<stdio.h>
main()
int i=1 ;
printf("%d\t”,i);
Examples:
Examples:
#include<stdio.h>
#include<conio.h>
main()
int i;
clrscr();
getch();
}
Examples:
10 25
1 7
100 200
*/
#include<stdio.h>
#include<conio.h>
main()
clrscr();
scanf("%d",&start);
scanf("%d",&end);
i=start*end ;
printf("%d\t",i);
getch();
}
Examples: